开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜