jQuery's JSON Request

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

Answers


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

header('Content-Type: application/json');

Need Your Help

Serving https video on http pages

html iframe https youtube

My website has some embedded Youtube videos where the embed URL uses http and the webpage is also served through http. Some of my users (i.e. using Google Chrome on Windows) have told me that the ...

C++ User defined string needs to contain spaces (but not allowed by program..?)

c++ string

I'm working on homework for my c++ class, and it's been quite awhile since I've used it. I was wondering if there was a way to allow spaces in a string (instead of it nulling out and ending the str...