Search code examples
javascriptjqueryjquery-loadjquery-post

How does this javascript work?


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.


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(); });