9.1 $ object and ajax method in jQuery

jQuery also has a special global object for working with the network. As you can guess, it's called $. Yes, that's the name. But it's simple and convenient.

Let's say you want to send a request to an API in your JavaScript and process the received response. This can be done like this:

  type: "POST",
  url: "api.codegym.cc",
  data: {name: 'Bill', location: 'Radmond'},
  success: function(msg){
    alert( "Person found: " + msg );

That's it, that's all the code. $We call the method on the object ajax(), where we pass the object that describes everything we need: both the request and the response.

  • The field typespecifies the type of HTTP request: GETorPOST
  • The field urlspecifies urlto which the request will be sent.
  • The field dataspecifies the request data in JSON format
  • The success field specifies a function to be called after a successful response from the server.

9.2 Useful queries

But if you do not need to transfer any data, then the request can be written even shorter. For example, you can write a simple POST request like this :

$.post("ajax/test.html", function( data ) {
  $( ".result" ).html( data );

Do you know what the code does $( ".result" ).html( data );? Let's try to guess...

It finds an element with the result class in the document, and adds HTML code inside it - data data. So in a couple of lines you can download data from the server and add it to your page. Well, isn't it a beauty? :)

A GET request can also be written in a couple of lines:

$.get("ajax/test.html"., function( data ) {
  $( ".result" ).html( data );

Would you like to download and execute a script?

  method: "GET",
  url: "test.js",
  dataType: "script"

Get the latest HTML page?

  url: "test.html",
  cache: false
  .done(function( html ) {
    $( "#results" ).append( html );

There is some very good jQuery documentation on the internet:

jQuery API


In addition, all common questions are easily googled and are on StackOverflow.