I have a ajax request script with post method using body value, what I want is, to print the response value.
$('#my-form').submit(function () {
$.ajax({
url: 'https://apiurl.com/users',
type: 'post',
headers: {
'accept': 'application/json;charset=UTF8',
'content-type': 'application/json',
'api-key': 'judmkd895849438'
},
contentType: 'application/json',
data: { "firstname": $('#firstname').val(), "lastname": $('#lastname').val() },
success: function( data, textStatus, jQxhr ){
$('#response pre').html( JSON.stringify( data ) );
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
and the form script is:
<form id='my-form'>
<div><input type='text' name='firstname' id='firstname' placeholder='Firstname' /></div>
<div><input type='text' name='lastname' id='lastname' placeholder='Lastname' /></div>
<div><input type='submit' value='Submit' /></div>
</form>
<!-- where the response will be displayed -->
<div id="response">
<pre></pre>
</div>
but nothing display on screen, anyone know why?
thanks
As Roy stated, you'll need to prevent the browser from submitting the form. You'll have to prevent the default event from firing as you're handling it via an AJAX request.
$('#my-form').submit(function (event) {
event.preventDefault();
$.ajax({
url: 'https://apiurl.com/users',
...