I know some PHP and now I want to combine it using ajax/jquery. Just for learning purpose im making some scripts. I wanted to make a register form that checks availability etc etc. But before I start to make such a script i’d wanted to do something easier just to check how it works.
My goal was a contact form with ajax and it works. Data gets sended to php validate script. Errors are saved in an array and it returns a list of errors or sends the message.
But I have a few questions:
- What if a browser doesnt support javascript. Is there a way to still send the message?
-
the submit triggers the ajax post function. what is the best way to add jquery validation before it goes to the php file (client side)
Contact AJAX Form
<script language="JavaScript" type="text/javascript"> function ajax_post(){ // Create our XMLHttpRequest object var hr = new XMLHttpRequest(); // Create some variables we need to send to our PHP file var url = "functions/validation.php"; var name = document.getElementById("name").value; var subject = document.getElementById("subject").value; var email = document.getElementById("email").value; var message = document.getElementById("message").value; var vars = "name="+name+"&subject="+subject+"&email="+email+"&message="+message; hr.open("POST", url, true); // Set content type header information for sending url encoded variables in the request hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // Access the onreadystatechange event for the XMLHttpRequest object hr.onreadystatechange = function() { if(hr.readyState == 4 && hr.status == 200) { var return_data = hr.responseText; document.getElementById("status").innerHTML = return_data; } } // Send the data to PHP now... and wait for response to update the status div hr.send(vars); // Actually execute the request document.getElementById("status").innerHTML = "processing..."; } </script>Contact form
text
<label>Name <span id="nameInfo" class="small">Add your name</span> </label> <input type="text" name="name" id="name" /> <label>subject <span id="subjectInfo" class="small">Add a subject</span> </label> <input type="text" name="email" id="subject" /> <label>Email <span id="emailInfo" class="small">Add a valid email address</span> </label> <input type="text" name="email" id="email" /> <label>message <span id="messageInfo" class="small">Your message min 20 chars</span> </label> <input type="text" name="message" id="message" /> <button type="submit" onClick="javascript:ajax_post();">Send</button> <div class="spacer"></div> <div id="status"></div>
If you built it properly it the form will submit the data normally if JavaScript isn’t available in the client. Progressive enhancement and should always be how JavaScript is used.
Use the
submitevent to capture the form data before submission.