Strategies for a multi-page form? - php

I've been trying to make a multi-page poll with jQuery Mobile that is supposed to interact with my MySQL database through Ajax/PHP and have been having issues with it for a while now. It seems I have some problems submitting the form as a result of having it split into several pages. One requirements I need is that the page can not have a page reload.
In my first attempts I tried to divide the pages up into the following:
<div id="page1" data-role="page">
This however failed so many times no matter how I tried to code it. I can not get the submit button to work and I think it could be caused by the fact that I have split the form into several div "pages". I've also tried to make next/submit buttons rather than "Next, next, next ... submit" so that I can store the temporary data in the session, unsuccessfully.
I reworked my whole strategy into a code that hides the question divs that are not active. By this I mean I have one div with data-role set to page, and within it I have several divs with data-roles of content that are hidden/shown by clicking through the form with the next button. I managed to make a small sample form this way that submits the whole form and gets printed out perfectly with some PHP code. However I have yet to successfully validate this version. I can only get my script to validate the last page, and even then it requires ALL checkboxes to be checked, which is pointless. When I tried to implement this version into my real project I could not get it to submit to the .php script at all, but that might just be some syntax error that I will keep looking for.
So, have anyone done anything similar? I'm looking for potential other strategies to solve this issue, or perhaps someone has a theory as to why my aforementioned attemps have failed. Seems Ajax form submits are hard to get working within jQuery Mobile?
Also in case someone can spot a flaw in this I've attached this code that I use for submission, is there an easy way to make this into a function? Or is that pointless?
$(document).ready(function()
{
$("#submit").click(function()
{
var data_string = $('#form').serialize();
$.ajax(
{
type:'POST',
url:'add.php',
data:data_string,
success:function(response)
{
$("#answers").html(response);
}
});
})
});
I also use this function during window.onload to generate the poll with a lengthy .php script. Basically it generates the questions as , every other question variety has only name="answers[question_id]".
function getQuestions(id)
{
var xmlhttp = getHttpRequestObj();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","poll2.php",true);
xmlhttp.send();
}
The form looks like this:
<form id="form">
<div data-role="content" id="form'.$page.'" class="section">
<fieldset data-role="controlgroup" data-type="vertical" data-mini="true" id="'.$question_id.'">
<input type="checkbox" name="answers['.$question_id.']['.$alt_id.']" id="'.$question_id.'_'.$alt_id.'" value="'.$alt_id.'"/>
<label for="'.$question_id.'_'.$alt_id.'">'.$alt_desc.'</label>
</fieldset>
<input type="button" name="next" value="Next" id="next" onClick="toggleVisibility(\'form'.($page+1).'\')" class="next-btn"/>
</div>
The last page has this code instead of the next button:
</div><input type="button" id="submit" value="Submit" class="submit-btn"/></form>

In my opinion, hiding the other options and open one by one is a better way (also called multi step form).
For validation, you can do it in client side with javascript or use ajax which triggers on appropriate event (you don't need to submit it for validation) and validates in server side.
You are in right track. The issue i see here is how you'l do the validation but that'l depend upon how your form is structured.

Related

Onblur or onchange check, using a php function in a registration form

I would like to be able to check the text in a text-box after it has changed, and report what is wrong.
It is for a registration form.
This is a part of register.php where
<form action"" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p><input name="username-field" type="text" onblur="someFunction()" /><span id="UsernamehelpText"> </span>
</li>
</ul>
</form>
Then I would have a registerfunctions.php where i would store all the functions for checking lenght,char,maybe regex etc.. Its not really that important what functions i call. I just don't know how to call them.
Form what i have seen the span is where u post the errors, but if there is any other option im open for it, all i want is to be able to post the erorr text in the same line as the text-box
I have checked JavaScript and AJAX, but I am pretty new in this and don't really understand how it works.
After discussion in comments I understand what you want.
First, an explanation. There are two places where validation occurs: In your frontend (your web page) and in your backend (in the PHP script that saves the posted values). Anything that you really don't want to save - for example unescaped SQL strings, too-long fields, and so on - has to be validated in PHP, because it is trivial to get around Javascript validation. For example, nothing is stopping someone from sending a POST to your server containing illegal values without even bothering to visit your webpage.
Even though you need to perform validation in the back-end, it's still user friendly to do the same validation in the front end, so the user doesn't have to wait as long to see an error. This also reduces traffic to your server. Something you probably want to do in a big project is to have some kind of system for writing validation rules centrally, and then using those rules to dynamically generate both PHP and Javascript validation. The advantage of doing that is that you don't duplicate your business rules in two places, but in a smaller project it's probably not worth the hassle.
Validation in the frontend looks about like this: You bind an event handler to an appropriate event or events (you can add onkeydown="validateUserName()" for example, so that the validation reacts a bit quicker), and update your warning text appropriately.
<form action="" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p>
<input id="username" name="username-field" type="text" onblur="validateUserName()" />
<span id="UsernamehelpText"></span>
</li>
</ul>
</form>
<script type="text/javascript">
function validateUserName() {
var userNameElement = document.getElementById('username');
//Do your work: Get the value of the user name field, check
// the values against your validation rules...
var helpText = document.getElementById('UsernamehelpText');
if(isValid)
helpText.innerHTML = "";
else
helpText.innerHTML = "Invalid!";
}
</script>
In the backend, when you process the form, you then have to check the same rules in PHP to prevent illegal values from being posted either maliciously or due to an error in your Javascript. If an error is found, you don't save, instead you can just re-render the form with the submitted values in the input fields and a message indicating what was invalid - this allows the user to change their inputs without losing the values they submitted.
With jQuery it would look something like this:
function someFunction() {
$.ajax({
url: "checkStuff.php",
data: $("input[name='username-field']").serialize,
success: function(data) {
if (data == "correct") {
$("#UsernamehelpText").html("Valid");
} else {
$("#UsernamehelpText").html("Invalid");
}
}
});
}
Your PHP could be something very simple that just checks the validity of the input and then echos "correct" if it is.

Showing an alert() dialog box if a form does not have valid values

I have a simple form which accepts a Title and a Contents variable from a textbox and a textarea. The form will send its data to a file called add-post.php. However, I am looking for a way to alert the user that either the textbox or the textarea has invalid data (is empty) in case they click the submission button.
I was thinking that an alert() popup box would be the best idea because it doesn't redirect to any other page and the user never loses their data (imagine they entered a whole lot of text but forgot a title. Sending the data to add-post.php and performing the check there will result in loss of data for the user).
However, I'm not sure how to actually implement the alert() popup. How would I make it so that the check is done AFTER they have clicked the submit button but BEFORE the data is sent off to the next file. Any advice is appreciated.
On your form add something like this
<form name="frm1" onsubmit="InputChecker()">
Then in javascript
<script type="text/javascript">
function InputChecker()
{
if(document.getElementById({formElement}) != '') { // not empty
alert("This element needs data"); // Pop an alert
return false; // Prevent form from submitting
}
}
</script>
Also as others have said jQuery makes this a little bit easier. I highly recommend the jQuery Validate Plugin
Some people do find the alert box "annoying", so it may be better to append a message into the DOM to let the user know what needs to be fixed. This is useful if there are numerous errors as the errors will be more persistent allowing the user to see all the things they need to be fixed. Again, the jQuery Validate plugin has this functionality built in.
Attach an onsubmit event to the form, and return false; to stop the submission if checks fail.
Form validation with Javascript. Or easier with jQuery.
Basically, validate the form when the submit button is clicked (with an onsubmit handler), and then use an alert() box if needed. By the way, people usually hate alert boxes.
You have a number of options when it comes to client side validation. This is just one.
<form id="tehForm" method="post">
<input type="text" id="data2check" >
<input type="button" id="btnSubmit" />
</form>
<script type="text/javascript">
function submit_form(){
if(document.getElementById("data2check").value!="correct value"){
alert("this is wrong");
}else{
document.getElementById("tehForm").submit();
}
}
</script>
For a more indepth example check out this link

Submitting a form through a modal box without leaving the page/modal

I am using the project 'ModalBox' from http://okonet.ru/projects/modalbox/index.html in order to generate my modal.
I am also using this overall script that persists e-mails submitted via form into a basic text file as a simple/quick solution. http://www.knowledgesutra.com/forums/topic/25586-php-simple-newsletter-script/
I have a dilemma though.
In order to keep the modal and display my 'mailing_thankyou.php' my form has to have 'onsubmit="return false"' but in order for my php script to work, I have to remove that return false, but then it changes to a new page in order to persist that information.
Does anyone have any ideas?
This is the main part in question:
myModal.html
<div id="signUp">
<form action="mailer/mailing.php" id="myForm" method="post" class="style16">
<input type="text" name="email" size="30" value="your email here!">
<input type="submit" value="Send link" name="submit" onclick="Modalbox.show('mailer/mailing_thankyou.php', {title: 'Form sending status', width: 500, params:Form.serialize('myForm') }); return false;">
or Cancel & close
<!-- ><input type="submit" value="GO!" name="submit"> -->
</form>
</div>
You may pull my files from my git repo:
https://github.com/jwmann/Modal-Sign-up
I'm not good at Mootools, so I will give you an example in jQuery - if you get the idea, I'm pretty sure you will find the right syntax for Mootools too.
The idea is to use AJAX call for form submission (and keep the onsubmit="return false;" so that browser window isn't reloaded):
var $form = $('#myForm');
$.post($form.attr('action'), $form.serialize(), function(response) {
$('div#signUp').html(response);
});
What this does is:
Stores jQuery wrapped form element into $form
Uses form's action attribute value as a request target address
Serializes and transfers all form elements' values
Executes callback function, which takes returned HTML code and replaces contents of <div id='signUp'>...</div> with this HTML.
Note: make sure that the script at forms action only returns html for the contents of the sign up box (meaning no <head>, <body>, etc. - only what should be in the box afterwards)
EDIT/AMENDMENT
This is what I've just found out on MooTools Docs page for Ajax/Request:
The equivalent of my jQuery snippet in MooTools would be
new Request.HTML({ // Creates an AJAX request
'url': $('myForm').get('action'), // Sets request address to the form's action
'update': $('signUp') // Indicates that results should be auto-loaded into element with id='signUp'
}).post($('myForm')); // Indicates that this form has to be serialized and transferred; also starts the request process
This requires that the form's action returns the result to display (a thank you message). One could achieve that by making redirect from the server-side after form data has been successfully processed, e.g. in PHP header('Location: mailer/mailing_thankyou.php'); exit;
After looking longer at your code I realized, that this is not entirely what you want (as I see you don't want the form replaced with the thank-you message - you want it to be shown in the modal). Hence the updated solution for your case:
new Request.HTML({ // Creates an AJAX request
'url': $('myForm').get('action'), // Sets request address to the form's action
'onSuccess': function() { // Defines what to do when request is successful (similarly you should take care of error cases with onFailure declaration
Modalbox.show('mailer/mailing_thankyou.php', {
title: 'Form sending status',
width: 500
// I have removed params from here, because they are handled in the .post() below
});
}
}).post($('myForm')); // Indicates that this form has to be serialized and transferred; also starts the request process
Pardon me if any of this doesn't work (as I said, I'm more of a jQuery guy - just trying to help here)
Have the form submit to a hidden iframe on the page. Give the iframe a name value and then set a target propery on the form. You can make the iframe 1x1 pixel and set the visibility to hidden (if you hide via display: none it might not work in all browsers.)
See this question for details:
How do you post to an iframe?
I removed the 'return false' from the input submit's 'onsubmit' (duhhh facepalm) because it was trying to serialize it in the first palce with prototype.js
Then I changed the php script so it would grab with $_GET instead of $_POST
no added functionality or hacks needed. Thank you for all the help though.

jQuery Dynamic Page Question

I have the following HTML page:
<div id="foobar">
<?php echo $dynamicVar; ?>
</div>
<input type="button" value="Submit" id="subButton"/>
When I press submit, the value of $dynamicVar will change. Is there a way, without using Ajax callbacks, .each(), or anything complicated, to do a dead-simple refresh of the div element? I know there's a jQuery function, I've seen it before, but I can't find it now. This function will just refresh an element. Everything I've found requires me to write unnecessarily complicated code to attempt to refresh a very small very simple element.
For example, if the the entire div had the value "1" inside of it, and I pressed the button, I want to refresh in order to show the value "n".
Here's the jQuery code:
$('#subButton').live('click',function() {
//dead-simple element refresh, nothing fancy necessary
});
Example #2:
<div id="foobar">
<?php echo time(); ?>
</div>
<input type="button" value="Submit" id="subButton"/>
Since time generally goes forward, the timestamp should be different from a few seconds ago when the web server gave me the timestamp. I would want to have the div element do a very simple update of itself so that I would see the new timestamp upon button click.
Any help?
Were you thinking of .load()? It's a high-level ajax function. You'd use it something like this:
$('#subButton').live('click',function() {
$('#foobar').load('thispage.php #foobar > *');
});
You'll have to use AJAX AFAIK, but in your $.ajax() callback, you can use $.replaceWith() (documentation).
$('#foobar').load('my/script.php');

Do browsers support autocomplete for ajax loaded login forms at all?

My problem is, that the browsers' (IE&FF) autocomplete does not work for my login form.
I have a webapp with CakePHP & jQuery. To allow visitors to login/register unobtrusively. The login form is inside a div, which is loaded via AJAX. (This enables logging in without a page reload.)
The browsers do recognize it as a login field, as they prompt me to save the credentials when clicking login. And they really do save the username/password, as they appear between the saved ones in the browser settings. But the saved username/password is never entered automatically. They do not appear pre-entered when the page loads. When I start typing in the username, the username appears as a suggestion, but even when you select it, the password is not entered next to it. Why? How can I get this working?
That you can test it yourself, here is a simple AJAX login form:
http://gablog.eu/test/ajaxlogin.html
It loads the following login form, if you go to the url below, autocomplete will work for just the plain form, so it is not a problem with the form itself, but rather that it is AJAX loaded:
http://gablog.eu/test/loginform.html
The layout:
<div id="user-bar">
<script type="text/javascript">
$(function() {
$("#user-bar").load('loginform.html').html();
});
</script>
</div>
The view loaded (when not logged in):
<form id="form-login" action="" onsubmit="login(); return false;">
<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>
<input type="submit" value="Login"/>
<div id="login-error" class="error-message"></div>
</form>
<script type="text/javascript">
function login() {
$.post('/ajax/login', $("#form-login").serialize(), function(data) {
if (data.success) {
$("#user-bar").load('userbar.html').html();
} else {
$("#login-error").html(data.message);
}
}, "json");
}
</script>
To clarify: I do not want to use AJAX autocomplete, I want the browser's autocomplete to work for my login form. This is an issue between my form and the browser. jQuery submission seems to play a minor role, as the usernames/passwords are saved. They are just not auto-entered for ajax loaded HTML elements! (The test site does not use jQuery submission.) Related question: browser autocomplete/saved form not work in ajax request
Autocomplete, in Firefox at least, triggers during page load. Adding the content afterwards would miss the window of opportunity.
A login form is tiny. I'd include it in the page from the outset and consider hiding it with CSS until it is wanted.
In case it helps, msdn says (towards the bottom of the page):
Note: if both of the following
conditions are true:
The page was delivered over HTTPS
The page was delivered with headers or a META tag that prevents
caching
...the Autocomplete feature is
disabled, regardless of the existence
or value of the Autocomplete
attribute. This remark applies to IE5,
IE6, IE7, and IE8.
I've emboldened the interesting bit.
.
I don't think you can get the form autocomplete to work if you load the form via ajax (security-wise I don't know if it can be really be abused or not, but the fact that a script could start loading fields into the page to see what data gets inserted doesn't look too good to me).
If you can, the best option would be to add a conditional block to the php file and include the form or not depending on whether the user is logged or not. If for some reason you can't do that, you might want to try to do a document.write() instead of the ajax call (and yes, using document.write is ugly :)
I see case when login form has to be pulled with ajax - if rest of the website loads as static html (cache). Login form (or authed user info) cant be displayed statically.
So your solution is to pull the form right after declaration (end tag) of the DOM element that serves as parent element for ajax-pulled loginform's html, ex:
<div id="loginforms_parent"></div>
<script language="javascript">
/* ajax request and insert into DOM */
</script>
And browser has the form in DOM onLoad. Tested, firefox does autocomplete in that case.
I'm not happy with loading the login form into my page at load time so I filed a issue with Chrome instead;
http://code.google.com/p/chromium/issues/detail?id=123955&thanks=123955&ts=1334713139
there is answer given : http://www.webmasterworld.com/javascript/4532397.htm . it does something with submit method and then uses click method. as i know values are not saved if form is not submitted. i think author of that solution just makes it submitted though submit button is not clicked by user.

Categories