DROTH DROTH - 1 month ago 8
Ajax Question

Ajax Multiple Forms with different Success functions

Thanks to help on StackOverflow I was able to validate and submit two forms to different action pages. I need to have the success functions change depending on which form was submitted.

This is my javascript:

$("form").each(function() {
$(this).validate({
submitHandler: function(form) {
var $form=$(this)
var data= $form.serialize()

$.ajax({
type : 'POST',
url : $(form).attr('action'),
data : $(form).serialize(),
cache : false,
dataType: 'text',
success: function(data){
},
});
return false; // Temporary
}
});


This is success for form 1:

$("#e1").prepend(data);
var magnificPopup = $.magnificPopup.instance;
magnificPopup.close();


This is success for form 2:

$("#messageTran").html(data);
$("#messageTran").hide();
$("#messageTran").fadeIn(1500);


What is the best way for me to achieve this? I am very new to javascript and haven't been able to find an answer for this. I have tried passing a form attribute with an if else statement, but have had no luck. Thank you in advance.

Answer

As you know, each action page will echo information back to the main page, which is available inside the AJAX success: function.

You can add a "header" to the returning data that identifies which action page is sending the data, then use an IF / ELSE structure to perform the appropriate action.

For example, action page first.php can send this text:

echo '1~This is from first.php';

In the success function, you can strip off that "header" character:

var hh = data.slice(0,1);
var therest = data.slice(2);
if (hh == 1) {
    $("#e1").prepend(therest);
    var magnificPopup = $.magnificPopup.instance; 
    magnificPopup.close(); 
} else {
    $("#messageTran").html(therest);
    $("#messageTran").hide();
    $("#messageTran").fadeIn(1500);
}

jsFiddle Demo


In response to a question re using JSON instead of a string that is manually parsed:

Of course one could use JSON, same principle. But much more challenging to explain in a concise answer. And for the JSON beginner, a significantly larger challenge than just using the above approach -- at least, it certainly was for me at first. Since the principle is the same, this is how I chose to communicate the concept.

For those seeking a demo that uses JSON, I can recommend these sources:

http://www.fourfront.us/blog/store-html-table-data-to-javascript-array

http://blog.kevinchisholm.com/javascript/associative-arrays-in-javascript

http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/

jquery AJAX and json format

Passing an array from PHP to Javascript using JQuery & JSON

http://xoops.org/modules/news/article.php?storyid=5103

Comments