DataType: "json" will not work

I am trying to send multiple variables from a php file to ajax using json in an array. The code in the php file works fine and does everything with my database as it should. But as soon as I add dataType: "json" to ajax, nothing else happens in the php file. I did a bit of work on Google, and some people mentioned that this might be a problem with the browser, but so far it doesn't work in firefox, chrome, or IE. I am using the latest version of jQuery.

This is what happens inside php:

<?php
//Create variables and update database

echo json_encode(array("id" => "$realid", "un" => "$username", "date" => "$date"));
?>

And this is the ajax code:

.ajax(
{
   url: 'UpdateComments.php',
   type: 'POST',
   dataType: "json",
   data: 
   {
      type: "add",
      comment: $("#comment").val(),
      id: videoID  
   },
   success: function (data) 
   {
       //Get the data variables from json and display them on page
   }
});

I do not know about this, any advice will be very grateful!

+5
source share
5 answers

, "- " JSON, () char. - :

<?php
//at the very beginning start output buffereing
ob_start();

// do your logic here

// right before outputting the JSON, clear the buffer.
ob_end_clean();

// now print
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date));
?>

( JSON) , ...

+6

, dataType, contentType, " - JSON - /json ".

.ajax(
{
 url: 'UpdateComments.php',
 type: 'POST',
 contentType: "application/json",//note the contentType defintion
 dataType: "json",
 data: 
 {
   type: "add",
   comment: $("#comment").val(),
   id: videoID  
 },
 success: function (data) 
 {
   //Get the data variables from json and display them on page
 }
});
+1

jQuery, Content-Type. , PHP script MIME . , PHP , ? , , Firefox, Chrome IE.

To get a more accurate estimate of your AJAX request, subscribe to ajaxBeforeSend (not sure if the event name is checking jQ docs correctly) and register the xhr object.

0
source

I would not use dataType if it causes problems, also I personally did not use the object as a data value, before, perhaps, something is connected with this?

In any case, I changed the basic ajax routine, hope this helps.

$.ajax(
{
   url: 'UpdateComments.php',
   type: 'POST',
   data: 
   {
      type: "add",
      comment: $("#comment").val(),
      id: videoID  
   },
   success: function (response) 
   {
       //Get the data variables from json and display them on page
       var data = $.parseJSON(response);
       alert(data.id);
   }
});
0
source

Try defining an error handler as part of the $ .ajax call

$.ajax({
  ...,
  error: function(xml, error) {
    console.log(error);
  }
});

Then check the debug console for errors that may help you diagnose the problem.

0
source

All Articles