jquery ajax response function code example

Example 1: make ajax calls with jQuery

// GET Request
    $.ajax({
        url: "example.php?firstParam=Hello&secondParam=World", //you can also pass get parameters
        dataType: 'json',	//dataType you expect in the response from the server
        timeout: 2000
    }).done(function (data, textStatus, jqXHR) {
        //your code here
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("jqXHR:" + jqXHR);
        console.log("TestStatus: " + textStatus);
        console.log("ErrorThrown: " + errorThrown);
    });

//POST Request
    var formData = {name: "John", surname: "Doe", age: "31"}; //Array 
    $.ajax({
        url: "example.php",
        type: "POST", // data type (can be get, post, put, delete)
        data: formData, // data in json format
       	timeout: 2000,	//Is useful ONLY if async=true. If async=false it is useless
        async: false, // enable or disable async (optional, but suggested as false if you need to populate data afterwards)
        success: function (data, textStatus, jqXHR) {
            //your code here
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("jqXHR:" + jqXHR);
            console.log("TestStatus: " + textStatus);
            console.log("ErrorThrown: " + errorThrown);
        }
    });


//Alternatively, the old aproach is
    $.ajax({
        url: "api.php?action=getCategories",
        dataType: 'json',
        timeout: 2000,
        success: function (result, textStatus, jqXHR) {   //jqXHR = jQuery XMLHttpRequest
            /*You could put your code here but this way of doing it is obsolete. Better to use .done()*/
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("jqXHR:" + jqXHR);
            console.log("TestStatus: " + textStatus);
            console.log("ErrorThrown: " + errorThrown);
        }
    });

Example 2: Call the web api from $.ajax() function.

1- Calling the web api method without parameter
•	If  you do not have parameter in your web API method then you no need to pass the data parameter inside AJAX function.
	The URL parameter of ajax function must match with the Route attribute of web api method.

o	Your web api controller action method.
       
       [HttpGet]
        [Route("student/Get")]
        public IEnumerable<string> Get()
        {
            return new string[] { "student1", "student2" };
        }

o	Your ajax function
$('#btnBindDropDown').on('click', function () {
                $('#btnBindDropDown').click(function () {
                    $.ajax({
                        type: 'GET',
                        url: 'student/Get',
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        success: function (data) {
                            alert('data is ' + data);
                        },
                        error: function () {
                            alert("INSIDE FAILURE");
                        }
                    });
                });
                
            });

2-	Now calling the web api method with  parameter


o	Your web api controller action method.

 [HttpGet]
        [Route("student/GetWithId")]
        public int Get(int Id)
        {
            return Id;
        }

o	Your ajax functionThe Id property must match with web api method parameter.


$.ajax({
                        type: 'GET',
                        url: 'student/GetWithId',
                        data: { Id: 101 },
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        success: function (data) {
                            alert('data is ' + data);
                        },
                        error: function () {
                            alert("INSIDE FAILURE");
                        }
                    });

3-	calling the web api method by passing object 

o	Your web api controller action method.

 [HttpPost]
        [Route("api/student/names1")]
        public Employee GetEmployee(Employee employee)
        {
            employee.Id = 101;
            employee.Name = "Kaushal";
            return employee; 
  }

o	Your ajax functionThe object name ‘employee’ must match with the web api method parameter
•	The URL name can be anything , But both should match.
i.e  Route attribute of web api method and URL parameter of ajax function.
	If you are passing object then you will use JSON.stringfy function.
	If webApi method is not returning anything then the parameter  dataType: 'json', 
Is optinal. This parameter is required if webapi method is returning something and you want to do something with the returned data.

$('#btnBindDropDown').click(function ()
            {
                var employee = { Id: 101, Name: "Love singh" };  
                    $.ajax({
                        type: 'POST',
                        url: 'api/student/names1',
                        data: JSON.stringify(employee),
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        success: function (data) {
                            alert('data is ' + data);
                        },
                        error: function () {
                            alert("INSIDE FAILURE");
                        }
                    });
                
            });