I’m having a problem trying to return a specific record using jQuery and JSON. I’m passing a variable to the function and want to output only the data matching the id I’ve set when the function is executed.
Right now, my function looks like this:
function getEffectsData(myNum){
$.getJSON("jsonscript.php", { id: +myNum },function(data){
var x = data.x;
//DO SOME STUFF
});
}
The JSON output looks like this:
{"stuff": [ { "id":1, "x":3, "y":6, "z":-6 },{ "id":2, "x":2, "y":7, "z":-3 }]}
The only thing I know is that the correct variable is being passed to the function. After that, nothing happens. Very new at this, so any help is greatly appreciated.
EDIT:
I appreciate everybody’s input on this. To clarify, I am trying to return the data from only the object that’s id matches myNum. I want to be able to access all of the data from that object, but only that object. I have no idea where that object will be in the array. I simplified the ids and the data in my question to help clarify the problem.
Thanks again.
You can access x from your JSON like this:
Because your JSON tree looks like this:
So with
data.stuff[0].xyou selectstuffobject then it’sfirstelement and then itsxkey.But If you want to handle all the
xkey for example, then you need to loop through thestuffarray by a simpleforloop or the$.eachmethod.As for your question. If you want to get the object with id
myNumyou have 2 possibilities:if you possess
jsonscript.phpyou can send the data only with the correct id from the server, because you pass the id to it by{ id: +myNum }which is the second parameter ofgetJSONYou loop through the data until you find the object with the correct id