get $.post to work with the validate plugin on multiple forms without seperate functions - jquery-plugins

On a fansite im doing http://yamikowebs.com/ee/
I have a few forms (2 atm). I used $.post to find out what form is being submited. submit the form and display that pages results where the form was originally with .html().
My next step was to use the validator which is working fine but im not sure how to put the 2 together.
submitHandler: function(form){} seems to be the setting for how its submitted. However, I can't get this to work with my $.post function or find out what form is being processed.
If I leave the defaults for validation plug-in if there no errors it will send you to the page. the ajax plug-in that it works with doesn't do what I want. Below is my $.post function
form validation:
//ajax post
$("form").submit(function(event)
{
event.preventDefault();//stop from submiting
//set needed variables
var $form = $(this)
var $div = $form.parent("div")
$url = $form.attr("action");
//submit via post and put results in div
$.post( $url, $form.serialize() , function(data)
{ $div.html(data) })
})
http://docs.jquery.com/Plugins/validation#source is the validation plugin

You're correct in thinking that submitHandler is the right callback to use. However, I ran into some interesting issues while using it with multiple forms (like you're trying to do). For example, in this code:
$("#form1, #form2").validate({
submitHandler: function(form) {
alert(form.action);
alert(form.id);
}
});
The submitHandler callback does not get supplied the correct parameter (it always gets #form1). I believe this is actually a bug in jQuery-validate (so I've filed it here).
Anyway, a decent workaround would be to wrap the validate call in .each():
$("form").each(function() {
$(this).validate({
submitHandler: function(form) {
/* 'form' has the correct value */
var values = $(form).serialize(),
$div = $(form).parent("div");
alert(form.action);
alert(form.id);
/* Perform AJAX call here */
}
});
});
Example: http://jsfiddle.net/andrewwhitaker/MmCXN/

Related

Send Multiple data with ajax

I want to use ajax for add data in database and i found following code in net and it is working fine.
<script language='javascript'>
reqObj=null;
function saveCust(){
document.getElementById('res').innerHTML='processing';
if(window.XMLHttpRequest){
reqObj=new XMLHttpRequest();
}else {
reqObj=new ActiveXObject('Microsoft.XMLHTTP');
}
reqObj.onreadystatechange=processSave;
reqObj.open('POST','./custSave?reqObj.open('POST','./cName?id='+document.getElementById('CustCode').value,true);,true);
reqObj.send(null);
}
function processSave(){
if(reqObj.readyState==4){
document.getElementById('res').innerHTML=reqObj.responseText;
}
}
</script>
Above code sends only one String but, i have 5 Strings in my form.
Please anybody alter the code for sending multiple data.
The problem is that you're sending a single parameter in the reqObj.open function:
reqObj.open('POST','./custSave?reqObj.open('POST','./cName?id='+document.getElementById('CustCode').value,true);,true);
Note that the only parameter you send is id.
You can add more parameters in the flavor of QueryString:
id=something&otherParameter=else //and more parameters
IMO the easiest way to handle an ajax request would be using jQuery, as shown and heavily explained by BalusC in How to use Servlets and Ajax?.
Based on the samples there and jQuery Ajax POST example with PHP, you can come with the following code:
Assuming the 5 Strings are in the form
function saveCust(){
$('#res').html('processing');
var $form = $(this);
var serializedData = $form.serialize();
$.post('./custSave', serializedData, function(responseText) {
$('#res').html(responseText);
});
}
Assuming there's data outside the form
function saveCust(){
$('#res').html('processing');
var $form = $(this);
var serializedData = $form.serialize() + "&id=" + $('#CustCode').val();
$.post('./custSave', serializedData, function(responseText) {
$('#res').html(responseText);
});
}
And you can even enhance this using more jQuery functions, but that's outside the scope of this answer.

jQuery .ajax 'success' function never runs

I am trying to use jQuery for the first time, and my POST function using .ajax is giving me grief.
The POST is successful; my PHP page runs the MySQL query correctly and the newly created user ID is returned. The only problem is that instead of running the 'success' function; it simply loads the PHP page that I called, which simply echoes the user ID.
Here's the jQuery function:
function register() {
$.ajax({
type: "POST",
url: 'sendRegistration.php',
data: dataString,
datatype: 'html',
success: function(response){alert(response);},
complete: function(response,textStatus){console.log(textStatus);},
error: function(response){alert(response);}
});
}
... and the PHP return stuff:
// Create a new send & recieve object to store and retrieve the data
$sender = new sendRecieve();
$custId = $sender->submitUser($userVars);
if ($custId != 0) {
echo $custId;
} else {
echo "Database connection problems...";
}
The database object is created, and then the php page from the 'url' parameter loads, displaying the id that the $sender->submitUser() function returns.
Ideally, I would like it to never display the 'sendRegistration.php' page, but run another js function.
I'm sure there's a simple solution, but I've not been able to find it after hours of searching.
Thanks for your help.
You are likely handling this from a form. If you don't prevent the default form submittal process of the browser, the page will redirect to the action url of the form. If there is no action in form, the current page will reload, which is most likely what is happening in your case.
To prevent this use either of the following methods
$('form').submit(function(event){
/* this method before AJAX code*/
event.preventDefault()
/* OR*/
/* this method after all other code in handler*/
return false;
})
The same methods apply if you are sending the AJAX from a click handler on the form submit button
how are you calling the register() function? It could be the form is being submitted traditionally, you might need to prevent the default action(standard form submit).

How to avoid redirect after form submission if you have a URL in your form's action?

I have a form that looks like this:
<form name="formi" method="post" action="http://domain.name/folder/UserSignUp?f=111222&postMethod=HTML&m=0&j=MAS2" style="display:none">
...
<button type="submit" class="moreinfo-send moreinfo-button" tabindex="1006">Subscribe</button>
In the script file I have this code segment where I submit the datas, while in a modal box I say thank you for the subscribers after they passed the validation.
function () {
$.ajax({
url: 'data/moreinfo.php',
data: $('#moreinfo-container form').serialize() + '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#moreinfo-container .moreinfo-loading').fadeOut(200, function () {
$('form[name=formi]').submit();
$('#moreinfo-container .moreinfo-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
Unfortunately, after I submit the datas, I'm navigated to the domain given in the form's action. I tried to insert return false; in the code (first into the form tag, then into the js code) but then the datas were not inserted into the database. What do I need to do if I just want to post the data and stay on my site and give my own feedback.
I edited Eric Martin's SimpleModal Contact Form, so if more code would be necessary to solve my problem, you can check the original here: http://www.ericmmartin.com/projects/simplemodal-demos/ (Contact Form)
Usually returning false is enough to prevent form submission, so double check your code. It should be something like this
$('form[name="formi"]').submit(function() {
$.ajax(...); // do your ajax call here
return false; // this prevent form submission
});
Update
Here is the full answer to your comment
I tried this, but it didn't work. I need to submit the data in the succes part, no?
Maybe, it depends from your logic and your exact needs. Normally to do what you asking for I use the jQuery Form Plugin which handle this kind of behavior pretty well.
From your comment I see that you're not submitting the form itself with the $.ajax call, but you retrieve some kind of data from that call, isn't it? Then you have two choices here:
With plain jQuery (no form plugin)
$('form[name="formi"]').submit(function() {
$.ajax(...); // your existing ajax call
// this will post the form using ajax
$.post($(this).attr('action'), { /* pass here form data */ }, function(data) {
// here you have server response from form submission in data
})
// this prevent form submission
return false;
});
With form plugin it's the same, but you don't have to handle form data retrieval (the commented part above) and return false, because the plugin handle this for you. The code would be
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm(function() {
// this call back is executed when the form is submitted with success
$.ajax(...); // your existing ajax call
});
});
That's it. Keep in mind that with the above code your existing ajax call will be executed after the form submission. So if this is a problem for your needs, you should change the code above and use the alternative ajaxForm call which accepts an options object. So the above code could be rewritten as
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm({
beforeSubmit: function() { $.ajax(...); /* your existing ajax call */},
success: function(data) { /* handle form success here if you need that */ }
});
});

MVC Form Validation

I am having trouble with my form validation. I have a form class with the Required attribute on it and I have ClientValidationEnabled to true in my web.config. I also have this call on my page #{Html.EnableClientValidation();}
I am using ajax form with the before submit option to catch the validation. Here is what I have:
$(document).ready(function () {
var options = {
beforeSubmit: ensureValid
};
$('#applyForm').ajaxForm(options);
});
function ensureValid(formData, jqForm, options) {
var result = $('#applyForm').validate();
console.log(result.valid());
return result.valid();
}
The code hits the ensureValid function but keeps continuing to the action in the controller even when I know a property should fire.
Thank you for any insight,
Brenna
If you are using asp.net-mvc-3, I would recommend at looking at using jquery.validate to perform your validation. It's far easier to setup, and generates cleaner code. You can see how to set this up in my blog post (I also cover a possible problem you could run into).

Jquery Validation Plugin, dynamic form validation

I'm using the Jquery Validation Plugin to forms loaded via Ajax (dynamic forms). I know that as of Jquery 1.4, live events on submit is now possible. Now the problem is I want to show a confirm message after the dynamic form has been validated. My code looks like this:
$('.dynamicForm').live('submit',function(){
$(this).validate();
if($(this).valid()){
if(!confirm('Are you sure?'))
e.preventDefault();
}
});
It's not working as expected. Somehow confirmation shows first, then at the second time I submit the form, that's the time the validation happens. Any ideas?
Somehow this seems to work:
$('.dynamicForm').live('mouseover',function(){
$(this).validate({
submitHandler:function(form){
if(confirm("Are you sure?")){
form.submit();
}
}
});
});
Use the submitHandler function available in the validate options:
$(".dynamicForm").validate({
submitHandler: function(form) { //Only runs when valid
if(confirm('Are you sure?'))
form.submit();
}
})
From the docs - submitHandler:
Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it validated.

Resources