javascript send json post code example
Example 1: how to send json in js with post
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);
Example 2: send json post ajax javascript
$.ajax({
url: 'users.php',
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: JSON.stringify( { "first-name": $('#first-name').val(), "last-name": $('#last-name').val() } ),
processData: false,
success: function( data, textStatus, jQxhr ){
$('#response pre').html( JSON.stringify( data ) );
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});