0

I am new to jquery and am trying to trouble shoot some code and i have come across the following:

jQuery.get( url , { valids : val } , function( data ) {
            if(data == 'success') {
                $("#asearch_form").submit();
                alert('Record Updated Successfully');

            }else{
                alert('Something went wrong');

            }
        });

Can someone please tell me what the "function (data)" part of this code means? Is (data) a user created or is it a built in jquery function? I see that data is tested to see if it equals success or error but I don't see where "data" is set to either success or error.

Juan Velez
  • 741
  • 5
  • 15
  • 29
  • it's a success function – mamdouh alramadan Apr 08 '14 at 14:42
  • You are passing the `$.get()` function a(n) (anonymous) "callback" function. jQuery will call this function (and send it the data returned from the AJAX call) when the AJAX call is done. `data` is just the parameter in the function's signature. – gen_Eric Apr 08 '14 at 14:42
  • 2
    It's a function definition for a function accepting one argument, referred to by the name `data`. The function will eventually be called by jQuery and gets passed the response of the Ajax call. To see where the function is called, you have to look into jQuery's source code. – Felix Kling Apr 08 '14 at 14:43
  • possible duplicate of [Getting a better understanding of callback functions in JavaScript](http://stackoverflow.com/questions/483073/getting-a-better-understanding-of-callback-functions-in-javascript) – Felix Kling Apr 08 '14 at 14:47

1 Answers1

3

Check out the documentation for $.get. The method signature looks like this:

jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

So the way you're using it you're passing url, { valids: val } and then a "success" function that accepts a data parameter.

The documentation describes success as "A callback function that is executed if the request succeeds."

This means that when the asynchronous request has completed successfully, jQuery will call the function you supply to $.get with the data it retrieved from the server, along with textStatus and jqXHR (which the function you've defined in your example happens to be ignoring).

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • 3
    It's worth noting that function is only called for a successful ajax call. If there's a server error of some kind, the "success" function is not called at all. The documentation Andrew linked also describes how to handle that situation. – Dave Apr 08 '14 at 14:49