AJAX
Basics
Data
DOM
Effects
Events
Forms
jQuery UI
Plug Ins
Traversing
Complete blueprint of an POST ajax call. Your callback functions will receive three arguments (all optional) from the call itself.
The optional callback parameter specifies a callback function to run when the given method is completed. The callback function can have three different parameters (name is mutable):
responseTxt
- contains the resulting content if the call succeedsstatusTxt
- contains the status of the callxhr
- contains the XMLHttpRequest objecthttps://api.jquery.com/jQuery.ajax/
async function CreateCity()
{
const newCity =
{
"name": "New City X",
"description": "description of city x"
};
let json = JSON.stringify(newCity);
let newCityResults = await CreateNewCity(json);
await ShowResults(newCityResults);
}
async function CreateNewCity(json)
{
const ajaxConfig =
{
url: "https://city-info-api-prod.azurewebsites.net/api/v1.0/cities",
method: "POST",
async: true,
data: json,
dataType: "json", // what we expect back
contentType: "application/json", // what we're sending
headers: { "x-custom-header": "foobar" }
};
let apiResults = await $.ajax(ajaxConfig)
.done(function (responseTxt, statusTxt, xhr)
{
// success code here
console.log("DONE callback function");
console.log("responseTxt");
console.dir(responseTxt);
console.log("statusTxt");
console.dir(statusTxt);
console.log("xhr");
console.dir(xhr);
if (statusTxt === "success")
{
console.log(" success! ");
}
})
.fail(function (xhr, statusTxt, errorThrown)
{
// fail code here
console.log("FAIL callback function");
console.log("xhr");
console.dir(xhr);
console.log("statusTxt");
console.dir(statusTxt);
console.log("errorThrown");
console.dir(errorThrown);
})
.always(function (responseTxt, statusTxt, xhr)
{
//always executed
// if success, you get back data, textStatus, jqXHR
// if fail, you get back XHR, textStatus, errorThrow
console.log("ALWAYS callback function");
console.log("responseTxt");
console.dir(responseTxt);
console.log("statusTxt");
console.dir(statusTxt);
console.log("xhr");
console.dir(xhr);
});
return apiResults;
}