AJAX
Basics
Data
DOM
Effects
Events
Forms
jQuery UI
Plug Ins
Traversing
The jQuery ajax()
is a complete, very configurable, way to make an asynchronous HTTP request. It is the most common.
https://www.w3schools.com/jquery/ajax_ajax.asp
https://api.jquery.com/jQuery.ajax/
(more up to date)
You typically pass an object to the ajax method. Here is detailed list of valid object properties: https://www.w3schools.com/jquery/ajax_ajax.asp.
$.ajax(configObj)
// or
$.ajax({name:value, name:value, name:value... })
This test will use a GET request and call the City Info DEMO API and grab a single city. The first attempt will be slow. The API will have to 'wake up'.
contentType
is important to take inconsideration. The default is application/x-www-form-urlencoded; charset=UTF-8
.
If you use this method, you need to make sure you pass a object and not a serialized one/json.
data: myObject,
contentType: "application/x-www-form-urlencoded",
You can also set the contentType to contentType: "application/json"
(preferred way), but if you do,
make sure you send a serialized object.
data: JSON.stringify(myObject),
contentType: "application/json",
This can be tricky. Double check all the settings (data, dataType, contentType, etc.). After many trials, it finally worked. Another great resource to test this with is REQ |RES. https://reqres.in/.
$(document).ready(function ()
{
// GET Test
const ajaxGetSettings =
{
url: "https://city-info-api-prod.azurewebsites.net/api/v1.0/cities/382762312d-a3e9-6f50873a95d2?includePointsOfInterest=true",
type: "GET"
};
$("#GetTestButton").click(function ()
{
$.ajax(ajaxGetSettings).done(function (response)
{
ShowOutput(response);
});
});
const newCity =
{
"name": "New City X",
"description": "description of city x"
};
let json = JSON.stringify(newCity);
// you can also add header data like so:
//headers:
//{
// "Accept": "application/json",
// "Access-Control-Allow-Origin": "*",
// "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
// "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
// "Content-Type": "application/json"
//}
const ajaxPostSettings =
{
url: "http://localhost:5000/api/v1.0/cities/",
method: "POST",
data: json,
dataType: "json",
contentType: "application/json"
};
$("#PostTestButton").click(function ()
{
console.dir(ajaxPostSettings);
$.ajax(ajaxPostSettings).done(function (response)
{
ShowOutput(response);
});
});
const ShowOutput = (response) =>
{
console.dir(response);
let output = `${response.cityId}<br />`;
output += `${response.name}<br />`;
output += `${response.description}<br />`;
$("#demo-content").html(`${output} (view the console)`);
};
});