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'; } }));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)