Asynchronous API and callback - javascript

I have to use one asynchronous service. Everything I can do is send data to this service (I'm doing it with PHP and CURL) and send data to some url from this service. How can I react/wait for a response from this service?
Now I have two pages: first is sending data to service and the second takes a response from this service and inserts it to database. On a first page I'm checking some table while there isn't the response. But selecting from database few times per second is bad idea. But what I need to have: Send data from one page and get the response at the same page. I guess I can use some Ajax and make the async service sending data to the same page and wait for the response on this page.
I guess I wrote very hard because I can't fully explain what I need, so feel free to correct me.

As #Steve noted, PHP has no concept of asynchronousity. However there is a hack which allows to implement something similar to long-polling in PHP. The main point is to use a file ready to read in Javascript, i.e. JSON.
Here is a general flow:
Your single web page does AJAX request to your php script which send
appropriate request to the external service and immediately return
some response (e.g. empty) to the web page.
The web page starts to repeatedly request server for the same static
JSON file (by doing AJAX requests) until it appears (created by
callback script).
The external service passes response to your callback script which
save the response into the JSON file.
The web page get the response from the JSON file and outputs it.

Your easiest option is going to be ajax polling - send the request to the webservice, then poll every x seconds. The response handler (the script called by the webservice when it completes) need to save the data somewhere, eg database or session, and the poll script will check for this data.
Although this will add a little to server load, if you set the polling interval high enough it should be fine
session_start();
if(isset($_GET['sendrequest'])){
WebService:sendRequest(['callback_url'=>'thispage?receiveresponse=1'])
$_SESSION['response']=false;
die();
}elseif(isset($_GET['receiveresponse'])){
$response = WebService:receive();
$_SESSION['response'] = $response;
die();
}elseif(isset($_GET['checkresponse'])){
$data=[];
if($_SESSION['response']){
$data['success']=true;
$data['response']=$_SESSION['response'];
}else{
$data['success']=false;
}
header('Content-Type: application/json');
die(json_encode($data);
}
<html>
<head>....</head>
<body>
<a id="send" href="#">Send Request</a>
<div id="response"></div>
<script>
var poll;
$('#send').click(function(ev){
ev.preventDefault();
$post('?sendrequest=1', {...}, function(){
poll = setInterval(function(){
$get('?checkresponse=1', function(response){
if(response.success){
clearInterval(poll);
$('#response').html(response.response);
}
});
}), 3000);
});
});
</script>
</body>
</html>

Related

How to Redirect within a POST request in node js [duplicate]

I have a website where I want to provide an option for users, if they click on a table's rows, they get regirected to another page (based on the contect of the table row).
So what I'm doing is basically collecting the data with jQuery and POSTing that to a PHP file. In my PHP file I'd like to do the redirecting using header('Location: ***').
Is it a correct way to do this? Because this way, the ajax request does not gets anything returned, no success, no nothing, it get redirected before that.
So is it a path that I could use, or should I come up with another idea?
No.
A redirect tells the client that the resource they just requested can be found elsewhere.
The page that was previously loaded which contains that JavaScript is not the resource that the Ajax request is asking for. Something will be returned though—it should get the resource that you redirected to (which will be available in xhr.responseText (assuming the same origin policy doesn't interfere and that you get a 200 OK response at the place you are redirecting to)
If you intend to always redirect, then don't use Ajax.
If you intend to sometimes redirect, then you'll need to put the URL in the body of the response, parse it with JavaScript and then assign it to location.
You cannot redirect with PHP, however you can easily redirect with the response of your ajax call.
refer to: window.location.replace(...)
Yes and no. If you work with jquery, and your ajax call responds with a json like this:
{
success : true,
redirect_to : "http://www.google.com"
}
that in php means
<?php echo json_encode([
'success' => true,
'redirect_to' => 'http://www.google.com',
]);
then your ajax caller can do the dirty job:
$.get('/your/path', function (json) {
if(json.success) {
document.location.href = json.redirect_to;
}
}, 'json');
My two cents.
I basically want to get the id from the row and when the visitor clicks on the row, they should land on example.php?id=XXXXX
You can do so entirely from PHP. When you generate the table, in each row (whose id we'll call XXXX to follow your example) you can include a link to example.php?id=XXXXX, or an onclick event for the whole row that executes window.location.href = 'example.php?id=XXXXX';. So your table might look like:
...
<tr onclick="window.location.href = 'example.php?id=1234';">
<td>1234</td><td>some value</td><td>some other value<td>
</tr>
<tr onclick="window.location.href = 'example.php?id=1235';">
<td>1235</td><td>some value</td><td>some other value<td>
</tr>
...
It could be done a little nicer by generating the rows with javascript and using event listeners, but this should work.

Real Time Refresh / Update

I have a MVC 3 project that publish in a server.
Scenario
For example I have a function for saving a data from (PC1) to (PC2).
It is possible that the viewing of data(data in jqgrid) in (PC2) is open(open in page) by a user and it will auto refresh or update the page or the jqgrid after the (PC1) save a data?
My jqgrid version is 4.3.3.
Hope you guys understand what I mean in my post. Post feedback if down votes. Thanks.
Any help will be accepted.
You might wonna use ajax to accomplish such a job, please read below
if I understand what you mean, is that you wonna poll a server to realtime updates on either intervals or something else...
option 1
Issue a normal stateless ajax call to the server, then force the server to hold the request for a limited time [to overcome server overhead]
This can also be reffered to as reverse ajax or comet.
Unless you are planning to use websocket technology, I hardly stress that you try this.
if(isset($_GET['finite'])){
#declare time for a session
$_SESSION['typing']=$reduce_browser_overhead=time();
#remember to close the session before entering the loop;
#if u dont close, then the browser will not reload the same website untill the connection is close or satisfied
session_write_close();
function loop(){
#do this to access external variables ===> $reduce_browser_overhead;
global $con,$reduce_browser_overhead;
#explicitly check 2exit
#please do this to release mysql connection since they are in a loop
if($reduce_browser_overhead+4<time()){
echo ' ';ob_flush();flush();
if(connection_aborted()){
#do some work here before you finally exit the connection
exit;
}$reduce_browser_overhead=time();
}
#php prepare statement...
$looper=$con->prepare("SELECT ROW FROM TABLE WHERE ID=SOMETHING AND $_SESSION[typing]=SOME_ROW");
#The statement above willcause the loop to work
#If a table had been update and table has not yet updated, this sql will detemin by the current time
#meaning that if the time[integer] of SOME_ROW is not equal to the time in the session variable,
#then it will let go to the client and then again it will continue looping untill the time in the
#SOME TABLE ROW changes....
$looper->execute();
$looper->store_result();
if($looper->num_rows>0){
sleep(2);
#do some work before looping again
loop();
#you have to explicitly return to this loop to work as expected.
return;
}else{
#send back data to the user or the client listening on the connection
session_start();$_SESSION['typing']=time();session_write_close();
#update the session before finishing the request so that the next time the request comes, the time will be equal to the DBserver time in the row and hence causing the loop again and again => more like a cycle
echo 'After some time the server has received new data which is =>> '.$newdata;
}
}loop();
exit;
//In another file on in the same document as the php / your server file ==> do javascript below
//first issue a normal / stateless ajax request to the target server
$.ajax({
//All optional but url required!
url:'abc.php?var_one=blabla',
cache:true,//whether to cache the requests
timeout:(1000*60)*20,//timeoutthe request
success:function(data){
//if the server successfully completed the request
//do some work here with data returned
},
error:function(){
//if the server return an error
//do more work around
//or call the function again
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Is it possible to redirect the page with PHP after an Ajax call?

I have a website where I want to provide an option for users, if they click on a table's rows, they get regirected to another page (based on the contect of the table row).
So what I'm doing is basically collecting the data with jQuery and POSTing that to a PHP file. In my PHP file I'd like to do the redirecting using header('Location: ***').
Is it a correct way to do this? Because this way, the ajax request does not gets anything returned, no success, no nothing, it get redirected before that.
So is it a path that I could use, or should I come up with another idea?
No.
A redirect tells the client that the resource they just requested can be found elsewhere.
The page that was previously loaded which contains that JavaScript is not the resource that the Ajax request is asking for. Something will be returned though—it should get the resource that you redirected to (which will be available in xhr.responseText (assuming the same origin policy doesn't interfere and that you get a 200 OK response at the place you are redirecting to)
If you intend to always redirect, then don't use Ajax.
If you intend to sometimes redirect, then you'll need to put the URL in the body of the response, parse it with JavaScript and then assign it to location.
You cannot redirect with PHP, however you can easily redirect with the response of your ajax call.
refer to: window.location.replace(...)
Yes and no. If you work with jquery, and your ajax call responds with a json like this:
{
success : true,
redirect_to : "http://www.google.com"
}
that in php means
<?php echo json_encode([
'success' => true,
'redirect_to' => 'http://www.google.com',
]);
then your ajax caller can do the dirty job:
$.get('/your/path', function (json) {
if(json.success) {
document.location.href = json.redirect_to;
}
}, 'json');
My two cents.
I basically want to get the id from the row and when the visitor clicks on the row, they should land on example.php?id=XXXXX
You can do so entirely from PHP. When you generate the table, in each row (whose id we'll call XXXX to follow your example) you can include a link to example.php?id=XXXXX, or an onclick event for the whole row that executes window.location.href = 'example.php?id=XXXXX';. So your table might look like:
...
<tr onclick="window.location.href = 'example.php?id=1234';">
<td>1234</td><td>some value</td><td>some other value<td>
</tr>
<tr onclick="window.location.href = 'example.php?id=1235';">
<td>1235</td><td>some value</td><td>some other value<td>
</tr>
...
It could be done a little nicer by generating the rows with javascript and using event listeners, but this should work.

How to auto redirect a webpage from ajax response if the session is expired?

This is my javascript..
function rDir() {
window.location="./index.php?status=session";
}
my ajax response from php code is
<script type="text/javascript">
rDir();
</script>
if I use header('Location:index.php?status=session;); in php it works.. but it loads the index.php content inside div...
How do I load redirect a main page through ajax if the session has expired?
though im not very proficient in PHP but im assuming that if your session is expired then you will be getting a response code for redirection like 3xx. In which case browser automatically issues a new request and downloads the page to which the request redirects. This is done transparently to your ajax request so finally in the success handler you will get the HTML of the login page.
by the way you have written that you your self are setting Location Header im also assuming you are your self handling the requests even in the session is expired. in which case
1.either you can change the status code being returned.
2.use a ajax service inside a look checking session status at preodic intervals. if you find that session has expired redirect to the login page.
To achieve that their are a lot of ways:
1-The simplest:
Var MustBe = "script type="\text/javascript\">rDir();</script>";
if(Request.ResponseText == MustBe ){
rDir();
}
2-Professional:
$('body').append(request.responsetext);
3-A good way:
if(Request.responsetext.indexof("rDir();") !== -1){
rDir();
}
I have chosen those ways because it is simple to implement in your code.

how to send a single element from browser to server without reload

How can I send just one element from browser to server fast and without reloading browser page?
Is there an AJAX way to do this, that is a NON-FILE method? The opposite of ".load"?
.load works great sending a single element from server to browser without page reload.
How to do the opposite direction?
Browser is JavaScript.
Server is vxworks with windmarks.
PRESENT METHOD THAT WORKS BUT RELOADS PAGE:
Presently, the browser element is and I use submit to send it to the server, but this takes too long and reloads the browser page.
The element's innerHTML contains data formatted as a vxworks WINDMARK.
(When the vxworks server receives this submission, it reads the windmark and copies it to a 'C' string for backend software to process.)
If you're using jQuery and PHP then something like this should work:
JS:
$.ajax('doServerSuff.php?action1=saveLog', function() {
// do stuff after server received the data
});
PHP (doServerStuff.php):
<?php
if ($_GET['action1'] == 'saveLog') {
//do stuff
}
?>
You can get and send data using jQuery. using something like this:
$.post('urlfromserver',browserdata,function(datafromserver){
//do stuff
})
if you let me put a little bit more, it's a good idea to use JSON to send/receive data to/from server. Having that in mind, you can do something like:
$.post('urlfromserver',{browserdata: JSON.stringify(browserdata)},function(datafromserver){
javascriptObject = jQuery.parseJSON(datafromserver)
//do stuff
})
And in your PHP code, it would be as simple as using json_encode to send data to javascript and json_decode to receive data from javascript
UPDATE
Obtaining the data in the server should be as simple as requesting the object via post or get depending on your send method, and parsing the JSON.
In PHP, this is an example of obtaining data using the above code:
$dataFromBrowser = json_decode($_POST['browserdata'])
Use $.post in jQuery to send the data.
The load intruction can also be used to transmit data to the server:
$().load("url", {limit: 25}, function(){
//transmission finished
});
In this example the parameter limit with the value 25 wil be transmitted to the server.
Taken from:http://api.jquery.com/load/
You can simply do with the ajax call like this
$.ajax({
type: "POST",
url: "yourpage.php?id=someValue",
success:function(data){
//do some stuff here
});
I got it working. Here is the corrected JavaScript, from the above answer.
Here is how to change a single element at the server.
This is also an example of how to write to a vxworks windmark string at a vxworks web server, without reloading the page.
NOTE: no URL is specified, so that the same page is used.
$.ajax({
type: "POST",
url: "?general_page_to_MM_data_1_windmark=CCCCCCCCCCCCCC",
success:function(data_from_server){
}});

Categories

Resources