Hello Readers ,
If you want to post the form but do not want to refresh the browser then the best approach to follow by using AJAX call .
Following is the HTML and Jquery code.
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
The result of the search will be rendered inside this div
<div id="result"></div>
JavaScript:
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
var ajaxRequest;
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
/* I am not aborting previous request because It's an asynchronous request, meaning
Once it's sent it's out there. but in case you want to abort it you can do it by
abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */
ajaxRequest= $.ajax({
url: "test.php",
type: "post",
data: values
});
/* request cab be abort by ajaxRequest.abort() */
ajaxRequest.done(function (response, textStatus, jqXHR){
// show successfully for submit message
$("#result").html('Submitted successfully');
});
/* On failure of request this function will be called */
ajaxRequest.fail(function (){
// show error
$("#result").html('There is error while submit');
});
0 Comment(s)