post request javascript code example
Example 1: javascript send post request
let data = {element: "barium"};
fetch("/post/data/here", {
method: "POST",
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
// If you are as lazy as me (or just prefer a shortcut/helper):
window.post = function(url, data) {
return fetch(url, {method: "POST", body: JSON.stringify(data)});
}
// ...
post("post/data/here", {element: "osmium"});
Example 2: jquery post
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Example 3: create http request javascript
const Http = new XMLHttpRequest();
const url='https://jsonplaceholder.typicode.com/posts';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
console.log(Http.responseText)
}
Example 4: ajax data post call in javascript
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {name:'yogesh',salary: 35000,email: '[email protected]'},
success: function(response){
}
});
Example 5: GET req with js
function httpGet(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
Example 6: how to send data using ajax
$.ajax({
url: "/something", // the url we want to send and get data from
type: "GET", // type of the data we send (POST/GET)
data: {p1: "This is our data"}, // the data we want to send
success: function(data){ // when successfully sent data and returned
// do something with the returned data
console.log(data);
}
}).done(function(){
// this part will run when we send and return successfully
console.log("Success.");
}).fail(function(){
// this part will run when an error occurres
console.log("An error has occurred.");
}).always(function(){
// this part will always run no matter what
console.log("Complete.");
});