user3851557
user3851557

Reputation: 91

jQuery Ajax using Deferred object

I am using Ajax for ASynchronous post back and using Deferred object to wait for the response till i perform additional task based on the response.

Response message i am getting from PHP page and based on that i am performing further action on current page I want to know how do i pass response message(received from PHP page) from my Ajax function to deferred object. Also is my code correct?

Here is my code:

jQuery(document).ready(function($) {
var action = jQuery('#contactForm').attr('action');
function checkfunction() {
    $("#contactForm").submit(function() {
        return $.ajax({
            type: "POST",
            url: action,
            dataType: "html",
            data: $(this).serialize(),
            beforeSend: function() {
                //$("#loading1").show();
            },
            success: function(response) {


            }
            // return response;
        })
        return false;
    });
}
checkfunction()
        .done(function(response) {
            if (response == "success") {
                // Display success message
            } else {
                // Display Error message
            }
        })
        .fail(function(x) {
            // Display Error message
        }); 
});

Upvotes: 1

Views: 562

Answers (3)

Daniel
Daniel

Reputation: 4946

You need to build in a promise. There are ways as above shown, but I find the re-usability to be poor. Have a look at this structure.

var AjaxJSON = {
    send : function(url, data) {
        var def = $.ajax({
            method : "post",
            url : url,
            dataType : "json",
            data : data
        });
        return def.promise();
    }
};

$("#contactForm").submit(function () {
    var data = {formdata: $(this).serialize()}
    AjaxJSON.send("/my/path", data)
    .done(function(result) {
      if (response == "success") {
        // Display success message
      } else {
        // Display Error message
      }
    })
    .fail(function() {
       // do something
    });
}

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You are not returning anything from the checkfunction method, so your code should throw an error

One possible solution is to return a custom promise from checkfunction like

jQuery(document).ready(function ($) {
    var action = jQuery('#contactForm').attr('action');

    function checkfunction() {
        var deferred = $.Differed();
        $("#contactForm").submit(function () {
            return $.ajax({
                type: "POST",
                url: action,
                dataType: "html",
                data: $(this).serialize(),
                beforeSend: function () {
                    //$("#loading1").show();
                },
                success: function (response) {


                }
                // return response;
            }).done(function (data) {
                deferred.resolve(data);
            }).fail(function () {
                deferred.reject();
            })
            return false;
        });

        //return a new promise
        return deferred.promise();
    }
    checkfunction()
        .done(function (response) {
        if (response == "success") {
            // Display success message
        } else {
            // Display Error message
        }
    })
        .fail(function (x) {
        // Display Error message
    });
});

Upvotes: 0

jfriend00
jfriend00

Reputation: 707326

You've got things a big mixed up. checkFunction() is not returning anything. The two return values you have in it are inside of other callbacks that aren't called until much later - long after checkFunction() has already returned.

I'm not quite sure what you were trying to do with the structure, but you can use the jQuery promise that the ajax call returns like this:

$("#contactForm").submit(function() {
    $.ajax({
        type: "POST",
        url: action,
        dataType: "html",
        data: $(this).serialize(),
    }).done(function(response) {
        if (response == "success") {
            // Display success message
        } else {
            // Display Error message
        }
    })
    .fail(function(x) {
        // Display Error message
    }); 
    // prevent default action of submit button
    return false;
 });

Also, it isn't going to do you any good to put all this inside of checkfunction() because all that would do is install the event handler which is both something you only ever want to do once and something where the action only occurs later when the actual .submit() event happens.

Upvotes: 2

Related Questions