Jquery Ajax Request Example

Posted on  by admin

The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.

jQuery AJAX Reference

Two commonly used methods for a request-response between a client and server are: GET and POST. GET - Requests data from a specified resource.

POST - Submits data to be processed to a specified resource. GET is basically used for just getting (retrieving) some data from the server.Note: The GET method may return cached data.

POST can also be used to get some data from the server.
However, the POST method NEVER caches data, and is often used to send data along with the request. To learn more about GET and POST, and the differences between the two methods, please read our HTTP Methods GET vs POST chapter. The $.get() method requests data from the server with an HTTP GET request. The required URL parameter specifies the URL you wish to request. The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the $.get() method to retrieve data from a file on the server:.
$("button").click(function(){ $.get("demo_test.asp", function(data, status){ alert("Data: " + data + "\nStatus: " + status); });});.
Try it Yourself ». The first parameter of $.get() is the URL we wish to request ("demo_test.asp").
The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
Tip: Here is how the ASP file looks like ("demo_test.asp"):.
<%response.write("This is some text from an external ASP file."
The $.post() method requests data from the server using an HTTP POST request.
The required URL parameter specifies the URL you wish to request.
The optional data parameter specifies some data to send along with the request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the $.post() method to send some data along with the request:. $("button").click(function(){ $.post("demo_test_post.asp", { name: "Donald Duck", city: "Duckburg" }, function(data, status){ alert("Data: " + data + "\nStatus: " + status); });});.
Try it Yourself ». The first parameter of $.post() is the URL we wish to request ("demo_test_post.asp").
Then we pass in some data to send along with the request (name and city).
The ASP script in "demo_test_post.asp" reads the parameters, processes them, and returns a result.
The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
Tip: Here is how the ASP file looks like ("demo_test_post.asp"):.
<%dim fname,cityfname=Request.Form("name")city=Request.Form("city")Response.Write("Dear " & fname & ".
")Response.Write("Hope you live well in " & city & "."
For a complete overview of all jQuery AJAX methods, please go to our jQuery AJAX Reference.
Modified2 years, 9 months ago. I am making this simple get request using jquery ajax:.
It's returning an empty string as a result. If i go to this link in my browser, i get:.
which is the expected result. So why isn't it working using ajax?thanks!
3131 gold badges130130 silver badges250250 bronze badges.

Example

250250 bronze badges. You can make AJAX requests to applications loaded from the SAME domain and SAME port.

Conclusion

Besides that, you should add dataType JSON if you want the result to be deserialized automatically.

jQuery $.post() Method

22 gold badges2424 silver badges2929 bronze badges. 2929 bronze badges. It seems to me, this is a cross-domain issue since you're not allowed to make a request to a different domain. You have to find solutions to this problem:- Use a proxy script, running on your server that will forward your request and will handle the response sending it to the browserOr- The service you're making the request should have JSONP support.

This is a cross-domain technique. You might want to read this http://en.wikipedia.org/wiki/JSONP. 3131 bronze badges. 94222 gold badges66 silver badges1717 bronze badges. 66 silver badges1717 bronze badges. 3535 bronze badges. i think the problem is that there is no data in the success-function because the request breaks up with an 401 error in your case and thus has no success.

  • there will be your 401 code i think (this linksays so). Matthew FisherMatthew Fisher.
  • Description: Perform an asynchronous HTTP (Ajax) request. A string containing the URL to which the request is sent.
  • Type: PlainObject. A set of key/value pairs that configure the Ajax request.
  • All settings are optional. A default can be set for any option with $.ajaxSetup().
  • See jQuery.ajax( settings ) below for a complete list of all settings.
Type: PlainObject. A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().

Type: PlainObject. A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept request header.

jQuery.ajax( url [, settings ] )Returns: jqXHR

This header tells the server what kind of response it will accept in return. For example, the following defines a custom type mycustomtype to be sent with the request: Note: You will need to specify a complementary entry for this type in converters for this to work properly.

Examples for the jQuery ajax() function

Recommended Articles

Send Http POST request using ajax()

async (default: true). By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

jQuery $.get() Method

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done(). Type: Function( jqXHR jqXHR, PlainObject settings ).

Working of the ajax() function

A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent.

Parameters

Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request.

As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. cache (default: true, false for dataType 'script' and 'jsonp').

Additional Notes:

If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests.

It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

version added: 1.0jQuery.ajax( [settings ] )

Type: Function( jqXHR jqXHR, String textStatus ). A function to be called when the request finishes (after success and error callbacks are executed).

Extending Ajax

The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror").

Callback Function Queues

As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn.

Introduction to jQuery ajax request

This is an Ajax Event. Type: PlainObject. An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5). contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8'). When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases.

If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent).

As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.

Send Ajax Request

Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server. Type: PlainObject. This object will be the context of all Ajax-related callbacks.

By default, the context is an object that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so: .

converters (default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}).

  • An object containing dataType-to-dataType converters.
  • Each converter's value is a function that returns the transformed value of the response. (version added: 1.5). crossDomain (default: false for same-domain requests, true for cross-domain requests).
  • If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true.

HTTP Request: GET vs. POST

This allows, for example, server-side redirection to another domain. (version added: 1.5). Type: PlainObject or String or Array.

Sending Data to the Server

Data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL. When data is an object, jQuery generates the data string from the object's key/value pairs unless the processData option is set to false.

For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf".

The jqXHR Object

If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.

When data is passed as a string it should already be encoded using the correct encoding for contentType, which by default is application/x-www-form-urlencoded. In requests with dataType: "json" or dataType: "jsonp", if the string contains a double question mark (??) anywhere in the URL or a single question mark (?) in the query string, it is replaced with a value generated by jQuery that is unique for each copy of the library on the page (e.g.

Type: Function( String data, String type ) => Anything. A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter.

dataType (default: Intelligent Guess (xml, json, script, or html)). The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

Advanced Options

The available types (and the result passed as the first argument to your success callback) are: "xml": Returns a XML document that can be processed via jQuery." html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM."

script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, _=[TIMESTAMP], to the URL unless the cache option is set to true.

Note: This will turn POSTs into GETs for remote-domain requests.

Prior to jQuery 3.5.0, unsuccessful HTTP responses with a script Content-Type were still executed."

Recommended Reading: