Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dataType: "json" won't work

Tags:

json

ajax

php

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!

like image 943
Glenn Avatar asked Apr 02 '12 23:04

Glenn


2 Answers

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...

like image 104
Jovan Perovic Avatar answered Sep 17 '22 23:09

Jovan Perovic


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
 }
});
like image 30
Travis J Avatar answered Sep 21 '22 23:09

Travis J