简体   繁体   中英

Load Json data with AJAX and PHP

I'm triing to load a json data with ajax, but it doesn't work. Everytime ajax call the error function and doesn't call the success function.

my AJAX call :

$(document).on("click", "#myMovies .btn-update", function() {
  var id = $(this).parent().data("id");

  $.ajax({
   url : 'index.php',
   type : 'POST',
   dataType: 'json',
   data : 'id=' + id + '&action=update',
   success : function(data){
      $('#updateMovie')
            .find('[name="title"]').val(data.title).end()
            .find('[name="list"]').val(data.list).end();
   },
   error : function(jqXHR, textStatus, errorThrown){
      console.log("error");
      alert(textStatus);
      alert(errorThrown);
   }

  });
});

The interessing part of index.php :

else if($_POST['action'] == "update") {
   /*getSpecificMovie($_POST['id']);
   $movies = getSpecificMovie();
   $results = Utils::secureMoviesJSON($movies);
   echo $results;*/

   header("Content-Type: application/json", true);
   $array = array(
     'title' => 'test',
     'list' => 'test');
   echo json_encode( $array, JSON_FORCE_OBJECT );
}

Anyone know where is my mistake ? Thank you for your answer.

I think the problem is at the 'JSON_FORCE_OBJECT' option. The data type the request expected is a json string. When adding JSON_FORCE_OBJECT to the json_encode function, the json string is not valid for the request.

else if($_POST['action'] == "update") {
   /*getSpecificMovie($_POST['id']);
   $movies = getSpecificMovie();
   $results = Utils::secureMoviesJSON($movies);
   echo $results;*/

   header("Content-Type: application/json", true);
   $array = array(
     'title' => 'test',
     'list' => 'test');
   echo json_encode( $array);
   die();
}

Also add a parser for the json to your javascript ( parseJSON ):

success : function(data){
    data = $.parseJSON(data);
      $('#updateMovie')
            .find('[name="title"]').val(data.title).end()
            .find('[name="list"]').val(data.list).end();
   },

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