1

i have 2 conditions that return as json like this

public funtion do_upload{
//1st
return json_encode(['upload_success' => 'Successfully import ' . $count_validEntries . ' document]);

//2nd
return json_encode(['upload_error' => 'Your document is not valid, at row '. $implode_err. 'Please use given data']);
}

my Ajax Call

  $("#upload_btn").on('click', function(){
    var mydata = new FormData(document.getElementById("form_upload"));
    $.ajax({
      type : "POST",
      data: mydata,
      contentType: false,
      dataType : "json",
      url : "<?php echo base_url();?>/C_MRCR_A/do_upload",
      cache: false,
      processData: false,
      beforeSend:function(){
      },
      success:function(response){
        console.log('succ ',response);
      },
      error:function(xhr, status, error){
      },
      complete:function(){
        // do nothing for now
      }
    });
  });

i want to make alert success if 'upload_success' and alert error if 'upload_error' using response above? or is there any other way?

pramudityad
  • 57
  • 1
  • 8

1 Answers1

0

You need to apply conditions in success function. like below -

success:function(response){
    //console.log('succ ',response);
    if(response.upload_success){
      $('#response').html('<div class="alert alert-success" role="alert"> T'+response.upload_success+' </div>');
    } else if(response.upload_error){
      $('#response').html('<div class="alert alert-success" role="alert"> '+response.upload_error+' </div>');
    }
}

Create a div in your HTML to show response.

<div id="response"></div>

Either you can append/show this response wherever you want.

Alok Mali
  • 2,821
  • 2
  • 16
  • 32
  • applied . but why is not display the alert? i place `
    ` outside the modal
    – pramudityad Apr 20 '20 at 11:46
  • put the div in the model. and please make sure it's id is unique in your HTML file – Alok Mali Apr 20 '20 at 12:46
  • put the div in the modal and `id` its unique. still dont appear any alert. i tried to `console.log(response.upload_success)` it show `undifined`. but why? – pramudityad Apr 20 '20 at 13:15
  • You need to echo your result at the server end instead of return. After this change please console the response in your success function. – Alok Mali Apr 20 '20 at 14:15
  • yeah did that to like this `echo json_encode(['upload_success' ...` but my console.log dont get anything, cause it always go to `error:function(xhr, status, error)` in ajax not the`success:function(response)` – pramudityad Apr 21 '20 at 04:47
  • It means you have another issue with your ajax. Maybe ajax is unable to hit the given URL or it is wrong. – Alok Mali Apr 21 '20 at 05:12
  • it's strange. im sure the URL is fine, beacuse when i use `return` it goes to `success:function(response)` – pramudityad Apr 21 '20 at 05:50