Using ajax long polling to update a response on my page from an external API

冷暖自知 提交于 2019-12-13 01:23:04

问题


I have the following ajax long polling script

(function poll(){
    $.ajax({ url: "<?php echo URL::to('/internal/v1/checkTxn');  ?>", success: function(data){
        //Update your dashboard gauge
        console.log(data.status);  //Data is getting logged
        if(data.status == 'success'){  //This condition is not being checked
            console.log('suucesful'); //Not coming
        }
    }, dataType: "json", complete: poll, timeout: 1000 });
})();

The backend PHP code is as follows

 if(isset($_POST['status']) && $_POST['status']){
            $data = ['status'=>$_POST['status']];
            $json = json_encode( $data );
           echo $json;
        }

Flow

  1. When I render the page, the ajax script runs and waits for response. When I checked the network tab, ajax was endlessly making requests to the URL specified.

  2. I get a form post from an external website to the backend PHP which I need to push to the jquery.

But when a post is happening, nothing is being logged in the console. But if I hard code some values in the $json and echo it, its coming up in the console.

I am facing two issues

  1. When a post happens on the PHP script, its not coming up in the ajax code.

  2. When I hard code (simulated the response posted by the external form post) the $json and echo it, its coming up in the console, but the condition for data.status== 'success' is not getting checked.

What is wrong in this. Am I missing something?

UPDATE

I could fix the "condition not being checked" as there was something wrong the json being echoed.

Now to avoid confusion, the flow for this

User open the page, 

> The ajax starts the long polling process to my PHP code, waiting for a
> response.User enters payment details in a form which is my html,clicks on pay, a pop up appears
> which renders the banks login page (Payment gateway).After user entering all
> details in the pop up (banks page), bank sents a server to server call about the status of
> transaction to my notificationURL
> ('mydomain.com/internal.v1/checkTxn'). As soon as I get a POST on this
> URL(I will close the pop up), my ajax polling should get the data posted to my PHP and there by
> I will show the status of TXN to the user on the same card form he entered his details earlier and
> the pop window closes. The response here is returned by my PHP code to the ajax.
The
> post coming to my PHP code is a server to server post which is posted
> by a Payment Gateway.

回答1:


1. let's debug this:

set your ajax error call back,

$(function(){

        (function poll(){
            $.ajax({ url: "http://tinyissue.localhost.com/test.php", success: function(data){
                //Update your dashboard gauge
                console.log(data.status);  //Data is getting logged
                if(data.status == 'success'){  //This condition is not being checked
                    console.log('suucesful'); //Not coming
                }
            },error:function(err){
                console.info('error fired...');
                console.info(err);
            }, dataType: "json", complete: poll, timeout: 1000 });
        })();

    });

run this, you will get console

error fired...
Object {readyState: 4, responseText: "", status: 200, statusText: "OK"}

2. Why went to error callback:

Why ajax response status is 200 and statusText is "OK" , error callback still fired instead of success?

Your AJAX request contains the following setting:

dataType: "json"

The documentation states that jQuery:

Evaluates the response as JSON and returns a JavaScript object. (...) The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.

This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".

Solution: make sure that the server returns valid JSON. It is worth noting that an empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.

3. Why ajax return invalid JSON:

In your mind, at server side, you checked the $_POST['status'] to make sure last call success in the loop poll, only $_POST['status'] is set, you will echo json, or it echo nothing.

But, unfortunately, at the beginning of the call loop, the first time the ajax called, you didn't set status to post. Then it echo nothing, then it went error callback, also went complete callback, then call again without status to post. See, it went a bad cycle.

4. Solution:

Set a status value to post at the first ajax call.

$(function(){

        (function poll(){
            var status = 'success';
            $.ajax({ url: "http://tinyissue.localhost.com/test.php", success: function(data){
                //Update your dashboard gauge
                console.log(data.status);  //Data is getting logged
                status = data.status;
                if(data.status == 'success'){  //This condition is not being checked
                    console.log('suucesful'); //Not coming
                }
            },error:function(err){
                console.info('error fired...');
                console.info(err);
                status = 'error';
            }, type:'post',dataType: "json", data:{status:status}, complete: poll, timeout: 1000 });
        })();

    });



回答2:


If you are using long polling, you could have a cache issue. First, when your post comes to your system, check that checkTxn changes. Last, you can add a random parameter (by adding date in millis, for example) in url query, you will not use it, but your server will think your requests are different.

Please, check it and let us know.

@Edit: Sure @Ajeesh, I'll explain it:

(function poll(){
    $.ajax({ url: "<?php echo URL::to('/internal/v1/checkTxn');  ?>?_ts=" + new Date().getTime(), success: function(data){
        //Update your dashboard gauge
        console.log(data.status);  //Data is getting logged
        if(data.status == 'success'){  //This condition is not being checked
            console.log('suucesful'); //Not coming
        }
    }, dataType: "json", complete: poll, timeout: 1000 });
})();

By doing this, cache will not be used, because all queries are different for your server/browser.

On the other hand, I ask you for any changes in your page when you receive the POST, so, if not, your ajax will never receive the notification, do you know what I mean?



来源:https://stackoverflow.com/questions/37129486/using-ajax-long-polling-to-update-a-response-on-my-page-from-an-external-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!