在 ajax 成功中触发 php 脚本

Trigger php script within ajax success

本文关键字:php 脚本 ajax 成功      更新时间:2023-09-26

我已经搜索过,找不到答案。我有一个循环并等待变量的 ajax,当它不等于 0 时,我想将数据发送到另一个脚本,以便它可以更新数据库,然后重定向到另一个 URL。我已经尝试了 .post 和 .get 并且无法获取更新数据库的值,但脚本确实重定向。

function updateTrigger(){
            $.ajax({
                url: "json.trigger.php",
                dataType: "json",
                cache: false,
                success: function(data) {
                    var scrape_type = data.scrape_type;
                    var account_id = data.account_id;
                       if(account_id != 0) {
                            $.post('update-pending.php', {account_id: account_id, scrape_type: scrape_type});
                            document.location.href="redirect.com"; 
                            }
                }             
            });              
        }

这是我的更新挂起.php我在重定向之前首先将变量发送到

$account_id = $_POST['account_id'];
$scrape_type = $_POST['scrape_type'];
$stmt = $con->prepare("UPDATE triggers SET
            pending='1'
            WHERE account_id = '$account_id' AND scrape_type =   '$scrape_type'") or die(mysql_error());
$stmt->execute();

运行触发 POST 请求的 JS 后,您将立即离开页面。这会导致 POST 请求被取消。

您需要等到收到对 POST 请求的响应后,才能将location设置为新值。

重要提示:检查答案的最后一部分,您需要更改PHP代码以避免SQL注入。

您正在为 POST 请求生成相应的承诺,但它永远不会执行,因为您在此之前离开了页面。

简单的调用 .done 方法,回调作为来自 $.post() 承诺的参数,该回调将在帖子成功后执行,您也可以考虑添加一个 .fail() 如果帖子失败,它将执行。

$.post( 'update-pending.php', {
    account_id: account_id,
    scrape_type: scrape_type
}).done(function() {
   document.location.href="redirect.com";
}).fail(function() {
//enter code here
};

服务器中,您需要在进程结束时返回对 post 请求的响应。如果不是,$.post 将返回错误并始终执行 .fail()。

如果您不能/不想等待 php 脚本完成其执行以将用户重定向到 redirect.com 考虑在服务器后台执行辅助脚本。

我更新了您的待定.php以使用 PDO:

//update-pending.php
/* Consider executing this in the background, (adapted) */
$account_id = $_POST['account_id'];
$scrape_type = $_POST['scrape_type'];
$params = array('account_id' => $account_id, 'scrape_type' =>  $scrape_type);
$query = "UPDATE triggers SET pending='1'
           WHERE account_id = :account_id 
           AND scrape_type =  :scrape_type";
$stmt = $con->prepare($query);
$stmt->execute($params);
/* End of background script  */
return true; // Return a response to the POST request.

没有测试(现在不能),但你明白了。

1)解决这个问题的最简单方法是使用内置的javascript函数settimeout()。 但是处理设置计时器是可怕的,因为您不知道脚本何时完成。

2)解决此问题的不太简单的方法是实现在第一个方法完成后触发的回调函数。实际上,构建起来并不难。

3)另一种方式可能是实现某种形式的"jsonp"实现,以便使用您的 php 脚本并与之交互。

如果是快速黑客,只需选择选项 1。 如果没有,请使用 2 和 3 的组合。 祝你好运的伙伴。