jQuery scope or race condition in AJAX/getJSON

By : slim
Source: Stackoverflow.com
Question!

I have a piece of jQuery code which invokes several getJSON() calls in quick succession:

var table = $("table#output");
for (var i in items) {
    var thisItem = items[i];
    $.getJSON("myService", { "itemID": thisItem }, function(json) {
        var str = "<tr>";
        str += "<td>" + thisItem + "</td>";
        str += "<td>" + json.someMember + "</td>";
        str += "</tr>";
        table.append(str);
    });
}

When I run this against a laggy server, the table gets populated with the expected json.someMember values (they arrive out of order: I don't mind that), but the thisItem column is populated with an unpredictable mixture of values from various iterations.

I'm assuming this is something to do with scope and timing - the callback function is reading thisItem from a wider scope? Am I right? How do I prevent this?

My current workaround is for the JSON service to return a copy of its inputs - which is unsatisfying to say the least.

By : slim


Answers

Javascript does not use block for scope. Scope is only based on functions.

If you want a new scope, you have to declare a new internal function and run it immediately, this is the only way to create a new scope in Javascript.

var table = $("table#output");
for( var i in items ) 
{
    (function(){
        var thisItem = items[i];
        $.getJSON("myService", { "itemID": thisItem }, function(json) 
    	{
            var str = "<tr>";
            str += "<td>" + thisItem + "</td>";
            str += "<td>" + json.someMember + "</td>";
            str += "</tr>";
            table.append(str);
    	});
    })();
}


This sounds a lot like a character encoding issue. The response containing the pound sign is being sent in the UTF-8 character set, but is being interpreted in a different character set (probably ISO-8859-1).

Check what character encoding you are specifying for your JSP, and if the problem still persists, use a sniffer to investigate the response that the form posts, and specifically any character set it specifies. By default the form should use the same character set as the page it was served on, so you should be able to control it by checking the page's character set.



I know you asked for ASP.NET resources. The Facebook Connect page provides some good information as well as the source to a sample implementation using PHP. Hopefully you can pull some good information from the PHP code.

http://developers.facebook.com/connect.php Check out the links on the right side.

The provided demo can be accessed here... http://www.somethingtoputhere.com/therunaround/

By : JWD


This video can help you solving your question :)
By: admin