drbxr86044 2012-02-15 21:46
浏览 50
已采纳

在链接重定向之前的ajax调用中的Php会话不起作用

I have a main page where you fill in some data. After you click on a link "create" it will call ajax to insert new record into mysql database (with data from main page). The mysql table where I'm inserting this new record has an auto_increment primary key and I need to know this key on page where the "create" link is redirecting. So to show it in a short simplified example I have something like this:

index.php has a link Create index.php has also this jquery $("#create").click($.ajax({ url: "create.php", cache: false, data: { ... some data from index.php ... } }));

create.php inserts record into database and after that does this $_SESSION["id"] = mysql_insert_id();

new.php needs to get this id from $_SESSION["id"]

When I tried to call ajax (insert record) outside of click event (so immediately after the main page has loaded) before I actually clicked the link it worked perfectly. However this way it works kind of randomly. Sometimes it does sometimes it doesn't and it never ever worked in Google Chrome this way...

I'm using session_start() properly in the beginning of the documents so there's no problem in this.

Thank you very much for any help I'm struggling many days with this and at last I located that the problem comes from this ajax call position in click event but I have no idea how to fix it. I guess that I'm missing some knowledge about how exactly do page redirecting and click event work together with ajax.

  • 写回答

1条回答 默认 最新

  • doupa8922 2012-02-15 22:13
    关注

    First your session has to be started in the index.php page so new.php and create.php will receive the session ID in the session cookie. You could theoretically call $.ajax then change the window location right after it. However this doesn't guaranty you that create.php as finished execution (ie. created the line you want and insert the data you want into the session which should be stored in your database). This can result in a race condition which you are experiencing.

    To fix this, you simply have to change your window URL in a function on Ajax call success like :

    $("#create").click($.ajax({ url: "create.php", cache: false, data: { ... some data from index.php ... }, success: function() { window.location = 'new.php'; } }));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名