简体   繁体   中英

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.

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM