Gandalf
Gandalf

Reputation: 13693

Specify function to be called in jquery

I have come across this snippet in the jquery post documentation and i am not sure what it does

$.post("test.php", { "func": "getNameAndTime" },
 function(data){
   console.log(data.name); // John
   console.log(data.time); //  2pm
 }, "json");

My thinking is that test.php has a function getNameAndTime(),is this the meaning of it?.If so is this some kind of javascript pattern?.

Upvotes: 2

Views: 101

Answers (3)

Chen Harel
Chen Harel

Reputation: 10062

{ "func": "getNameAndTime" } is a JS object that is parsed to a string and then sent to the server. test.php handles POST requests and the data passed on to that servlet is taken from data. Take another look at jQuery.post()

Upvotes: 1

Shyju
Shyju

Reputation: 218872

That means, this script is making an asynchronous POST call to test.php page and passing a parameter called func with value getNameAndTime. then it is receiving the response from this ajax server page in a variable called data. I guess the respone is in JSON format. So in the callback function, It is accessing the name and time part from the JSON response and making a call to the console.debug function so that it will be printed in the firebug console.

The JSON may look like this

{
    "name": "Jon",
    "time": "5.30"
}

There may be additional items in the JSON. But for sure our code is expexting a name and time elements

You may refer the below resources to get a good understanding of what each item does

$.post : Load data from the server using a HTTP POST request.

JSON : Javascript Object Notation- A lightweight data-interchange format

Upvotes: 2

LeleDumbo
LeleDumbo

Reputation: 9340

From jQuery documentation:

data A map or string that is sent to the server with the request.

So it's simply an argument map to test.php, test.php might provide remote procedure call through this request, using that func argument.

Upvotes: 1

Related Questions