There are several problems:
getJSON
executes an ajax request. Ajax requests are subject to policies of the same origin . If your page is not loaded from http://test.com
(or several other caveats), it will not work. You are probably looking for JSON-P (which also supports jQuery) if the server supports it.
getJSON
, like all ajax requests, is asynchronous by default, so your second warning (with a list of users) will occur before the request completes. Although you can make ajax requests synchronous, this is a very bad idea (it blocks the user interface of most browsers during the request). Instead, just use the user list after you got it in the callback, instead of trying to use it in the function that calls getJSON
.
Change You said below that you are trying to use the Twitter Search API. This API supports JSON-P, so if you use JSON-P to fulfill your request, it should work. eg:.
$(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
... but you do not want to do this for each text field in the form?
Here is a live example , but without a form (and only one request, not a request for each field).
Tj crowder
source share