DROTH DROTH - 1 year ago 56
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() {
submitHandler: function(form) {
var $form=$(this)
var data= $form.serialize()

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:

var magnificPopup = $.magnificPopup.instance;

This is success for form 2:


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 Source

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) {
    var magnificPopup = $.magnificPopup.instance; 
} else {

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:




jquery AJAX and json format

Passing an array from PHP to Javascript using JQuery & JSON


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download