views:

24

answers:

2

Hi,

I beginer in javascript and jquery soo my question about understanding of javascript syntax.

Why in ajax jquery function - should be writen function success:function (){myfun();} and not directly success:myfun() ?

Working:

$.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: data,
        success: function(data) {
            alert(data);
        }
});

Not Working:

$.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: data,
        success: alert(data)
});

Thanks

+2  A: 

In short, because you're executing alert() and trying to assign the result to the success callback, so this won't work (the result of alert() is undefined). However you can do this:

$.ajax({
    type: 'POST',
    url: 'http://www.myurl.com',
    data: data,
    success: customFunc //*not* customFunc() which would call it
});

In this case customFunc will receive the same parameters as success passes, so it's signature should be: customFunc(data, textStatus, XMLHttpRequest), though it can be a subset, for example customFunc(data).

Nick Craver
+5  A: 

You can do that. You just using the wrong syntax.

The success property needs a function expression not a function() call (which then returns a value into success);

So

success: myfunction

instead of

success: myfunction()
jAndy