2013-08-29 02:24
浏览 62

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

I have a script that sends data to and gets a response from a web service. The response is a link/url that will be used to check the registration status. I use file_get_contents to get the status from the provided url. After getting the status, the user is then redirected into a page. The registration process will take up to 10 seconds to complete so I need to check the registration status again using the provided url/link.

PHP does not allow to header location redirects so what I did was I used jQuery and AJAX to check for the registration status. It works when the page is not yet redirected. But in this case, it won't work since the page redirects first to another URL before checking the registration status after 10 seconds.

I hope this isn't confusing.

Here's the code I use:

    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);
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
        if ($result === false || $info['http_code'] == 400) {
          return "0";
        } else {
          return $result;

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

    // 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 = ''; // Set to TEST environment
        case "live":
            $mpurl = ''; // Set to LIVE environment

    // 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;?>' />

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

    // If Customer Exists
    if ($response == "0"){
        header ("location:");
    } else {

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

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

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

        // Post to Trax

        $traxurl = ""; //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("
Trax Result: {$trax} 

        // Redirect to Confirmation page provided
        if($debug) echo("Redirect to Confirmation URL:
        if(!$debug) header("Location: {$URL}");

        if ($stat != "Successful"){

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

        echo "
        <script src='//'></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=';
                    type: 'post',
                    url: 'get_resp.php',
                    data: {

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

        $lateststat = $_COOKIE['stat'];
    } else {
        $lateststat = $stat;


    // Log Leads
        $logdetail = $aff_id.','.$unique_id.','.$testlive.','.$firstname.','.$lastname.','.$phonesubmit.','.$uemail.','.$rid.','.$lateststat.','.$trax;


If you have suggestions on how I could accomplish this, I would be very grateful. Thanks.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanfen1992 2013-08-29 02:34

    You can't continue to access the results of an ajax call after the window in which it was started has been redirected to another URL. That whole context has been cleaned up by the browser and is no longer available.

    You would need to stop doing the redirection until you are done with the ajax call. Some possibilities:

    1. Change from redirection to loading content via ajax so you can keep the original document open during the whole process so the ajax call will continue and you can access its results, but you're also showing the new content.

    2. Don't do the redirect until after the ajax call completes (in its completion handler).

    3. Open a new window for the redirect and when the ajax call completes, close that window. If these windows are in the same domain, you can access data between them. Personally, I'd avoid the extra window if possible.

    点赞 打赏 评论
  • duanmu8911 2013-08-29 02:36

    Make the redirect be a part of the success callback for the jQuery AJAX call.

    If you redirect during the AJAX call, then it is essentially lost, because there is no longer any registered callbacks to handle the returned data. You cannot wire up a callback on the new page either.

    点赞 打赏 评论

相关推荐 更多相似问题