简体   繁体   中英

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.

Use param dataType for access to field status

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

Try this

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM