user461316
user461316

Reputation: 913

Ajax/Jquery Redirect call does not work

So from my php, I am echoing {error:1}:

$(document).ready(function(){
    $('#form').submit(function(e){
        register();
    });
});

function register(){
    $.ajax({
        type:"POST",
        url:"submit.php",
        async : false,
        data: $('#form').serialize(),
        dataType: "json",
        success: function(msg){
            if(parseInt(msg.error)==1){
                window.location="index.html";
            }
            else if(parseInt(msg.error)==0){  
                $('#error_out').html(msg.error);
                e.preventDefault();
            }
        }
    });
}

But it does not want to redirect. Instead it return "submit.php" with 1 echoed.

Upvotes: 0

Views: 389

Answers (2)

John Green
John Green

Reputation: 13445

Well, you can't just have a return of 1, as that wouldn't be JSON. If you're just returning '1' and doing a parseInt on it, set the dataType to 'html'.


If you want JSON, do this in your PHP:

$return = array('code'=>1);
echo json_encode($return);

Your 'success' function would look like this:

if(msg.code==1){
    window.location="index.html";
}
else if(msg.code==0)
{
    $('#error_out').html(msg.code);
    e.preventDefault();
}
else 
{ 
   // handle any other return value.
}

Ok, my fault for not reading the problem properly. The problem is that you're submitting the form, and not cancelling it properly. Do this in your event handler:

$(document).ready(function(){
    $('#form').submit(function(e){
        e.preventDefault();
        register();
    });
});

You can remove the one in your failure case. That one doesn't do anything, since the stack would have already cleared by the time the async function came back (if it did at all).

Upvotes: 2

petraszd
petraszd

Reputation: 4297

You have to prevent form from submiting itself.

$(document).ready(function(){
    $('#form').submit(function(e){
        register();

        e.preventDefault(); // Or return false;
    });
});

Your form submits and ajax does not have chance to work its callbacks.

Upvotes: 1

Related Questions