jQuery - AJAX get() and post() Methods (code error)


The jQuery methods called get() and post() are used to ask the server for information using either an HTTP GET or POST request.


HTTP Request: GET vs. POST

In web communication between a user's device and a remote computer, there are two main ways to exchange information: GET and POST.

  • GET - Requests data from a specified resource
  • POST - Submits data to be processed to a specified resource

The GET method is mainly used to fetch information from a server. Please note that using GET may retrieve cached data.

You can use POST to receive data from the server. But remember, POST doesn't save data, and it's commonly used to send data with a request.


jQuery $.get() Method

The $.get() function asks the server for information using an HTTP GET request.

Syntax:

$.get(URL,callback);

The "required URL parameter" tells the computer the web address you want it to visit.

The "optional callback parameter" is a function's name. It runs when the request is successful.

In this example, we use the $.get() method to get information from a file on the server.

The initial part of $.get() is where we specify the web address we want to visit, which in this case is "demo_test.asp."

The second thing you need is a callback function. The first part of this function holds the content of the requested page, and the second part holds information about whether the request was successful or not.

Hint: This is what the ASP file ("demo_test.asp") looks like:

<%
response.write("This is some text from an external ASP file.")
%>

jQuery $.post() Method

The $.post() method sends data to the server with an HTTP POST request.

Syntax:

$.post(URL,data,callback);

The URL parameter is the web address you want to request.

The optional data parameter specifies data to send with the request.

The optional callback parameter is the function name that runs when the request succeeds.

Here's an example that uses the $.post() method to send data with the request:

The first parameter of $.post() is the URL we want to request ("demo_test_post.asp").

Next, we include some data (name and city) to send with the request.

The ASP code in "demo_test_post.asp" takes in the inputs, works on them, and gives back an outcome.

The third parameter is a callback function. The first callback parameter contains the content of the requested page, and the second callback parameter contains the status of the request.

Tip: Here is what the ASP file ("demo_test_post.asp") looks like:

<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>