claudios claudios - 6 months ago 20
Ajax Question

Passing data to ajax call on success

I wanted to pass the data from

json_encode()
function into jquery. And on success I wanted to reload the specific div.

Trigger:

<a id="js-delete-file" href="#" data-url="<?php echo site_url('document_items/remove/'. $value['id'].'/'. $value['filename']) ?>">Remove</a>


PHP:

public function remove ($id=null, $filename) {

$dir = "_resources/docs/";
if ($this->doc_item->remove($id)) {
unlink($dir.$filename);
$status = 'success';
$msg = 'File successfully deleted';
} else {
$status = 'error';
$msg = 'Something went wrong when deleting the file, please try again';
}

echo json_encode(array('status' => $status, 'msg' => $msg));
}


JQUERY:

$('#js-delete-file').click(function(e){

var url = $(this).attr('data-url');
$.ajax({
type: 'POST',
url: url,
success: function(result) {
$('#uploaded-files').html(result);
},
});
});


after I click the button it will give me this
{"status":"success","msg":"File successfully deleted"}
instead of the actual html.

Answer

Use param dataType for access to field status

$.ajax({
      type: 'POST',
      url: url,
      dataType: "json",
      success: function(result) {
        $('#uploaded-files').html(result.status);
      }
    });
Comments