Validating forms returned by ajax - php

If i have a page which has an ajax link and that the code returns a that form needs validating, where do i put the validation code please. Say my form had this validation using the jquery validation plugin
jQuery(document).ready(function() {
$("#basicForm").validate({
showErrors: function(errorMap, errorList) {
// Clean up any tooltips for valid elements
$.each(this.validElements(), function(index, element) {
var $element = $(element);
$element.data("title", "") // Clear the title - there is no error associated anymore
.removeClass("error")
.tooltip("destroy");
});
// Create new tooltips for invalid elements
$.each(errorList, function(index, error) {
var $element = $(error.element);
$element.tooltip("destroy") // Destroy any pre-existing tooltip so we can repopulate with new tooltip content
.data("title", error.message)
.addClass("error")
.tooltip(); // Create a new tooltip based on the error messsage we just set in the title
});
},
submitHandler: function(form) {
var myselect = $('select[name=ddCustomers]');
//alert(myselect.val());
window.location.replace("customer.php?customer_id=" + myselect.val());
}
});
$("#basicForm").removeAttr("novalidate");
});
where do i put it as the document.ready where i would normally out this code has already been called
I hope this makes sense
Could i have it on the page in the initial page load ready for when the form is returned
I've read i coud have the validation in the document.on function but dont really understand. Would i post something like this back with my ajax response for the validation
$(document.body).on('click', '#basicForm', function(){
$("#basicForm").validate({
submitHandler: function() {
// do whatever you need here
}
});
});
Thanks for your help. Its confusing and I cant find a decent example on google
EDIT
I know how to write the validation code for the dynamically generated forms so thanks for those answers but I am alright on that. The question is WHERE that code should i put it in the ajax return?
Perhaps i have a misconception but i am using jquery validate module (base assistance( and i have only ever seen the `form validate method called in doc. ready on the first page - never an ajax postback
document.ready
Options
1) Hard coded in page already writing for when form injected by ajax? not dynamic enough - the injected form is created dynamically so the validation may need to
be
2) Add validation code to
document.on
when i do ajax postback for the new form? Is this even possible? Im not a client side programmer.
I am bemused that such a common scenario doesnt have a design pattern. Though i have read postng back forms via ajax is bad practice as it can confuse the browser and now what ajax whs written for so perhaps that why i cant find a solution
thanks

I've coded and developed many web apps just with jquery, php being the server side script. The way I formed was to have the jquery code and html on the same page since jquery needs to check the html element and respond with the proper error message and sanitize all the data fields before I submit to the "form-process.php" for an example if that was the name of your server side script.
Have:
$(document.body).on('click', '#basicForm', function(){
$("#basicForm").validate({
submitHandler: function() {
// do whatever you need here
}
});
});
code as the same page as say: create-username.html or create-username.php page
html elements. Some prefer to have jquery on the bottom, depends on how you have your
page structured, but I like to put the js on top from old practices although sometimes it doesn't apply to jquery.
include your tooltips code in the same block. I don't like to have jquery all over the place; incase of errors or if you need to modify in future reference it wouldn't be hard to pinpoint to edit, add or fix code. I hope this helps.

You need to initialize the validation plugin first and set up the rules you want. Then when a user submits the form, prevent the default form submission behavior and if all is validated successfully based on the criteria of the rules you set, you manually submit the form to the server using ajax.
$('#basicForm').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
$('document').on('submit', '#basicForm', function(e){
if($(this).valid()){
//client side is valid, make ajax call
}
e.preventDefault();
});

Related

Ajax, JQuery Validation, and MVC

I have an issue I can't seem to solve. First some context that may be relevant.
I am building a MVC-like (I say "like" because I'm still learning how MVC works) php framework for my software. I want all the input forms to submit data via ajax to a backend controller that routes the data and inputs it into the appropriate database. All the HTML code is generated through php classes and the JavaScript in included through php classes.
The problem I'm having is with the ajax function. It keeps trying to submit the post request normally while I want it to submit asynchronously. I've had it working properly at various points in time but it seems to break when I change aspects of the framework. I've tried various combinations of "form.preventDefault()" and "return false" but it doesn't seem to matter. The validation part works (it won't submit with invalid entries. Using this plugin). I discovered that JavaScript caches itself and I've worked through that by appending version numbers to the file name.
Here is the ajax code. It returns a message to the user about the status of the request. Any idea why it refuses to submit asynchronously?
$(document).ready(function() {
// Initialize form validation
***old code
$("form[name='ajaxform']").validate({ ***
// Specify validation rules
***Updated code
$('#ajaxsubmit').on('click', function() {
$("#ajaxform").valid();
});
// Initialize form validation
$('#ajaxform').validate({ ***
....[omitting the validation rules for brevity]
errorElement : 'div',
errorLabelContainer: '#usermessage',
submitHandler: function(form) {
$.ajax({
cache : false,
url : $(form).attr('action'),
type : 'POST',
dataType: 'text',
data : $(form).serialize(),
success : function(data) {
var response = $.parseJSON(data);
if(response['error']){
$('#usermessage').html(response['error']);
}else{
if(response['success']){
$('#usermessage').css({"color":"#00b300","font-weight":"bold"});
$('#usermessage').html(response['success']);
}
}
},
error : function(err) {
alert(err);
}
});
return false;
}
});
});
Here's how I've handled having problems with forms trying to submit even when I'm trying to preventDefault().
I haven't seen your HTML markup so I can't be certain.
If you have a
<button type='submit'>Submit</button>
Change it to
<button type='button'>Submit</button>
and then listen for the click on the button with javascript rather than a form submission
You can change the handler:
submitHandler: function(form) {
To handle the events as well:
submitHandler: function(form, event) {
event.preventDefault();

Submit a Form without Leaving Page

I am working on a survey that will go at the bottom of a FAQ page. My problem is that everytime a form is submitted, it sends you to a different page. I was wondering - is there a way to submit the form and have a little message that replaces the survey that says "Thanks for your feedback" instead of sending the user to another page or refreshing the page?
So far, I have a file that contains the HTML form, CSS, and jQuery and another file that contains the PHP connection to database and insertion of data to the database.
I would appreciate an explanation that is dumbed-down and an example would help since I am relatively new to programming.
An important note: My jQuery is set up to automatically submit if a user answers very helpful/extremely helpful. If not, two more questions appear below with a submit button at the bottom.
More specifically it looks like this:
$(document).ready(function() {
$('.rating').click(function() {
$('.rating').removeClass('selected');
ratingClick(this);
});
});
function ratingClick(that) {
console.log(that.id);
if (that.id == 'rating4' || that.id == 'rating5') {
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
$('#questions').submit();
} else {
$('#getMore').fadeIn();
$(that).toggleClass('selected');
}
}
$(document).ready(function() {
$('#submit').click(function(){
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
});
});
What you want is the jquery post function: http://api.jquery.com/jQuery.post/
Make sure your data is JSON.
$("#formdiv").click(function(){
$.post("somepage",{ yourformdata} );
$("#formdiv").replacewith("Thanks for filling out the form!");
});
You can use the replaceWith function to replace the desired content with the thankyou message.
Alex,
from the code you supply, the reason for leaving the page is due to the fact that you don't preventDefault() on the click event. Your page will always reload after that submit unless you take abortive action. No guarantees, but try a quick refactor to:
$(document).ready(function() {
$('#submit').click(function(e){
e.preventDefault();
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
});
});
This should get you a stage closer. You then just have the ajax logic to define, which should come good with a quick search to match your needs.

AJAX email form validation in AJAX loaded div?

I've created a pretty straight-forward site which loads all of its content via jquery .load() functions when you click the navigation links, and it works great. What I want now is to load in an email contact form with AJAX-style validation that alert the user about invalid input fields prior to running the php submission.
In other words, user clicks navigation link for "contact me" and a form is loaded into the content div. If the user enters an invalid name or email and hits submit, appropriate error messages will appear next to those input fields. I don't really care what happens after form goes through, whether it be a popup window or redirect page.
I've been trying to figure this out for weeks and I'm ready to give up. The form loads fine, but I can't figure out the basic construct for getting an AJAX loaded form to respond to the user without reloading the page and clearing their fields. I even got the php form submission part working exactly how I want, but getting client-side scripts to function with server-side php functions just seems arduous.
Is this even possible? How should I go about this? What are the basic concepts and tools for something like this?
What is your problem? Why can't you use a simple jQuery validator plugin?
Some examples:
Plugins/Validation/validate
jQuery plugin: Validation
Plugins/Validation
I got my form to work using the jquery validation plugin! Thanks to Praveen for suggesting it. It's a great tool.
The underlying issue was that I really wasn't wrapping my head around .load(). Once I utilized the .load() callback function, the validation ran fine. I created an external javascript file called contact.js which contains the validation plugin rules and submitHandler nested within contactPageScript() function. I called contactPageScript() with the .load() callback and voila:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript" src="js/contact.js"></script>
<script>
$(document).ready(function(){
$("div#menu ul li a").click(function() {
var whichPage = $(this).attr('href');
$('div#page_content').load(($(this).attr('href') + ' #contentB'), function(){
if (whichPage == 'contact.html') {
contactPageScript();
}}
);
});
});
</script>
</head>
The validation script of course also worked fine nested within the callback function rather than as an external .js, but it was too lengthy for my tastes. And there were some small details to be worked out regarding the validation rules. Here's the chunk of validation code I used just for reference:
$(document).ready(function() {
$('#mailform').validate( {
rules: {
fullname: {
required: true,
minlength:2
},
email: {
required: true,
email: true
}
},
messages: {
fullname: 'Please enter a valid name',
email: 'Please enter a valid email address'
},
submitHandler: function(form) {
$.post('php/submitForm.php', $('#mailform').serialize(), function() { DO STUFF });
}
});
});
At first I couldn't get the plugin script to work during debugging. Beware of extra commas after the rules! And also be advised that some copypasta tutorials contain hidden invalid characters within them! You'd never know! I had to rewrite the whole code by hand to get it to validate!
I later added nested if/else statements within the callback to call functions for all the other pages on the site which required jquery/javascript. At first I tried using a switch instead of nested if/elses, but it was not ideal. It helps to read the manual!
Cheers.

JS not working on echoed PHP

So I have a form that is submitted via an Ajax POST request. After the send button is clicked, the form is removed and a processing graphic is put in its place. The form data is sent to my PHP script, validated, and a thank you message returns to replace the processing graphic if everything checks out. But if there is a validation error, I have a copy of the entire form echoed back to the div where the original form was at showing where the errors are in the form. This all works fine except when the copy of the form is echoed back, the JS for the form doesn't work? Neither the JS for the send button or for my focus/blur functions on the inputs. Thank you for any help.
When you remove the form from the DOM, the events are cancelled as well. You can have a function that sets these events and call it when there are errors in the response.
Did you try to just hide your form and display the processing graphic instead of removing the form ? And when you have an error, hide the graphic and display the form again.
With this solution, error handling will be a little more difficult, but you will not have your form at 2 places in your project !
When you insert HTML mixed Javascript into some node, eg a div, it isn't the same as serving it the first time as part of the whole document. It isn't considered a script when inserted as innerHTML or some textnode.
You have a few options:
** Switch visibility and encode the errorresponse (in JSON for example)
Create 2 divs, one holding the form, the other the PROCESSING image.
Switch display to none for the form when processing, and the image to block.
When you have processed the form and you have an error, encode it somehow (JSON, eg) and send that back, and let an EXISTING script on the page interpret the response.
You can for example create some structure that holds each formelementname, and the error associated with it, so you can easily highlight them in your form if you create an empty span next to each formelement where you can display the error.
When the answer arrives from the server, you can display the form again, and display:none the PROCESSING div.
** Interpret your response (WITH JAVASCRIPT)
This is more difficult, but also more elegant.
I once needed this (Javascript that returned from an XHR request), and Randy Webb helped me out with a smart approach.
It is too much to explain here.
Read this thread for a more detailed approach, and links to the script of Randy:
http://tinyurl.com/6pakdu
$.ajax({
url: 'mypage.html',
success: function(){
alert('success');
**<ADD YOUR CUSTOM CODE AFTER AJAX SUCCESS - JS CODE>**
},
error: function(){
alert('failure');
}
});
You can also ref.
http://docs.jquery.com/Ajax_Events
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});

Rating system with jQuery, PHP and SQL: Passing rated value from javascript to PHP

I'm meeting huge problems while creating a rating system for my website.
I have no problem with PHP, but with Javascpit and jQuery.
My intentions are to give the rated value to PHP, and, also give some other variables that are into the page URI (like: ?pg=try&id=2).
Here what I do (and it work) util now:
$(document).ready(function(){
// START the RAtings script
$('.ratingStars').hover(
// Mouse Hover
function() {
$(this).prevAll().andSelf().addClass('overStar');
$(this).nextAll().removeClass('voteStar');
},
// Handle teh mouseout
function() {
$(this).prevAll().andSelf().removeClass('overStar');
set_votes($(this).parent());
}
);
// This make al clicable
$('.ratingStars').bind('click', function() {
////// HERE THE CODE TO PHP
});
});
I also need to know how to pass variables from PHP to Javascript...
Thanks in advice.
You will need to use AJAX to make a request to the backend. Have a look at http://api.jquery.com/jQuery.ajax/

Categories