I am trying to insert data into the database using AJAX. An ajax
call goes to a servlet, that is meant to insert data into the database. But I think I have made a mistake somewhere in initializing ajax
object. When I click on the submit button,data doesn't get submitted to the database.
HTML:
<form class='form-inline'>
<div class='form-group'>
<label for='nameField'>Name</label>
<input type='text' class='form-control' id='nameField'name='nameField' placeholder='David'>
</div>
<div class='form-group'>
<label for='goalField'>Goals Scored</label>
<input type='text' class='form-control' id='goalField' name="goalField" placeholder='0'>
</div>
<div class='form-group'>
<label for='passField'>Passes Made</label>
<input type='text' class='form-control' id='passField' name="passField" placeholder='0'>
</div>
<button type='submit' class='btn btn-primary' id='submitdata'>Submit to database</button>
</form>
JQuery :
<script>
$(document).ready(function() {
$('#submitdata').click(function(event) {
event.preventDefault();
alert('clicked');
if(window.XMLHttpRequest) {
$xhr = new XMLHttpRequest();
$xhr.onreadystatechange = function() {
if($xhr.readyState === 4 && $xhr.status === 200) {
$xhr.open("GET","insert","true");
$xhr.send();
}
}
} else {alert('else statement');}
});
});
</script>
Where did I make a mistake?
You should call open() and send() outside ready state change listener not from within the callback :)
$('#submitdata').click(function(event) {
event.preventDefault();
alert('clicked'); // DOESN'T GO BEYOND THIS
if(window.XMLHttpRequest) {
$xhr = new XMLHttpRequest();
// bind the readystage change listener first
$xhr.onreadystatechange = function() {
if($xhr.readyState === 4 && $xhr.status === 200) {
alert('response received');
}
}
// call open passing request type, url, async
$xhr.open("GET","/context-root/insert.do",true);
$xhr.send();
} else {
alert('else statement');
} // DOESN'T EVEN REACH HERE
});
Also you can use load
event to handle response
Using jQuery, you can do something like this
$('#submitdata').click(function(event) {
event.preventDefault();
$.ajax({
'url' : '/ctxRoot/insert',
'type': 'GET' // default is GET
})
.done(function(data){
console.log('Ajax response - '+data);
});
});
For more details, check the official documentation here