I have a page finduser.php which is accessed by clicking a button on another page user.php. user.php is a simple form that takes a couple of parameters from an end user, submits to finduser.php which appends that user to a list.
user.php
<form action="finduser.php" method="post">
<input type="text" name="username" required="required"/>
<input type="submit" value="Find User"/>
</form>
finduser.php
<?php
//session start is on another page included on every page
$theUser = $_POST["username"];
if (!isset($_SESSION["users"])) {
$_SESSION["users"] = array();
} else {
$_SESSION["users"][] .= $theUser;
}
?>
The way the UX handles is that you begin on user.php, submit form and are navigated to finduser.php, but if you want to keep searching for users, you need to press back and resubmit the form. I'd like a way to not redirect on form submit, but still execute the code on finduser.php.
I notice some sites use a similar concept for adding items to a cart. Some sites redirect you to the cart on adding something, but some stay on the same page without disrupting UX. A little box might appear "x has been added to cart", which lets you add multiple things from the same page to cart but without seeing the cart between.
How can I accomplish this? To reiterate what I'm trying to do:
user types a name in user.php
user presses submit, the PHP in finduser.php is executed
perhaps a box appears "[name] has been added to the list"
there are no page redirects
I could do something like the below:
user.php
<?php
//session start is on another page included on every page
if ((sizeof($_POST) == 1) && isset($_POST["username"])) {
$theUser = $_POST["username"];
if (!isset($_SESSION["users"])) {
$_SESSION["users"] = array();
} else {
$_SESSION["users"][] .= $theUser;
}
}
<form action="user.php" method="post">
<input type="text" name="username" required="required"/>
<input type="submit" value="Find User"/>
</form>
?>
This way only one page is needed, but it still needs to redirect (to itself), and is prone to disruption when someone refreshes the page for example.
You need to use AJAX to process your PHP code and return the result. Here's an option using jQuery's AJAX handler:
# File: yourform.html
<form action="finduser.php" id="findUserForm" method="post">
<input type="text" name="username" required="required"/>
<input type="submit" value="Find User"/>
<div class="messages"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#findUserForm').submit(function(e) {
// Stop the regular post action
e.preventDefault();
var $form = $(this);
// Define the request that should happen instead
$.ajax({
url: $form.attr('action'),
method: $form.attr('method'),
dataType: 'json',
data: {
username: $('input[name="username"]').val()
}
}).done(function(result) {
// Append the results to the messages div
$('.messages').append('<p>' + result.message + '</p>');
});
});
});
</script>
Then your backend script to process the username:
# File: finduser.php
<?php
session_start();
if (isset($_POST['username'])) {
// do your processing...
if (empty($_SESSION['users'])) {
$_SESSION['users'] = [];
}
// Add it to the array
$_SESSION['users'][] = trim($_POST['username']);
// do more processing?
// Return a result
echo json_encode(
'success' => true,
'message' => $_POST['username'] . ' was successfully added!'
);
exit;
}
// Handle errors!
echo json_encode(
'success' => false,
'message' => 'No username was posted.'
);
I haven't tested this, but the idea is that you tell jQuery to override the default way it handles that form being submitted, and instead it should send the username via AJAX to finduser.php. That script will do things that you tell it to, add the user to the session array, then output a JSON result message. jQuery's .done() event then processes that result message and adds the message to the .messages div.
You can use the success => bool option to control how the messages might display, for example:
.done(function(result) {
var $elem = $('<p></p>');
// Add a CSS class for display
if (result.success) {
$elem.addClass('success');
} else {
$elem.addClass('error');
}
// Append the results to the messages div
$elem
.html(result.message)
.appendTo($('.messages'));
});
Then add some CSS like so:
.success {
color: green;
}
.error {
color: red;
}
In theory, your result messages should then be colour coded.
Related
Is there a php way to validate a form that goes submitted to another page before submitting and stay on same page if fields are not valid or if everything valid send post data to another page?
Example would be:
I am on page somesite.com/orderitems and there would be form like
<form method="post" id="orderform" action="somesite.com/shoppingcart">
<input type="number" name="numitems" id="numitems" value="1">
<input type="date" name="date" id="date">
</form>
So google chrome for example already knows to validate if you put in input field required value and to validate date and number fields. I have also a jquery datepicker so user can select date easily, and also jquery validator to validate fields before submit, but all this can be overridden and/or fail at some point.
So end point would be validation in php when form is submitted.
But what i am stumbled upon is that i can't use GET request in getting data on somesite.com/shoppingcart so i must send POST to that page, but if some of the field fail to validate, like wrong date or wrong date format, than i shouldn't even go (redirect or post) to somesite.com/shoppingcart, instead i should stay on the page somesite.com/orderitems and display the errors.
So is there a solution to something like this, what suggestions would you recommend. Can i post form to the same page and validate fields if, all is good than redirect to another page and pass POST data, or stay on same page and display error?
I will show you how this can be done via JavaScript/Ajax and PHP. I think it won't be difficult to learn doing it from this tutorial, but if some questions arise I am ready to help you.
JavaScript/Ajax request
First of all, we need to add "Submit" button to form and set "sendData()" function as its "onclick" listener. Which means each time you click on "Submit" button, "sendData()" function will execute. Also, we need to add 'class' attribute to 'number' and 'date' input elements, to get their values in more cleaner way.
<form method="post" id="orderform" action="somesite.com/shoppingcart">
<input type="number" class='myForm' name="numitems" id="numitems" value="1">
<input type="date" class='myForm' name="date" id="date">
<input type="Submit" value="Send" onclick = sendData(); return false;"/>
</form>
<script type="text/javascript">
function sendData()
{
var formElements = document.querySelectorAll(".myForm"); // We use 'class' attribute to get form elements (number and date).
var formData = new FormData(); // we create FormData object with which we can send data to "PHP" script (server side).
for(var i = 0; i < formElements.length; i++)
{
formData.append(formElements[i].name, formElements[i].value);
}
//AJAX Starts Here
var xmlHttp = new XMLHttpRequest(); // Create "ajax" object
xmlHttp.onreadystatechange = function() //This is to wait for response from your PHP script
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //And when status is OK use result
{
var responseText = xmlHttp.responseText; //here you save your response from server side.
if(responseText["Status"] === "OK") //if you send from server side that "Status" is OK, then you can go to that page
{
window.location.href = "somesite.com/shoppingcart";
}
else //otherwise you refresh page
{
window.location.reload();
}
}
}
xmlHttp.open("POST", "somesite.com/shoppingcart"); //set page value, where you want to send form values
xmlHttp.send(formData); //send actual data
}
</script>
PHP validation (to avoid manipulation/override on client-side)
When you validate values in server-side, set $_SESSION["Status"] = "OK".
After that if someone tries to "hack" your page and "change" your JavaScript functions to navigate to somesite.com/shoppingcart page, you will check:
somesite.com/shoppingcart
<?php
if($_SESSION["Status"] === "OK"])
{
//give permission
}
else
{
return false;
}
?>
i am also facing this problem. and i solve it by doing this
UPDATE
$(document).ready(function () {
$('#orderform').validate({
rules: {
numitems: {
required: true,
number: true
},
date: {
required: true,
date: true
}
}
});
$('#orderform input').on('keyup blur', function () {
if ($('#orderform').valid()) {
$("#button1").removeClass("submit");
//TRIGGER FORM
//$('#orderform').submit();
}
});
});
.submit{
user-select: none;
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<form method="post" id="orderform" action="somesite.com/shoppingcart">
<input type="number" name="numitems" id="numitems"><br/>
<input type="date" name="date" id="date"><br/>
<span class="submit" id="button1">SUBMIT</span>
</form>
i Hope it helps.!
I'm just a PHP starter and now I want to learn JQUERY, on my learning process I practice on validating inputs usually I validate my inputs using a pure PHP code only and every time I validate the inputs the page reloads and now I want to improve in doing things I found some articles like http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.post/ (can't post other links) but I am more confused because they have different approach and I want to use the approach from the JQUERY tutorial but I haven't found any good tutorials and there is no tutorials on JQUERY's site that is using a database, usually I code like this:
<form method="post">
<label for="Username">Username:</label>
<input id="Username" type="text" name="username">
<?php
session_start();
if(isset($_SESSION['msg'])){
$msg=$_SESSION['msg'];
echo '<label for="Username">'.$msg.'</label>';
?>
<input type="submit" name="reg">
</form>
<?php
if(isset($_POST['reg'])){
$result=//check username from database here
if($result){
$_SESSION['msg']='username not available.';
}
else {
$_SESSION['msg']='username available.';
}
}
?>
Now I want to learn how can I validate inputs directly from the database without reloading the page? I don't know where should I start, what to add in my code. Any help, advice or suggestions will be really a big help for me :)
first, in your form add a onSubmit function
<form name='myform' type='POST' action='http://www.action.fr' onSubmit="return check_form()">
you can do this in ajax like that
function check_form()
{
var user = $('#Username').val(); // Username is the id of your input
var password = $('#password').val(); // password is the id of your input
$.ajax(
{
type:"POST", // or get as you want
url:"myfile.php", // it is the php file which can do the job
data: "user="+user+"&password="+password, // the param to send to your file,
success:function(msg)
{
;// msg is the result of your 'myfile.php', everything you write is in the msg var
}
});
}
in your php file you can get your data like this :
$user = $_POST['user'];
$password = $_POST['password'];
// if your type is get then use $_GET instead of $_POST
tell me if you have any problem with my code.
Write your validation script as though you're expecting a page refresh. Instead of outputting error messages, put them in a JSON array and print the JSON data. Then call the script from the AJAX function. It's really that simple.
<?php
// validate.php
$sampleInput_number = isset($_POST['sampleInput_number']) ? $_POST['sampleInput_number'] : "";
$errors = array();
if (trim($sampleInput_number) == "" || !is_numeric(trim($sampleInput_number)) {
$errors[] = "SampleInput_number must be a number!";
}
// sample input must also match a value from the database
if (!matchesDBValue($sampleInput_number)) {
$errors[] = "SampleInput_number must match a value from the database!";
}
function matchesDBValue($value) {
$retval = false;
// compare to db values here...
return $retval;
}
echo json_encode($errors);
Your form would look something like this:
<form action="" method="post" id="theForm">
<input type="text" name="sampleInput_number" id="sampleInput_number" />
<input type="button" id="formSubmit" value="Submit" />
</form>
And your javascript would look like this:
<script language="javascript" type="text/javascript">
$(#formSubmit).on("click", function() {
$.post("validate.php",
{
sampleInput_number: $("#sampleInput_number").val()
}, function(data) {
// check returned json data
// perform action based on results
if (no_errors) {
$("#theForm").submit();
}
}, "json"
);
});
</script>
Here I am trying to check that username input is available for the user or not. I am doing it in codeigniter.
Here is my view page:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<style type="text/css">
.no{color:red;}
.yes{color:green;}
</style>
<script>
$(document).ready(function(){
// unique user name checking ------------- starts here----------------
$("#username").blur(function(){
var form_data= {
action : 'check_username',
username : $(this).val
};
$.ajax({
type: "POST",
url : "check_unique_username",
data : form_data,
success : function(result) {
$("#message").html(result.message);
alert(result);
}
});
});
// unique username checking -------------- ends here-----------------
});
</script>
</head>
<body>
<form class="RegistrationForm" id="RegistrationForm" method="POST" action="">
<label for="username">User Name</label>
<div>
<input id="username" name="username" size="25" class="required" />
</div>
<input type="button" id="button1" name="button1" value="check availability" />
<div id="message"></div>
</form>
</body>
here is my controller code :
<?php
class Registration extends MX_controller {
function index(){
$this->load->view('registrationPage'); // this will load the registration page.
}
function unique_username() {
$action = $_POST['action'];
if($action=='check_username'){
$u = $this->input->post('username');
$users=array("jhon","neo","margo","hacker","user123");
if(in_array($u,$user)) {
echo json_encode(array('message' => "It is not available!"));
}
else {
echo json_encode(array('message' => "It is available!"));
}
}
}
}
?>
But my code is not working, where I am getting wrong,please help me out..showing only it is available for every username
Edited : I have changed my controller code...
You have not used # while using the id of the div, so use:
$("#message").html(result);
instead of $("message").html(result);
EDIT: An updated answer to an updated question.
It's actually pretty stupid none of us could see it, but the problem is this string: username : $(this).val. The reason is that .val is not jQuery's method that get's the value of a text field, it should be username : $(this).val() (with brackets).
This covers the first JS part, the next problem is a typo, you have url : "check_unique_username",, but it should be url : "registration/unique_username", (didn't have controller name, and had unnecessary check_ prefix while in controller the method was without it).
Next typo is in PHP - if(in_array($u,$user)) {, but we have an array $users, so change this to if(in_array($u,$users)) {, so PHP would not throw a notice.
Next problem is the missing line dataType: 'json', in AJAX request. We must put it so that JS could know what data type we are receiving and parse it in a correct way.
After that it should work. But I have some suggestion for you. Change the PHP, so that it would return not strings, but a boolean value. For example - true, if it's available, false if it's not.
if(in_array($u,$users)) {
echo json_encode(array('message' => false));
} else {
echo json_encode(array('message' => true));
}
That way it would be easier to manipulate this data in your JS code. For example you could add this code to the success part of your AJAX request:
success : function(result) {
if(result.message) {
$("#message").html("It's available!");
$("#button1").removeAttr('disabled');
} else {
$("#message").html("It's not available!");
$("#button1").attr('disabled','disabled');
}
}
And you will have your submit button enabled/disabled. This will make sure a normal user would not be able to submit the form if he entered a username that is taken.
Also I would change the event blur to keyup, that way you will have faster updates, but it's a bit more heavy on the server. Problem with blur event is that your user could fill the username and click on the button anyway, because blur event fires only after the user leaves the element.
Hope this helps!
I found a tutorial here : http://tutorialzine.com/2009/08/creating-a-facebook-like-registration-form-with-jquery/ (please take a look)
It's a nice tutorial, I followed everything there and remove extra stuff I don't want , like the functions.php with generate_function option as I am not in need of birthday etc. stuff.
All I want is a NAME(usrname) , EMAIL(email) , Password(password) , when the user click on "REGISTER" button (which is the form submit button), the script I got from the tutorial will send the data over to "regprocess.php" which contains validation check codes like checking if the submitted form data is empty.
But when I click REGISTER , the data is not sent back (the error message) from the "regprocess.php" nor the success message.
When i check with my firebug , the JSON response is showing the full php code like the one below(scroll down).
Here's my code :
HTML-
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript" src="register.js"></script>
<form id="regForm" action="regprocess.php" method="post">
<label for="usrname">Name:</label>
<input id="usrname" name="usrname" type="text" value="" class="nor">
<label for="email">Email:</label>
<input id="email" name="email" type="text" value="" class="nor">
<label for="password">Password:</label>
<input id="password" name="password" type="password" value="" class="nor">
<table><tr><td style="width:290px;"><div id="error"> </div></td><td><input name="register" type="submit" value="Register" id="regbtn"><center><img id="loading" src="images/load.gif" alt="Registering..." /></center></td></tr></table>
</form>
Okay the Ajax script is in "register.js" above.
Ajax script(register.js)-
$(document).ready(function(){
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
hideshow('loading',1);
hideshow('regbtn',0);
error(0);
$.ajax({
type: "POST",
url: "regprocess.php",
data: $('#regForm').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
hideshow('regbtn',1);
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error(act,txt)
{
hideshow('error',act);
if(txt) $('#error').html(txt);
}
CSS:
Regbtn is the submit button , it's visibility is set to visible
loading is set to hidden
error is set to hidden
When a user click on Regbtn , loading visibility will become visible while Regbtn hides(visibility:hidden).
It's done in the Ajax script(register.js).
Okay now the php:
PHP(regprocess.php)-
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
This checks whether the username , email and password data is empty , if yes , returns a message which will be displayed in the Error(#error in html) , it also checks whether email provided is valid.
If everything else is right , user will be directed to registered.html
But i think the script can't get the error message back from the php.
I hope someone can help me. Thanks.
Have a nice day.
hmm not too much of an answer but what I do on my forms is a I submit via ajax and put the result from the php page in the parent of the form.
below is the plugin in code. it works when the form is a child of a div by default.
(function($){
$.fn.extend({
//pass the options variable to the function
ajaxForm: function(options)
{
//Set the default values, use comma to separate the settings, example:
var defaults =
{
target: 'div'
}
var options = $.extend(defaults, options);
return this.each(function()
{
var o=options
$(this).submit(function(event)
{
event.preventDefault();//stop from submiting
//set needed variables
var $form = $(this)
var $div = $form.parent(o.target)
$url = $form.attr("action");
//submit via post and put results in div
$.post( $url, $form.serialize() , function(data)
{ $div.html(data) })
})
});
}
});
})(jQuery);
note this will run for every form so change it as you would wish.
whatever you want to display just echo on the php page. also this is made for post and the php page will access anything just like any other form being with post.
also it wouldn't be hard to modify if you felt necessary to send as json instead.
You need to put php tags around the php code, like this:
<?php
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
?>
I have a form that you can add data to a database. It is all done with jquery and ajax so when you press submit it validates the code and then if everything is correct it submits the post data with out refreshing the page. The problem is the form works the first time, but then when you go to submit another entry with the form it doesn't work. I thought it had something to do with the
$(document).ready(function(){
But I really have no idea. I've pasted some of the code below. It is pretty long, but this should give enough info to know what it's doing.
The entire js file is at http://www.myfirealert.com/callresponse/js/AddUser.js
$(document).ready(function(){
$('#AddCaller').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var Firstname = $('#Firstname').val();
...OTHER FORM FIELDS HERE
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut. */
if(Firstname.length == 0){
var error = true;
$('#Firstname_error').fadeIn(500);
}else{
$('#Firstname_error').fadeOut(500);
}
if(Lastname.length == 0){
var error = true;
$('#Lastname_error').fadeIn(500);
}else{
$('#Lastname_error').fadeOut(500);
}
...MORE CONDITIONAL STATEMENTS HERE
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'added'){
//$('#cf_submit_p').remove();
//and show the success div with fadeIn
$('#Add_success').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
document.getElementById('Firstname').value = "";
document.getElementById('Lastname').value = "";
document.getElementById('PhoneNumber').value = "";
document.getElementById('DefaultETA').value = "";
document.getElementById('Apparatus').value = "";
document.getElementById('DefaultLocation').value = "";
setTimeout(" $('#Add_success').fadeOut(500);",5000);
}else if(result == 'alreadythere'){
//checks database to see if the user is already there
$('#Alreadythere').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
}
else{
//show the failed div
$('#Add_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
Right now, the first time you use the form it works great. and the button is reenabled, but then when you try to make another entry and click the button nothing happens.
Thanks for the help!
EDIT: After the form submits the first time the button is still enabled and you can click on it, but when you click on it nothing happens... even if you don't fill in the form. It's like the click event of the form isn't firing the first time.
EDIT2 As requested, I'm going to post the HTML, it's behind a password protected site, so I can't send you the page link.
<form action='addcallers.php' method='post' id='AddCaller_form'>
<h2>Add Callers</h2>
<p>
First Name:
<div id='Firstname_error' class='error'> Please Enter a First Name</div>
<div><input type='text' name='Firstname' id='Firstname'></div>
</p>
<p>
Last Name:
<div id='Lastname_error' class='error'> Please Enter a Last Name</div>
<div><input type='text' name='Lastname' id='Lastname'></div>
</p>
...MORE FORM FIELDS HERE
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly >
</div>
</p>
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
<p id='cf_submit_p'>
<input type='submit' id='AddCaller' value='Send The Message'>
</p>
</form>
</div>
EDIT3 There is other ajax on the page too, but it's written in straight javascript. I'm not sure if that would affect the functionality in any way. But if needed I can post that ajax as well.
EDIT4 I got the original tutorial from http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ and modified it
EDIT After putting in some different alerts, I found out that it does not do the conditional statement if(error==false)... Any Idea why?
most likely, it's the #DefaultLocation field, since it's a read only and you are resetting it after the first post:
document.getElementById('DefaultLocation').value = "";
And never changing it's value back to something (or are you?)
so you have to do one of the following:
don't reset it
set it's value with something after posing the form
don't validate it at all since it's a read only and you are using it as a hidden input (which is wrong by the way)!
also, it can be the other "ajax" code you are talking about so please post that too here, also maybe you have other fields (elements) somewhere else on the page with same IDs like the ones in the form..
anyway, here are sometips for you:
1- close the input tags correctly (add / to the end of it):
<input type='text' name='Firstname' id='Firstname' />
2- make sure all DIVs and Ps are closed...as it seems that you have an open P here:
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
</p> <---- missing this one
<p id='cf_submit_p'>
3- you are redeclaring the error variable all the time, you don't need to do that:
if(Firstname.length == 0){
var error = true;
....
just use error = true; without var this applies on all places you are changing its value only use var on initialization:
var error = false;
4- instead of this:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
use:
$('#AddCaller').attr({'disabled' : 'disabled', 'value' : 'Adding...' });
5- if you are using DefaultLocation as a hidden field then instead of this:
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly />
</div>
use:
<input type="hidden" name="DefaultLocation" id="DefaultLocation" value="Something" />
Try to change from using the click event handler to the form's submit event handler
Change this : $('#AddCaller').click
To this : $('#AddCaller_form').submit
Do not remove the attribute of disabled, set it to false.
This line
$('#AddCaller').removeAttr('disabled').attr(...
should be
$('#AddCaller').attr('disabled', false).attr(...
I assume that by removing and adding attributes, the element is removed and replaced by the new one, but the handler is not re-attached. Try using $('#AddCaller').live('click', function(){ //code }) instead of .click()
This function send queries to php and can return results from the php file using ajax.
I have left comments for guide. the first part with try & catch statements does not need modifications. go to #1 and #2
function ajaxFunction(){
var ajaxRequest;
//Browser compatible. keep it as it is
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//Browser compatible end
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//#2 opional: create functions to return data from your php file
$('#resultArea').html(ajaxRequest.responseText);
}
}
//#1 Set the form method, filename & query here here
ajaxRequest.open("GET", "serverTime.php?query=something", true);
ajaxRequest.send(null);
}
example:
<input type='submit' value='ajax-submit' onclick='ajaxFunction()' />
quick jquery plugin for that since you might use this in almost every ajax form on your site:
it will disable all fields that could trigger a submit event and also add a class on the form tag so that you can apply some styling, or showing a load message when the form is submitted:
jQuery.extend(jQuery.fn, {
formToggle: function (enable){
return this.each(function(){
jQuery(this)[(enable ? 'remove' : 'add') + 'Class']('disabled')
.find(':input').attr('disabled', !enable);
},
enable: function(){ return this.formToggle(true); },
disable: function(){ return this.formToggle(false); }
}
then on your jq ajax code:
[...]
var $form = $(your_form).submit(function(){
$.ajax({
type: 'post',
url: "/whatever/",
data: $form.serialize(),
success: function (){ alert ('yay');},
complete: function(){ $form.enable();},
error: function(){ alert('insert coin')}
}
$form.disable();
return false;
});
It should be enough to properly block the submits while the forms is sending/receiving data.
If you are really paranoid you can add a check so that it cannot be sent twice between the moment the user triggers the submit and the fields get disabled with : if ($form.is('.disabled')) return false; as first line of the submit handler, but it shouldn t be necessary really
Set some breakpoints in Firebug and watch if it goes somewhere.
Button can lose its click handler after submit and applying effects. You probably need to assign click handler again after submit and stuff.
Not 100% on this but try setting the code as a separate function then rebinding the click event at the end.
Example:
function addCaller(e) {
// your unchanged code
$('#AddCaller').click(addCaller(e));
}
$(document).ready(function(){
// added an unbind just in case
$('#AddCaller').unbind('click').click(addCaller(e));
});
Try to change this:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
into that:
$('#AddCaller').attr({'value' : 'Adding...' });
This should make it work.