0

I have called .ajaxSubmit() to submit data and after saving data successfully, upon response from server, I am redirecting user to next page using JavaScript. Issue is this redirect works most of the time but for 5 to 10 percent times it just displays the server response as text in browser instead of redirecting user to next page.

UPDATE START

One strange thing that I just noticed is that the page also gets redirected to the URL of form which is being submitted using .ajaxSubmit() means the server response displayed in browser has URL of form action.

UPDATE END

Please guide what is being done wrong here, why this random behavior?

Following is the code I am using:

$(document).ready(function () {

    function showResponse(data) {
        if (data.success == false) {
            alert(data.message);
        }
        else {
            var redirect = data.redirect_to;
            window.location.replace(redirect);
        }
    }

    var options = {
        success: showResponse, // post-submit callback
        dataType: 'json'
    };

    // bind to the form's submit event
    $('#signupForm, #mobileSignupForm').submit(function (e) {
        // inside event callbacks 'this' is the DOM element so we first
        // wrap it in a jQuery object and then invoke ajaxSubmit
        $(this).ajaxSubmit(options);

        e.preventDefault();

        // !!! Important !!!
        // always return false to prevent standard browser submit and page navigation
        return false;

    });
});
Umair Malhi
  • 565
  • 1
  • 5
  • 16

1 Answers1

0

It is quite possible that in server side you are not getting proper format response in this 5-10 percent times. Try to debug and check.

Ketan Vaghasiya
  • 384
  • 4
  • 13
  • Format of response is JSON in both cases, Firefox shows it as JSON in it's default JSON response window. – Umair Malhi Feb 28 '18 at 07:22
  • Have you debug the code server side to check if your request is not ending before it was suppose to end. – Ketan Vaghasiya Feb 28 '18 at 09:35
  • Yes, I am setting a variable for example `success = 1` at a single place on server side code and it's being returned properly. – Umair Malhi Mar 01 '18 at 05:11
  • If you haven't still figure it out. Send me both kind of responses. – Ketan Vaghasiya Mar 06 '18 at 13:26
  • **Response Headers:** `Access-Control-Allow-Headers:`Content-Type, X-Auth-Token, Origin, Authorization `Access-Control-Allow-Methods:`POST, GET, OPTIONS, PUT, DELETE `Access-Control-Allow-Origin:`* `Cache-Control:`no-cache, private `Connection:`keep-alive `Content-Length:`164 `Content-Type:`application/json `Date:`Tue, 06 Mar 2018 18:01:24 GMT `Server:`Apache **Response Text:** `{"success":1,"redirect_to":"https:\/\/www.examplesite.com\/cs\/1506\/page1?cid=15"}` – Umair Malhi Mar 06 '18 at 18:09
  • One strange thing that I just noticed is that the page also gets redirected to the URL or form which is being submitted using `.ajaxSubmit()` – Umair Malhi Mar 06 '18 at 18:10