php - 即使页面卸载或重定向到另一个页面后,如何继续 AJAX/JQuery?

标签 php javascript jquery ajax redirect

我有一个脚本,可以将数据发送到 Web 服务并从 Web 服务获取响应。响应是一个链接/url,将用于检查注册状态。我使用 file_get_contents 从提供的 url 获取状态。获取状态后,用户将被重定向到页面。注册过程最多需要 10 秒才能完成,因此我需要使用提供的网址/链接再次检查注册状态。

PHP 不允许 header 位置重定向,因此我所做的是使用 jQuery 和 AJAX 来检查注册状态。它在页面尚未重定向时起作用。但在这种情况下,它不会起作用,因为页面会在 10 秒后检查注册状态之前先重定向到另一个 URL。

我希望这不会令人困惑。

这是我使用的代码:

<?php
    function sendRequest($url, $params)
    {
        $request = curl_init($url); // initiate curl object
        curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
        curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
        curl_setopt($request, CURLOPT_POSTFIELDS, $params); // use HTTP POST to send form data
        curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
        $response = curl_exec($request); // execute curl post and store results in $post_response
        curl_close ($request); // close curl object
        return $response;
    }

    function sendJSONRequest($url, $data)
    {             
        $data_string = json_encode($data);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);               
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);             
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);     
        curl_setopt($ch, CURLOPT_TIMEOUT ,50);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(                       
            'Content-Type: application/json',
            'Accept: application/json',
            'X-MP-Version: 10072013')                      
        );
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        ob_start();
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
        if ($result === false || $info['http_code'] == 400) {
          return "0";
        } else {
          return $result;
        }
        ob_end_clean();
        curl_close($ch);
    }

    function WriteLog($offer,$values)
    {
        $Filename = "./reports/".$offer.date('Ym').".txt";
        $fh = fopen($Filename, 'a') or die("can't open file");
        $filecontent = date('Y-m-d G:i').',';
        $filecontent .= $values;
        $filecontent .= PHP_EOL;
        fwrite($fh,$filecontent);
        fclose($fh);
    }

    // Get Variables sent from websites
    $uname = $_GET['un'];
    $usname = $_GET['ul'];
    $uphone = $_GET['up'];
    $uemail = $_GET['ue'];
    $testlive = $_GET['test'];
    $aff_id = $_GET['aff'];
    $unique_id = $_GET['uid'];
    $password = md5($_GET['pass']);
    $mnumber = $_GET['meter'];
    $bank = $_GET['bank'];
    $camp = $_GET['camp'];
    // Convert URL and Name split
    $rurl = 'http://'.$_GET['rurl'];

    // Determine if ReturnURL contains variables
    $pos = strpos($rurl,'?');
    if($pos === false) {
        $urlconnector = '?';
    } else {
        $urlconnector = '&';
    }

    // Split Name if no surname entered
    if (strlen($usname) > 0) {
        $firstname = $uname;
        $lastname = $usname; // I have a first and lastname
    } else {
        list($firstname, $lastname) = explode(" ",$uname,2); // I only entered my firstname
    }
    // Determine phone number format
    $phoneformat = strpos($uphone,'-');
    if($phoneformat === false) {
     // string - NOT found in haystack
     $phonesubmit = $uphone; 
    } else {
        $phone1 = substr($uphone,0,3);
        $phone2 = substr($uphone,4,3);
        $phone3 = substr($uphone,8,4);
        $phonesubmit = $phone1.$phone2.$phone3;
    }
    // Determine Live or Test
    $testlive = strtolower($testlive);
    switch ($testlive) {
        case "test":
            $debug=true; //Set this to 'false' to redirect users
            $mpurl = 'http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest'; // Set to TEST environment
            break;
        case "live":
            $mpurl = 'https://api.myprepaid.co.za/api/ConsumerRegisterRequest'; // Set to LIVE environment
            break;
    }

    // Set Variables
    $data = array("Email" => "$uemail", "Mobile" => "$phonesubmit", "Password" => "$password", "MeterNumber" => "$mnumber", "Bank" => "$bank", "CampaignID" => "$camp");

    $response = sendJSONRequest($mpurl, $data);
    ?>
    <!-- Hidden Fields for AJAX -->
    <input type='hidden' id='resp' value='<?php echo $response;?>' />
    <input type='hidden' id='rurl' value='<?php echo $rurl;?>' />
    <input type='hidden' id='urlconnector' value='<?php echo $urlconnector;?>' />
    <input type='hidden' id='firstname' value='<?php echo $firstname;?>' />
    <input type='hidden' id='lastname' value='<?php echo $lastname;?>' />
    <input type='hidden' id='phonesubmit' value='<?php echo $phonesubmit;?>' />
    <input type='hidden' id='uemail' value='<?php echo $uemail;?>' />
    <?php

    if($debug) echo "Response: ".$response."<br />";

    // If Customer Exists
    if ($response == "0"){
        header ("location: https://www.myprepaid.co.za?affid=1040");
    } else {

        $res = json_decode(file_get_contents($response), true);

        if($debug) echo "<pre>";
        if($debug) "\n" .print_r($res). "\n";
        $now = time();

        //Read values from response
        $rid = $res["ID"];
        $stat = $res["Status"];

        // Post to Trax

        $traxurl = "http://trax1.internetmarketingupstart.com/SP3o?"; //Trax URL
        $trax_post_string = 'aff_id='.$aff_id.'&aff_sub='.$unique_id;
        $trax_post_string .= '&aff_sub2='.urlencode($uname).'+'.urlencode($usname);
        $trax_post_string .= '&aff_sub3='.urlencode($uphone);
        $trax_post_string .= '&aff_sub4='.urlencode($uemail);
        $trax_post_string .= '&aff_sub5=';
        $trax = sendRequest($traxurl, $trax_post_string);

        if($debug) echo("\nTrax Result: {$trax} \n");

        // Redirect to Confirmation page provided
        $URL=$rurl.$urlconnector.'un='.urlencode($firstname).'&ul='.urlencode($lastname).'&up='.urlencode($phonesubmit).'&ue='.urlencode($uemail).'&status='.urlencode($stat);
        if($debug) echo("Redirect to Confirmation URL:\n{$URL}");
        if(!$debug) header("Location: {$URL}");


        if ($stat != "Successful"){

        //Recheck the registration status after 50 seconds using AJAX.

        echo "
        <script src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
        <script>
            alert('Registration may take about 50 seconds to complete. Please wait. You will be redirected when registration is complete.');
            setTimeout(function() {
                var value = $('#resp').val();
                var rurlval = $('#rurl').val();
                var urlconnectorval = $('#urlconnector').val();
                var firstnameval = $('#firstname').val();
                var lastnameval = $('#lastname').val();
                var phonesubmitval = $('#phonesubmit').val();
                var uemailval = $('#uemail').val();
                var rurl = rurlval+urlconnectorval+'un='+firstnameval+'&ul='+lastnameval+'&up='+phonesubmitval+'&ue='+uemailval+'&status=';
                $.ajax({
                    type: 'post',
                    url: 'get_resp.php',
                    data: {
                        resp:value,
                        rurl:rurlval,
                        urlconnector:urlconnectorval,
                        firstname:firstnameval,
                        lastname:lastnameval,
                        phonesubmit:phonesubmitval,
                        uemail:uemailval                    
                    },
                    success:function(data){

                        $('.response').html(data);
                        if (data == 'Successful'){
                            window.location.href = rurl+'Successful';
                        }
                    }
                });
            }, 10000);
        </script>";
    ?>
        <div class="response"></div>
    <?php
    }

    if(isset($_COOKIE['stat'])){
        $lateststat = $_COOKIE['stat'];
    } else {
        $lateststat = $stat;
    }

        unset($_COOKIE['stat']); 

    // Log Leads
        $logdetail = $aff_id.','.$unique_id.','.$testlive.','.$firstname.','.$lastname.','.$phonesubmit.','.$uemail.','.$rid.','.$lateststat.','.$trax;
        WriteLog("mypepaid",$logdetail);
    }

    ?>

如果您对我如何实现这一目标有任何建议,我将非常感激。谢谢。

最佳答案

在启动 ajax 调用的窗口已重定向到另一个 URL 后,您将无法继续访问该 ajax 调用的结果。整个上下文已被浏览器清理并且不再可用。

您需要停止重定向,直到完成 ajax 调用。一些可能性:

  1. 从重定向更改为通过 ajax 加载内容,这样您就可以在整个过程中保持原始文档打开,这样 ajax 调用将继续,您可以访问其结果,但同时也会显示新内容。

  2. 在 ajax 调用完成(在其完成处理程序中)之前不要执行重定向。

  3. 打开一个新窗口进行重定向,当 ajax 调用完成时,关闭该窗口。如果这些窗口位于同一域中,您可以访问它们之间的数据。就我个人而言,如果可能的话,我会避免额外的窗口。

关于php - 即使页面卸载或重定向到另一个页面后,如何继续 AJAX/JQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18501338/

相关文章:

php - 如何只为未登录用户取消注册Wordpress样式表?

javascript - 如何添加选项以选择从 PHP 中的 AJAX 请求收到的表单

javascript - RetrieveAttribute-一次性请求多个属性 (Dynamics CRM SOAP)

javascript - jQuery UI Sortable 当项目重新排列或在列表之间移动时触发

javascript - 如何在html文本区域逐行阅读文本?

php创建没有类的对象

php - Ubuntu server 20.4 nginx 在任何 php 页面上总是返回 404,html 完美运行

php - PHP中删除小数中无用的零位并删除2以上的小数

javascript - 将输入字段从一个字段复制到另一个字段?

javascript - Dynamoose 如何让多个模型共享一个表?