7

I'm trying to send back multiple variables from a php file to ajax using json in an array. The code in the php file works perfectly and does everything with my database like it should. But as soon as I add dataType: "json" in ajax, nothing happens in the php file anymore. I googled a bit and some people mentioned it could be a browser problem, but so far it doesn't work in either firefox, chrome or IE. I'm 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'm clueless on this, any advice would be greatly appreciated!

Glenn
  • 479
  • 2
  • 7
  • 19
  • Check the ajax response in firebug / net panel and see what's coming from your server. – Sam Dufel Apr 02 '12 at 23:22
  • A contentType HTTP header may help – Bergi Apr 02 '12 at 23:24
  • 1
    I suspect what is being returned isn't strictly JSON - check for whitespace before or after your PHP, or anything else in the file that should not be there (hint: use 'die' right after json_encode). When you don't specify the dataType in JQuery, success = getting a response. When you do, success = getting a VALID response.... Also check your PHP version, I seem to recall json_encode was bugged in an earlier version. – Codecraft Apr 02 '12 at 23:31

7 Answers7

10

Common issue is that browser prints "something else" before JSON whether that is some readable or unreadable(invisible) char. Try doing something like this:

<?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));
?>

Now, all supplement data (before JSON) will be discarded and you should have it working...

Jovan Perovic
  • 18,767
  • 5
  • 39
  • 76
2

It's easy to forget about an echo or a var_dump() that you may have been using in the past to test how your script is working.

In my own script I had a var_dump(), which I had forgotten about, that wasn't using JSON_encode-ed text and sent plain text to the browser. This broke the dataType:"json" requirement and caused the success function not to work.

Took me a while to find the problem as I had ctrl+f(ed) for echo only and forgot about the vagabond var_dump().

printf is probably another suspect.

JoSSte
  • 2,210
  • 5
  • 25
  • 40
2

I believe if you use dataType you should be using contentType, "The official Internet media type for JSON is application/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
 }
});
Travis J
  • 77,009
  • 39
  • 185
  • 250
0
        $.ajax({
    
       url: '/route/',
       type: 'POST',
       dataType: "json",
       data: 
       {
          type: "add",
          comment: $("#comment").val(),
          id: videoID  
       },
       success: data => {console.log(data);}
    
    });
    
    <?php
    
ob_start();
    
ob_end_clean();
    
echo json_encode(array("id" => "$realid", "un" => "$username", "date" => "$date"));
    ?>
    
        
0

If you set the dataType in jQuery, that actually sets the Content-Type header attribute. Perhaps, in your PHP script you will need to declare this MIME type as accepted. Did you notice if the code even enters the PHP script when you make the request? I doubt it is a browser problem if it doesn't work in Firefox, Chrome or IE.

To gain a better perspective at your AJAX request, subscribe to the ajaxBeforeSend (not sure if the event name is right check jQ docs) event and log the xhr object.

praneetloke
  • 1,813
  • 1
  • 13
  • 13
0

I wouldn't use the dataType if it is causing you issues, also I've personally not used an object as the data value before maybe that has something to do with it?

Anyway I've tweaked the main ajax routine I 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);
   }
});
Dale
  • 9,929
  • 17
  • 33
0

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

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

Then check your debugging console for any errors that can help you diagnose the problem.

Ben Rowe
  • 26,794
  • 6
  • 50
  • 72