0

I am returning a JSON array to my jQuery function script, but cannot seem to get the syntax correct -- even after reading about a dozen different examples here.

Here is the calling jQuery ajax function:

$.ajax({
    url: "fetchAlleles.php",
    datatype: 'json',
    data: {'mndx': mndx, 'sndx': sndx },
    success: function(rtnval) {
      alert("success: allele_1="+rtnval['allele_1']+", allele_2="+rtnval['allele_2']);
      //alert(rtnval);
    },
    error: function() { alert('Error!'); }
    });

Here is the PHP code that returns the values:

echo "{";
echo "allele_1: ", json_encode($ary[0]), "\n";
echo "allele_2: ", json_encode($ary[1]), "\n";
echo "run_date: ", json_encode($ary[2]), "\n";
echo "}";

If I use my alert debugging statement, I can see what's being returned is what I expect:

{allele_1: "440"
allele_2: "480"
run_date: null
}

but anything else I try to read the values inside the JSON object comes back "undefined", whether it's

alert("success: allele_1="+rtnval['allele_1']+", allele_2="+rtnval['allele_2']);

or

alert("success: allele_1="+rtnval.allele_1+", allele_2="+rtnval.allele_2);

or

alert("success: allele_1="+rtnval['allele_1'][0]+", allele_2="+rtnval['allele_2'][0]);

Hope someone can help -- this is exasperating! (Wish JSON syntax were more obvious!)

thanks much, rixter

7 Answers 7

3

Your JSON content doesn't appear to be valid JSON - you should have quotes around the field names like

{ "allele_1": "value", ... }
Sign up to request clarification or add additional context in comments.

1 Comment

more important, it's missing the comma's :)
2

If you make datatype -> dataType your json will be parsed by jQuery.

$.ajax({
    url: "fetchAlleles.php",
    dataType: 'json',
    data: {'mndx': mndx, 'sndx': sndx },
    success: function(rtnval) {
      alert("success: allele_1="+rtnval['allele_1']+", allele_2="+rtnval['allele_2']);
      //alert(rtnval);
    },
    error: function() { alert('Error!'); }
});

Comments

2

The PHP json output is invalid because it does not contain commas.

Change php output to:

echo json_encode(array(
    'allele_1' => $ary[0],
    'allele_2' => $ary[1],
    'run_date' => $ary[2]
));

Comments

1

Use jQuery.parseJSON to make this easier http://api.jquery.com/jQuery.parseJSON/

Here's their example:

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name ); //John

Comments

1

use JSON.parse(rtnVal) this function is available in all latest browsers and converts string to JSON

Comments

1

Ok so there are two things I want to suggest to you.

First of all. When you are returning your values from PHP back to JavaSctipt, you'll only need to perform one json_encode() command. Simply build your data in a regular PHP array (yes, it can be nested arrays).

Just execute one echo json_encode($data) at the end of your script.

Secondly, you'll want to access that data with JavaSctipt using dot syntax if you are dealing with an object. You can use the square brackets (key) syntax when dealing with an array.

  • { 'key1':'value1' }
    Here you would use data.key to get value1

  • { 'key1':[ 'array_value1', 'array_value2', ... ] }
    Here you would use data.key1[1] to get array_value2.

Comments

1

First of all, like others have mentioned, your JSON is not valid. It should be something like:

{
"allele_1": "440",
"allele_2": "480",
"run_date": null
}

if you're not sure about your json, try using something like jsonlint, it checks it for you.

The way you are using json_encode() in php also seems a bit odd. It would be better to put everything in a single array and json_encode the entire array once. You could recreate your json result by structuring your array in php like this:

$json_output = array(
    'allele_1' => '440',
    'allele_2' => '480',
    'run_date' => null
);

echo $json_output;

And last, the way you're accessing your $.ajax response is incorrect, you're accessing the data like it's an array, but it's an object.

success: function(rtnval) {
    alert("success: allele_1="+rtnval.allele_1+", allele_2="+rtnval.allele_2);
}

Try it like that.

2 Comments

Thanks; this was helpful. But the "new array" in PHP should just be "array". Plus, the object notation only worked when I ran it through jQuery.parseJSON()...see below...but thanks again. --rixter
You're welcome, you are right about "new array" I've made an edit, I make this mistake a lot when it comes to PHP, thanks for the notice :) I thought that JQuery would take care of the parsing of the json itself when you entered 'json' as the datatype, and now I see why this didn't worked out for you. It's because you've entered 'datatype' and it should have been 'dataType' you've missed the capital T, so the parseJSON() step would not have been necessary, like Kevin B already mentioned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.