March 29, 201016 yr Hi, I hope I have posted in the right section. I want to validate a form using Javascript then if all fields are entered correctly pass it to a PHP script to process the form. How would I do this? Thx. Lee.
March 29, 201016 yr If you're using both, why not use AJAX (with jQuery) and let the form validation be mostly carried out by the PHP script (it'll look fancy!). I personally prefer validating a form via a PHP script, though empty fields could be caught by JavaScript to avoid unnecessary script execution. A few links to get you started; jQuery jQuery AJAX API W3Schools JavaScript Tutorial
March 29, 201016 yr good call, this is one way of saving yourself some effort - although pure JS validation is quicker and affords more options (i.e. real time validation) - plus some forms are not so easy to AJAX. Either way, don't rely on JS for validation, you should ALWAYS validate server side first.
March 29, 201016 yr Here's a little demo for you to use... mail_js.js (Requires jQuery) function sendForm(name,surname){ $.ajax({ url: "mail.php", data: "name="+name+"&surname="+surname, type: "POST", dataType: "html", success: function(data) { $('#message').html(data); } }); } mail.php if (($_POST['name']) && ($_POST['surname'])) { //Do some validation die('<span style="color:green;">Success. Thanks '.$_POST['name'].'!</span>'); } else { die ('<span style="color:red;">Required fields not input!</span>'); } index.html <form action="" method="post" onsubmit="sendForm(this.name.value,this.surname.value);return false"> <label>Name: </label><input type="text" name="name" /><br /> <label>Surname: </label><input type="text" name="surname" /> </form> <div id="message" style="font-weight:bold;"></div> Edit: I've added an attachment of the 3 full files all working. You'll need to add your own fields and validation to the PHP and HTML/JavaScript files. ajax_example.zip Edited March 29, 201016 yr by andyl
March 29, 201016 yr Author Thanks very much for your help guys. I have previoulsy used PHPMailer with forms before & I'll go with your advice & validate server side. Thanks for the examples as well. So how does Ajax & jquery differ from PHP & Javascript? Sorry i'm new to this.
March 30, 201016 yr Hang on... do you have control over the documents? By this, I mean, can you change them if you feel like it? If you can't then ignore this post, but if you can there's a much simpler way than trying to get your head around AJAX. Simply put all your server-side validation in the document that processes the form you've sumbitted. Tweek your form to give it an onsubmit handler that looks a little like this: <form id="myForm" method="post" action="myProcessingDocument.php" onsubmit="return validateMyForm()"> In your JavaScript, check all the fields you want to check in the validateMyForm function. If they're all fine, return true, if anything's wrong, return false. If you return false, the form won't submit.
Create an account or sign in to comment