简体   繁体   English

在ajax成功内触发php脚本

[英]Trigger php script within ajax success

I've searched and cannot find an answer to this. 我已经搜索过,但找不到答案。 I have an ajax that loops and waits for a variable and when it does not equal 0 I want to send the data to another script so that it can update the db and then it redirects to another URL. 我有一个循环并等待一个变量的ajax,当它不等于0时,我想将数据发送到另一个脚本,以便它可以更新db,然后将其重定向到另一个URL。 I've tried .post and .get and cannot get the values to update the db but the script does redirect. 我已经尝试过.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"; 
                            }
                }             
            });              
        }

Here is my update-pending.php that I am sending the variables to first before it redirects. 这是我的update-pending.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();

You are leaving the page immediately after running the JS that triggers the POST request. 运行触发POST请求的JS后,您将立即离开页面。 This causes the POST request to be cancelled. 这将导致POST请求被取消。

You need to wait until you get a response to the POST request before setting location to a new value. 您需要等到收到POST请求的响应后,再将location设置为新值。

IMPORTANT: Check the last part of the answer, you NEED to change your PHP code in order to avoid SQL Injection. 重要信息:检查答案的最后一部分,您需要更改PHP代码,以避免SQL注入。

You are generating the corresponding promise for the POST request, but it never is executed because you are leaving the page before that happen. 您正在为POST请求生成相应的Promise,但是由于在此之前您要离开页面,因此它从未执行。

Simple call .done method with a callback as a parameter from your $.post() promise, that callback it's going to be executed after the post succeed, also yo can consider add a .fail() that it's going to be executed if the post fail. 使用$ .post()承诺中的参数作为回调简单地调用.done方法,该回调将在发布成功后执行,也可以考虑添加.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
};

In the server you need return a response to the post request at the end of the process. 在服务器中,您需要在流程结束时返回对发布请求的响应。 If not you $.post will return error and execute .fail() always. 否则,$ .post将返回错误并始终执行.fail()。

If you can't / don't want to wait the php script finalize its execution to redirect the user to redirect.com consider to execute a secondary script in the background in the server. 如果您不能/不想等待php脚本完成其执行以将用户重定向到redirect.com,请考虑在服务器后台执行辅助脚本。

I updated your pending.php to use PDO: 我更新了您的pending.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.

No tested (Can't now) but you get the idea. 没有经过测试(现在不能),但是您知道了。

1) The easiest way to address this is to make use of the built in javascript function settimeout(). 1)解决此问题的最简单方法是利用内置的javascript函数settimeout()。 But dealing with set timers is scary because you don't know when the script is going to complete. 但是处理设置计时器很可怕,因为您不知道脚本何时完成。

2) The not-so easiest way to address this is to implement a callback function that gets triggered after the first method completes. 2)解决这个问题的最简单方法是实现在第一个方法完成后触发的回调函数。 Actually, it's not that hard to build. 实际上,构建起来并不难。

3) The other way may be implementing some form of "jsonp" implementation for working with and interacting with your php script. 3)另一种方法可能是实现某种形式的“ jsonp”实现,以便与您的php脚本一起使用并与之交互。

If it's a quick hack, just go with option 1. If not, play around with a combination of 2 and 3. Good luck partner. 如果这是一个快速技巧,那就选择选项1。否则,请选择2和3的组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM