Stop reloading on post a form with JQuery
Question by Raymond van Os
I have the following problem. I got two forms on my web page. On the first form can i select a users whit a select box. When i have selected the users in the form, i will send it to the another form on the same web page. How can i be sure that the first page does not reload when i post the form. It is not intended that when I enter some data and a user wants to add the data that i entered are gone by reloading the page by post. I know this can with jquery can but i have no idea how this goes.
Thanks
Answer by NAVEED
You can achieve this by using jQuery.ajax() function.
jQuery('#firstForm').live('submit',function(event) {
$.ajax({
url: 'GetUserInfo.php', // script to return user info in json format
type: 'POST',
dataType: 'json',
data: $('#firstForm').serialize(),
success: function( data ) {
for(var id in data) {
jQuery('secondForm#' + id).val(data[id]); // loop json data to populate each field of second form
}
}
});
return false;
});
GetUserInfo.php
- Get user’s name from
$_POST
variable - Get User information from database.
- Create an array of user info such that
index
of eachvalue
should representid
of a second form field.
For Example:
$userInfo = array( 'FirstName' => 'abc', 'LastName' => 'xyz', 'DOB' => '01/01/2000');
Here FirstName, LastName and DOB are the IDs of form elements in second form
- echo you data into json format:
echo json_encode( $userInfo );
Answer by Starx
You dont need jQuery for this. You can give javascript:void(0);
to simply stop the proceeding of a form like
<form action="javascript:void(0)" >
But, in case you want jQuery Solution
$("form").on("submit", function(e) {
// ^ Select the form with tag, or #idname or .classname
// do stuff
return false; //stop the submition or in your case, stop the reload
/*
return false also is equivalent to
e.preventDefault();
e.stopPropagation();
So, you can scale your concept too :)
*/
});
However, what you are trying this with probably involves a hidden element in another form. So, I will give a small logical part of how the whole thing works.
Example HTML:
<form name="form1" id="form1">
<select id="formselect1">
....
</select>
</form>
<!-- And Form 2 -->
<form name="form2" id="form2">
<input type="hidden" id="inputfromform1" name="inputfromform1" />
</form>
Example JS:
$("#form1").submit(function() {
var tempval = $("#formselect1").val(); //get the value of form 1
$("#inputfromform1").val(tempval); // and place in the element of form 2
return false; //Here stop it
});