Can't leave Page while Ajax (async) - javascript

I have the following AJAX call which needs up to 20 seconds to complete. I want the user to be able to leave the site while this call is loading and not finished.
However when the user clicks on a link or the back button the site is waiting for the call to finish before the user gets redirected to the previous site or the link the user clicked on
$.ajax({
url: 'index.php?route=sale/order/getSupportTickets&token=<?php echo $token; ?>&email=<?php echo $email; ?>',
dataType: 'json',
success: function(json) {
//do stuff here
}
});

An AJAX call is no different from a regular HTTP call (it just happens behind the scenes). As such the server is still executing this call (getSupportTickets).
It sounds like your web server is actually blocking (i.e. you don't have any threading support or the CPU is 100% busy) which is giving you this illusion of a blocking call

In your ajax call, use session_write_close(); once you got the data of the session you needed.
Only 1 php script can run with 1 php session at the same time, sessions are 'locked' to the current script. The scripts which use session_start() will be blocked on that instruction until the session is freed.
If you release the session by using session_write_close(); then your ajax script will be able to continue, while the new requests will be able to access the session (which is what was blocking).

Related

Ajax and page refresh

I am building a web app and one of the functionalities is to trigger an action in the backend which can take up to 5 minutes. This 'action' is a process which will run totally on its own (regardless of the front-end/back-end of my web app).
There is a form on the client-side which I use JavaScript to grab the data, clean it up/validate and send an Ajax call to my backend to start the process (which can take up to 5 minutes).
My question is, what if the user refreshes the page? The backend will still be triggered and run on its on, but I wanted to be able to capture the response back to the browser once the process is done in the back end. Is that viable/possible?
My Ajax is a pretty simple POST request to my backend:
$.ajax({
type: 'POST',
url: '/add-user',
data: {'data': JSON.stringify(data)},
//contentType: 'application/json;charset=UTF-8',
success: function(response){
console.log(response['message'])
}
//timeout: 3000 // sets timeout to 3 seconds
});
Please refer to this question prompt-user-before-browser-close
The only solution is to display a loading bar or spinner on the page while your page is waiting for the server task to finish.
If the user wants to navigate away you can use the confirm prompt.
I highly suggest using a websocket connection and if the user really closes, then inside window.onbeforeunload you should send a message and notify the backend to cancel the request context and stop the task from running. Running something like this without this protection can make your backend easy to get bombed.
PS. If it's a process independent of your backend then you should have scripts in place to kill it if the request context is canceled.

overcome ajax page refresh

I am building a application with many form submissions and using ajax to send data to server (node js). I have a table to be updated on a button click , and on click I need to load a spinner and call the ajax post request to server. On server it takes some time to update and send back result to ajax success. So on ajax success I hide the load spinner and update the data to table. Everything works fine problem is meanwhile when ajax req is called and server side is executing query the user may reloads the page, when page reloads ajax call is cleared so i cannot hide the load spin and update success data to html. What is the possible solution to avoid this
$.ajax({
url: url,
type: 'POST',
processData: false,
contentType: false,
data: formdata,
success: function (data) {
if (data.status == 'Success') {
toastr.success(data.msg);
// code to hide load spin
// update result data to html
}
})
You can do three things listed below in the order of complexity:
1. Put warnings on the page for users not to press reload or back buttons. This approach is often adopted on payment gateways when credit card details are verified server side. You can show a modal dialog box with the warning and spinner graphic.
2. Use session variables on server side to detect interruptions to ajax calls. For example you can have a variable called ajax_status (values none, incomplete and complete). You can set this variable at the start and successful completion of an ajax call. On page load, if you find the variable set to incomplete, show an error message, saying ‘something went wrong, have you pressed the reload button?’
3. Extend the 2nd approach to save ajax call parameters and reinitiate the request on page reload (show a warning saying data refresh was interrupted and reinforce message re not reloading).
You can avoid a page refresh(re-load) while all of your code is being executed by changing your html form action -
<form id="myForm" action="javascript:void(0)"></form>
This will also maintain HTML standards without fancy code to manipulate element functions.

AJAX page redirect properly. But because of redirect the passed data going to refresh

I am performing a ajax request but ajax request working fine. but the problem is after the request i am performing a page redirect. Because of previously passed variable values are going to reset. Following is my ajax call
$.ajax({
url: "http://localhost:8080/UserCreater/UserCreatorSub.jsp",
type: "POST",
data: {"subuserId":subuserId},
success: function(){
debugger;
window.location.replace("/UserCreater/UserCreatorSub.jsp");
}
});
Page is calling 2 times. Thats the problem .
Since the Response code of the Request is 302, the Browser automatically redirect to the url in the response irrespective of the location you want to redirect.
The main purpose of Ajax is to avoid page redirections/refresh (most of the time). You may want a simple request instead, since you're redirecting on the very same page.

Get from which IP a page was accessed via AJAX request in PHP

I have a simple AJAX GET request going to a certain PHP page:
$.ajax({
type: "GET",
url: "http://example.com/remote.php",
success: function(response){
document.getElementById("test").innerHTML = response;
}
});
The remote.php page echoes the $_SERVE['REMOTE_ADDR'] variable. The response of the AJAX request is the IP address of the client itself (from which a user is navigating from).
The JS file containing the AJAX request is located on the same server, e. g. http://example.com/js/ajaxstuff.js.
My objective is to get from which website the PHP page was accessed from, in order to prevent users simply going on the PHP page itself to gather information. Basically, I am trying to get a result of http://example.com or the IP of said server when the page is accessed from AJAX, or the user's IP address if the PHP page was accessed from its browser directly.
Well you could use a ref tag in PHP but this would not give you the correct way of getting this to work.
Option 1: Database.
A way that I would make instead would to create a mysql field with the ip and last loaded in another ajax call that would work as access control. For instance you add that into the normal page and load it with javascript for instance with setInterval() function in javascript.
When that ajax is called then the ip will be added into the table and that sets a unix timestamp.
If that timestamp is longer than 2 minutes since last load then you block your normal script for accessing. This way you can also insert a function to block ips that you know is fake or not good for your script.
Option 2: Set Session in the main php loading page.
You can create a session that you set a magic key for instance $_SESSION["access"]="YOU SECRET KEY"; and then check if this one is inside the remote.php
I would prefer the database version.

Jquery PHP ajax show server response as it send it

I'd like to know if there is a possibility to show server response as it send it in real time in a long time consuming request.
Context:
1) A Jquery function send an ajax request to the server and open a Dialog widget waiting for response to update Dialogs content.
2) The PHP server process the request in a long time consuming process, 20s, or much more up to minutes, it's an intranet website the user knows thongs takes time, lots of stuff to manage.
While the server is working, I have several "echo" in my PHP code with some stuff to say and the server is still working on other things to "echo" more.
My problem is that the Dialog don't updates as long as the server has not finished.
I want to show the partial response in live as soon as the browser receives it, with a SINGLE Ajax call from a unique function.
So... Two questions in fact:
Is my browser receiving the "echo" in live?
If Yes: How do I Show it live?
If No: How do I send it Live? And how do I Show it Live?
Any help would be greatly appreciated.
Thanks
Is my browser receiving the "echo" in live?
No, ajax waits for php to finish and then throws out all echoes at once.
If No: How do I send it Live? And how do I Show it Live?
I dont know a quick way to show it live but there are workarounds.
Create multiple ajax functions that will interact with the server to make it seem live. like I said in the comments. With this I am assuming you know how ajax works.
//javascript
function f1(){
//call ajax to tell the server send a start response
}
//php
echo "<img src='loading.gif'>";
//or something like it.
//ajax function to make the server do the data.
function f2(){
//call ajax to tell the server to start and save data in a session
//Or something like it also set div to be changed to a hidden div.
}
//php
//run the required script. then echo a finished response that can be found by js.
//to make it seem extra live you can split this up in different parts.
//so you can show progress to the client side. like step 1 of 5 complete.
//ajax function 3 for finished
function f3(){
//tell server to echo results once f2 is finished;
}
//php
//echo results loaded from where you saved it.
//probably session, delete the session when finished.

Categories