jQuery getJSON call not returning desired arguments?
A couple of issues there:
getJSON
does an ajax request. Ajax requests are subject to the Same Origin Policy. Unless your page is loaded fromhttp://test.com
(or a couple of other caveats), it won't work. You're probably looking for JSON-P (which jQuery also supports), provided the server supports it.getJSON
, like all ajax requests, is asynchronous by default, so your second alert (with the user list) will happen before the request completes. Although you can make ajax requests synchronous, it's a very bad idea (locks up the UI of most browsers during the request). Instead, just use the user list after you've received it in the callback, rather than trying to use it in the function callinggetJSON
.
Edit: You've said below that you're trying to use the Twitter search API. That API does support JSON-P, so if you use JSON-P to do your request, it should work. e.g.:
$(document).ready(function(){
$("#inputForm").submit(function(event){
$(":text").each(function() {
var inputText = $(this).val();
var userList = [];
var weblink = 'http://search.twitter.com/search.json?q=&ands=google';
// problem is from here.
$.ajax({
url: weblink,
dataType: "jsonp", // <== JSON-P request
success: function(data){
alert(weblink); // this statement doesn't show up
$.each(data.result, function(entryIndex, entry){ // <=== Note, `data.results`, not just `data`
userList.push(entry['from_user']); // <=== Or `entry.from_user` would also work (although `entry['from_user']` is just fine)
});
alert(userList); // <== Note I've moved this (see #2 above)
}
});
});
});
});
...but surely you don't want to do that for each text field in the form?
Here's a live example but without a form (and only doing one request, not a request for each field).
Just add to link
&callback=?
or
?callback=?
(if it's first and only GET variable) This will make your call into JSONP call, which doesn't have problems with Same Origin Policy.