Forum Moderators: open

Message Too Old, No Replies

How to submit a form without refreshing

         

JuicyScript

11:38 am on Jul 29, 2010 (gmt 0)

10+ Year Member



I saw this code in [webmasterworld.com...]
and i would like to implement this on my registration website.
Can someone please help one.All i want to do is submit three steps of forms on one page without it refreshing the whole page.So when to submit page one it hides and page two appears,then you submit page two and page three appears .
I dont have an in-depth idea of xmlhttpRequest so would knw how to manipulate the code b
Hi,
Well this should do it:


<html>
<head>
<script type="text/javascript">
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
}else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
//change to something like: yourlayer.visibility = 'hidden';
} else {
alert('There was a problem with the request.');
}
}
};
http_request.open('GET', url, true);
http_request.send(null);
}
function sendform(el){
var sub = el.getElementsByTagName('input');
query = new Array();
for(i in sub){
if(sub[i].name){
query.push(sub[i].name + '=' + sub[i].value);
}
}
query = '?' + query.join('&');
makeRequest("http://www.domain.local/test.php" + query);
}
</script>
<head>
<body>
<form action="/test.php" method="get" onsubmit="sendform(this);return false;">
<input type="text" value="hello" name="text">
<input type="submit">
</form>
</body>
</html>

It seems to work but I just threw it together so we'll see.

Andrew

Fotiman

2:55 pm on Jul 29, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There are a couple of approaches you could take. One approach would be to include all 3 "pages" of the form in a single page:


<!DOCTYPE html>
<html>
<head>
<title>Your Form</title>
</head>
<body>
<form action="/test.php">
<div>
<div id="formPage1">
<input ...>
<input ...>
</div>
<div id="formPage2">
<input ...>
<input ...>
</div>
<div id="formPage3">
<input ...>
<input type="submit" ...>
</div>
</div>
</form>
</body>
</html>


And then you use JavaScript to show/hide each "page" of the form, and then you include your submit button in "page" 3. This has the benefit that if the visitor has JavaScript disabled, they can still see all 3 pages of the form (but as 1 larger "page" vs. 3 "pages"). You wouldn't have to do any AJAX in this case, the form would just submit all of the data at once.

Another option would be to have actual separate pages for each page of the form:

page1.php -> page2.php -> page3.php

So again, a user with JavaScript disabled can still use your forms. Then you would enhance it by using AJAX to submit each page, and then replace only part of your page with the results (ie - the form). This requires more work in that you need multiple form processing pages, so the first option I listed would be much simpler. But if you wanted to go this route, you are on the right track with your code above.

Where you have "alert(http_request.responseText);", http_request.responseText will contain the entire HTML page returned. But you only want a portion of the results... the new form. jQuery makes this easy, and would eliminate the need for you to work with the low level XMLHttpRequest object (or its ActiveX equivalent). If that's something that interests you, you may want to check out the load [api.jquery.com] method. Instead of calling makeRequest, you would do something like this:

var $form = $('#formId');
var formAction = $form.attr('action');
$form.load(formAction + query + ' #formId');

Where the form on each page would have an id of "formId".

Some things to watch out for:
1. In your sendForm method, you are creating a global "query" variable. Add "var" before the first instance to prevent it from being a global.
2. You need to encode the form components before using them in a query string, otherwise you'll have problems if an input contains spaces or certain special characters. Use encodeURIComponent on the values.

Hope this helps.

JuicyScript

5:48 pm on Jul 29, 2010 (gmt 0)

10+ Year Member



Ok so i followed your instruction and took the first one which is simpler...But i can not submit the form to the php script because of e.preventDefault(); which prevents me from submitting the form.And when i get rid of it get the form does nothing.What can help me submit the form to php script.
And please help me change the button to submit and still make the script work.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>.::Apply | Ministry of Health Online Application</title>

<link rel="stylesheet" type="text/css" href="asset/jqueryui1.7/development-bundle/themes/smoothness/ui.core.css">
<link rel="stylesheet" type="text/css" href="asset/jqueryui1.7/development-bundle/themes/smoothness/ui.theme.css">
<link rel="stylesheet" type="text/css" href="asset/jqueryui1.7/development-bundle/themes/smoothness/ui.progressbar.css">
<link rel="stylesheet" type="text/css" href="css/demo.css" />
<!---End of Progess Bar link script--->
<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.validationEngine-en.js" type="text/javascript"></script>
<script src="js/jquery.validationEngine.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
// SUCCESS AJAX CALL, replace "success: false," by: success : function() { callSuccessFunction() },

$("#formID").validationEngine()


//$.validationEngine.loadValidation("#date")
//alert($("#formID").validationEngine({returnIsValid:true}))
//$.validationEngine.buildPrompt("#date","This is an example","error") // Exterior prompt build example // input prompt close example
//$.validationEngine.closePrompt(".formError",true) // CLOSE ALL OPEN PROMPTS
});
function validate2fields(){
if($("#fname").val() =="" || $("#lname").val() == ""){
return true;
}else{
return false;
}
}

</script>


</head>

<body>

<div id="div-regForm">
<p>Progress:</p>
<div id="progress"></div><label id="amount">0%</label>
<form id="formID" id="formID" action="" method="post">
<div id="panel1" class="form-panel">
<fieldset><legend>Personal Information</legend>
<table>
<tbody>
<tr>
<td><label for="fname">First Name:</label></td>
<td><div class="input-container"><input name="fname" id="fname" class="validate[required,custom[onlyLetter],length[0,100]] text-input" type="text" /></div></td>
</tr>
<tr>
<td><label for="lname">Last Name:</label></td>
<td><div class="input-container"><input name="lname" id="lname" type="text" /></div></td>
</tr>
<tr>
<td><label for="sex-select">I am:</label></td>
<td>
<div class="input-container">
<select name="sex-select" id="sex-select">
<option value="0">Select Sex:</option>
<option value="1">Female</option>
<option value="2">Male</option>
</select>
</div>

</td>
</tr>

<tr>
<td><label>Birthday:</label></td>
<td>
<div class="input-container">
<select name="month"><option value="0">Month:</option><?=generate_options(1,12,'callback_month')?></select>
<select name="day"><option value="0">Day:</option><?=generate_options(1,31)?></select>
<select name="year"><option value="0">Year:</option><?=generate_options(date('Y'),1900)?></select>
</div>
</td>
</tr>
<tr>
<td><label>Nationality:</label></td>
<td>
<div class="input-container">
<select name="nationality"><option value="0">Nationality:</option><?=generate_options(1,12,'callback_month')?></select>
</div>
</td>
</tr>

<tr>
<td><label >Parents/Guardian</label></td>
<td><div class="input-container"><input name="parent" id="parent" type="text" /></div></td>
</tr>
<tr>
<td><label >Region:</label></td>
<td>
<div class="input-container">
<select name="drpregion" id="drpregion" >
<option value="">Please Select....</option>
<option value="Ashanti Region">Ashanti </option>
<option value="Central Region">Central </option>
<option value="Western Region">Western </option>
<option value="Northern Region">Northern </option>
<option value="Eastern Region">Eastern </option>
<option value="Greater Accra Region">Greater Accra </option>
<option value="Volta Region">Volta </option>
<option value="Upper East Region">Upper East</option>
<option value="Upper West Region">Upper West</option>
<option value="Brong Ahafo Region">Brong Ahafo </option>
</select>
</div>

</td>
</tr>
<tr>
<tr>
<td><label >Language Spoken:</label></td>
<td><div class="input-container"><input name="lang" id="lang" type="text" /></div></td>
</tr>
</table>

<fieldset><legend>Contact Information</legend>
<table>
<tr>
<td><label >Your Email:</label></td>
<td><div class="input-container"><input name="email" id="email" type="text" /></div></td>
</tr>

<tr>
<td><label >Postal Address:</label></td>
<td><div class="input-container"><input name="postal" id="postal" type="text" /></div></td>
</tr>
<tr>
<td><label >Residental Address:</label></td>
<td><div class="input-container"><input name="resident" id="resident" type="text" /></div></td>
</tr>

<tr>
<td><label >Telephone:</label></td>
<td><div class="input-container"><input name="tel" id="tel" type="text" /></div></td>
</tr>

<tr>
<td><label >Mobile Number:</label></td>
<td><div class="input-container"><input name="mobile" id="mobile" type="text" /></div></td>
</tr>

<tr>
<td>&nbsp;</td>
<td><button id="back" disabled="disabled">&lt;&lt; Previous</button><button id="next" >Continue &gt;&gt;</button>
</td>
</tr>


</tbody>
</table>

</form>
</div>

<div id="panel2" class="form-panel ui-helper-hidden">
<form id="regForm" action="" method="post">
<fieldset><legend>Educational Information</legend>
<table>
<tbody>
<tr>
<td><label>School Name:</label></td>
<td><div class="input-container"><input name="txtSchoolName" id="txtSchoolName" type="text" /></div></td>
</tr>
<td><label>Period:</label></td>
<td>
<div class="input-container">
<select name="from"><option value="0">From:</option><?=generate_options(1,12,'callback_month')?></select>
<select name="to"><option value="0">To:</option><?=generate_options(1,31)?></select>
</div>
</td>
</tr>
<tr>
<td><label>Index Number:</label></td>
<td><div class="input-container"><input name="txtindexno1" id="txtindexno1" type="text" /></div></td>
</tr>
<tr>
<td><label>Subject</label></td>
<td>
<div class="input-container">
<input name="subject1" id="subject1" type="text" />
<select name="drpGrade1"><option value="0">Examination:</option><?=generate_options(1,12,'callback_month')?></select>
<select name="drpExamResult1"><option value="0">Results:</option><?=generate_options(1,31)?></select>
<select name="drpYearComplete1"><option value="0">Year:</option><?=generate_options(date('Y'),1900)?></select>
</div>
</td>
</tr>
<!---2nd row--->
<td><label>Subject</label></td>
<td>
<div class="input-container">
<input name="subject2" id="subject2" type="text" />
<select name="drpGrade2"><option value="0">Examination:</option><?=generate_options(1,12,'callback_month')?></select>
<select name="drpExamResult2"><option value="0">Results:</option><?=generate_options(1,31)?></select>
<select name="drpYearComplete2"><option value="0">Year:</option><?=generate_options(date('Y'),1900)?></select>
</div>
</td>
</tr>
<!---3rd Row--->
<tr>
<td><label>Subject</label></td>
<td>
<div class="input-container">
<input name="subject3" id="subject3" type="text" />
<select name="drpGrade3"><option value="0">Examination:</option><?=generate_options(1,12,'callback_month')?></select>
<select name="drpExamResult3"><option value="0">Results:</option><?=generate_options(1,31)?></select>
<select name="drpYearComplete3"><option value="0">Year:</option><?=generate_options(date('Y'),1900)?></select>
</div>
</td>
</tr>
<!---4th row--->
<tr>
<td><label>Subject</label></td>
<td>
<div class="input-container">
<input name="subject4" id="subject4" type="text" />
<select name="drpGrade4"><option value="0">Examination:</option><?=generate_options(1,12,'callback_month')?></select>
<select name="drpExamResult4"><option value="0">Results:</option><?=generate_options(1,31)?></select>
<select name="drpYearComplete4"><option value="0">Year:</option><?=generate_options(date('Y'),1900)?></select>
</div>
</td>
</tr>
<!---5th Row--->
<tr>
<td><label>Subject</label></td>
<td>
<div class="input-container">
<input name="subject5" id="subject5" type="text" />
<select name="drpGrade5"><option value="0">Examination:</option><?=generate_options(1,12,'callback_month')?></select>
<select name="drpExamResult5"><option value="0">Results:</option><?=generate_options(1,31)?></select>
<select name="drpYearComplete5"><option value="0">Year:</option><?=generate_options(date('Y'),1900)?></select>
</div>
</td>
</tr>
<!---6th Row--->
<tr>
<td><label>Subject</label></td>
<td>
<div class="input-container">
<input name="subject6" id="subject6" type="text" />
<select name="drpGrade6"><option value="0">Examination:</option><?=generate_options(1,12,'callback_month')?></select>
<select name="drpExamResult6"><option value="0">Results:</option><?=generate_options(1,31)?></select>
<select name="drpYearComplete6"><option value="0">Year:</option><?=generate_options(date('Y'),1900)?></select>
</div>
</td>
</tr>
<!---7th Row--->
<tr>
<td><label>Subject</label></td>
<td>
<div class="input-container">
<input name="subject7" id="subject7" type="text" />
<select name="drpGrade7"><option value="0">Examination:</option><?=generate_options(1,12,'callback_month')?></select>
<select name="drpExamResult7"><option value="0">Results:</option><?=generate_options(1,31)?></select>
<select name="drpYearComplete7"><option value="0">Year:</option><?=generate_options(date('Y'),1900)?></select>
</div>
</td>
</tr>
<!---8th--->
<tr>
<td><label>Subject</label></td>
<td>
<div class="input-container">
<input name="subject8" id="subject8" type="text" />
<select name="drpGrade8"><option value="0">Examination:</option><?=generate_options(1,12,'callback_month')?></select>
<select name="drpExamResult8"><option value="0">Results:</option><?=generate_options(1,31)?></select>
<select name="drpYearComplete8"><option value="0">Year:</option><?=generate_options(date('Y'),1900)?></select>
</div>
</td>
</tr>
</table>
<!---End of form filling for results--->
<table>


<tr>
<td>&nbsp;</td><td><button id="back" disabled="disabled">&lt;&lt; Previous</button><button id="next" >Continue &gt;&gt;</button>
</td>
</tr>


</tbody>
</table>
</form>
</div>
</div>
<script type="text/javascript" src="asset/jqueryui1.7/development-bundle/jquery-1.3.2.js"></script>
<script type="text/javascript" src="asset/jqueryui1.7/development-bundle/ui/ui.core.js"></script>
<script type="text/javascript" src="asset/jqueryui1.7/development-bundle/ui/ui.progressbar.js"></script>
<script type="text/javascript">
$(function() {

//call progress bar constructor
$("#progress").progressbar({ change: function() {

//update amount label when value changes
$("#amount").text($("#progress").progressbar("option", "value") + "%");
} });

//set click handler for next button
$("#next").click(function(e) {

//stop form submission
e.preventDefault();

//look at each panel
$(".form-panel").each(function() {

//if it's not the first panel enable the back button
($(this).attr("id") != "panel1") ? null : $("#back").attr("disabled", "");

//if the panel is visible fade it out
($(this).hasClass("ui-helper-hidden")) ? null : $(this).fadeOut("fast", function() {

//add hidden class and show the next panel
$(this).addClass("ui-helper-hidden").next().fadeIn("fast", function() {

//if it's the last panel disable the next button
($(this).attr("id") != "thanks") ? null : $("#next").attr("disabled", "disabled");

//remove hidden class from new panel
$(this).removeClass("ui-helper-hidden");

//update progress bar
$("#progress").progressbar("option", "value", $("#progress").progressbar("option", "value") + 50);
});
});
});
});

//set click handler for back button
$("#back").click(function(e) {

//stop form submission
e.preventDefault();

//look at each panel
$(".form-panel").each(function() {

//if it's not the last panel enable the next button
($(this).attr("id") != "thanks") ? null : $("#next").attr("disabled", "");

//if the panel is visible fade it out
($(this).hasClass("ui-helper-hidden")) ? null : $(this).fadeOut("fast", function() {

//add hidden class and show the next panel
$(this).addClass("ui-helper-hidden").prev().fadeIn("fast", function() {

//if it's the first panel disable the back button
($(this).attr("id") != "panel1") ? null : $("#back").attr("disabled", "disabled");

//remove hidden class from new panel
$(this).removeClass("ui-helper-hidden");

//update progress bar
$("#progress").progressbar("option", "value", $("#progress").progressbar("option", "value") - 50);
});
});
});
});
});
</script>

</body>
</html>

Fotiman

7:16 pm on Jul 29, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Warning: Code Dump! :)
That's quite a bit of code to look through... I would suggest this:
1. You've got multiple buttons with the same id ("next" for example). That won't fly. Also, these are just buttons, so they're not going to submit the form (so preventing the default action on them isn't doing anything).
2. I would create your next/previous buttons using JavaScript. If the user has JavaScript disabled, he/she might get confused if there are next/previous buttons sprinkled throughout the page, especially if they don't do anything.
3. Your form lacks a submit button. See item 2.

In other words, you should start with a normal form, split it into 3 logical "blocks" (ie: wrap those sections in div elements with unique ids), and the form should contain a normal submit button in the last section. Then create previous next buttons and insert them into each block.