POST variable from jquery redirecting but is not set

耗尽温柔 提交于 2019-12-02 10:57:06

The jQuery $.post() method is what is referred to as an asynchronous call. What this means is that while $.post() is trying to execute, any line of code after it will try to execute.

Note that you're redirecting immediately after your $.post(). This means that while $.post() is trying to run, you're redirecting to includes/changePage.inc.php, which is probably preventing the PHP redirect to ../secondPage.php from running. This is what we call a race condition, where two events are running simultaneously and either one could finish before the other with no way to keep the events synchronized.

What you're really trying to do, from what I can tell, is hand off processing of your data to PHP, then upon finishing, you want to redirect to a given page.

If I'm correct about this, then remove the window.location.href = "includes/changePage.inc.php"; line because otherwise you're always going to run into issues with this race condition. Handle the redirect in PHP--it should work on its own. If you're having trouble with redirecting directly in PHP, then you can redirect through jQuery:

Your jQuery POST

$.post("includes/changePage.inc.php", {message: message}, function(data) {
    var obj = $.parseJSON(data);
    window.location.href = obj.redirect_url;
});

What to return via PHP

echo json_encode(array('redirect_url'=>'includes/secondPage.php'));

If this doesn't meet your needs, then you'll need to really sit down and better explain your use case and your intent. If you can't explain it well enough to communicate exactly what you want, then you probably don't have a complete grasp of the problem you need to solve.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!