I’m using .getJSON to send a search query to my PHP server and am returning an array which has been json_encode’d. I’d like to use the resulting object after the jQuery function completes (ideally, pushing it into an array, and use it like any other object elsewhere in the page.
But, the object ceases to exist after the function completes. This is a success:
var widgets = new Array();
$.getJSON('/server.php', {query: search.value}, function(response) {
widgets.push(response);
alert('value of result's attribute1 is ' + widgets[widgets.length].attribute1);
});
However as soon as I leave the function, widgets.push[length] becomes null, and I can’t access anything about the push’ed object. I would think this would be a copy and not a reference?
My application involves the user doing several of these searches in order to create a list of widgets, and then working between each object’s attributes. Is there an accepted way to make this data persistent after the function completes?
The getJSON call is happening asynchronously or independent of the rest of your JavaScript. Your issue is most likely because your getJSON call is not completed before your are attempting to manipulate your widgets array.
You need to make sure any manipulation of widgets occurs after getJSON has completed.
Part of the getJSON syntax allows you to add a callback function when the call succeeds. See http://api.jquery.com/jQuery.getJSON/. Put your ALL your widget maniuplation code in “success”.