0

I'm trying to send an AJAX request to a php file, and I want the php file to respond with a JSON object, however the AJAX function is continually failing when declare that I specifically want JSON returned. Any help will greatly be appreciated.

this is my ajax function

function getMessages(){
  $.ajax({
    type: 'POST',
    url: 'viewInbox',
    dataType: 'json',
    success: function(msg){
      //var content = data.substr(0, data.indexOf('<')); 
      populateMessages(msg);
    },
    error: function(){
      alert("ERROR");
    }
  });
}

and this is the relevant code for the php file

$message_links[] = array();
.....
while($run_message = mysql_fetch_array($message_query)){
    $from_id = $run_message['from_id'];
    $message = $run_message['message'];
    $user_query = mysql_query("SELECT user_name FROM accounts WHERE id=$from_id");
    $run_user = mysql_fetch_array($user_query);
    $from_username = $run_user['user_name'];
    $message_links[] = array("Hash" => "{$hash}", "From" => "{$from_username}", "Message" => "{$message}");
    // is that not valid json notation???
    }            
}
echo json_encode( $message_links, JSON_FORCE_OBJECT);
//$arr = array("a" => "1", "b" => "2");
//echo json_encode($arr);

UPDATE:

Well, I ended up switching the dataType request to 'html' and I am now able to actually access these values via JSON, however, I would still like to know why the php file was not returning correct JSON notation. Any insight would be awesome, cheers.

function getMessages(){
    $.ajax({
        type: 'POST',
        url: 'viewInbox',
        dataType: 'html',
        success:function(msg){
            var content = msg.substr(0, msg.indexOf('<'));
            msg = JSON.parse(content);
           populateMessages(msg);
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(errorThrown);
            alert(textStatus);
            alert(xhr);
        }
    });
}
function populateMessages(data){
    var out = '';
    var json;
    for (var i in data){
        var my_string = JSON.stringify(data[i],null,0);
        json = JSON.parse(my_string);
        alert(json.Hash);
        out += i + ': ' + my_string  + '\n';
    }
    alert(out);
}
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Lee Bo
  • 1
  • 1
  • what do you mean by failing? post the error message. – dsharew May 04 '15 at 09:12
  • You do not need to write array values in {} – Manish Shukla May 04 '15 at 09:12
  • the error is "unexpected token < ", which I assume is because it is somehow grabbing the html tags – Lee Bo May 04 '15 at 09:18
  • what does run only php file and check what is the output and no need to pass{} as manish said – Sandhya Gor May 04 '15 at 09:29
  • @LeeBo — That implies that your PHP script is returning some HTML before or after the JSON. You haven't shown enough code to tell what that is though. – Quentin May 04 '15 at 10:15
  • **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin May 04 '15 at 10:16
  • Is there a chance you're hitting the wrong url? The < could be your web page or it could be a php stack trace exception message. In chrome, open up dev tools and go to the network tab, you'll be able to see your request and look at the repsonse which will give you the full stack trace exception – dannyshaw May 04 '15 at 10:29

1 Answers1

-1

You need to set the header as json type before your echo in PHP:

header('Content-Type: application/json');
dannyshaw
  • 368
  • 2
  • 6
  • That's best practise, but setting `dataType` will cause jQuery to ignore the content-type header and process the response as JSON anyway. – Quentin May 04 '15 at 10:15