Question

I'm a javascript noob, and I don't understand why this works:

$().load('/my/url/', {my:data, more:data}, jsFunc());

function jsFunc()
{
    $("#myid").val("yep");
}

But not this:

$().load('/my/url/', {my:data, more:data}, function() {jsFunc()});

function jsFunc()
{
    $("#myid").val("yep");
}

I tried an $.ajax instead of $.load with the same result. I will be passing the response data to jsFunc() and that is why I need jsFunc() inside the function. I'm sure it is something simple I'm just not very experienced with javascript. Thanks.

Thanks again for all the help. I decided to use $.post because it works best for the situation but now I'm having trouble with the response data. My code looks like this:

$.post('/my/url/', {my:data, more:data}, function(data) {
    var strung = JSON.stringify(data)
    var parse = jQuery.parseJSON(strung)
    console.log(parse.some);}, 'json');

I'm logging to the console to see what is coming back for now and I will add the callback when I see the correct value logged. The process I got from the jQuery api page, but it will only log undefined. When I change parse.some to parse the console log will display the objects and I can select an element and see the correct key:value pair. Any help would be sweet.

Was it helpful?

Solution

Neither works. The first one appears to work, because you call the function jsFunc immediately, it doesn't wait for any response.

If you create an empty jQuery object using $() and use the load method on that, it won't call the server because there is no element where it can put the result.

To specify the callback function you either use the name of a function:

$('#someElement').load('/my/url/', {my:data, more:data}, jsFunc);

or a function expression:

$('#someElement').load('/my/url/', {my:data, more:data}, function() { jsFunc(); });

OTHER TIPS

The first code block will simply call jsFunc() and return the results as the parameter to the load(..) method, which is odd because that parameter is supposed to be a callback function to fire when the load completes, but that works? The callback syntax is more in keeping with the second example (the one I believe you stated doesn't work).

Answer to my second part:

My returned JSON data consisted of many objects, so I had to specify the index and the key to get the value to return.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top