简体   繁体   中英

Calling PHP on another server from Javascript, and waiting for it to complete

I have a PHP script on my server that needs to be run from my clients websites using Javascript in a plain HTML page. After the script is run the HTML page will redirect. The problem is that sometimes the script doesn't run before the redirect happens.

This is the code I am using...

$.ajax({
     async: false,
     type: 'GET',
     url: 'the_URL_of_the_PHP_on_my_server.php',
     success: function(data) {
     }
});

window.location="the_URL_for_the_redirect";

The PHP script on my server is to track hits/sales etc. Is there are way I can force the page to wait for the script to complete before the page redirect.

The HTML page and the PHP page are on different servers. Also, the HTML page is being used on lots of different websites, so I can't give them all permission to access my server. I'm not sure if that's causing a problem or not.

I don't need any information back from the PHP script I just need it to run.

Thank you.

The success function runs when you get a response (unless it was an error, in which case the error function you haven't defined would run).

If you want some code to run after you get a response, put it inside those functions instead immediately after the code which sends the request.


That said: The point of Ajax is to talk to the server without leaving the page. If you are going to go to a different page as soon as you have a response, then don't use Ajax. Use a regular link or form submission and then having an HTTP redirect as the response.

This is normal, that this situation happens.

because $.ajax is async and won't wait till success method

change your code to

$.ajax({
     async: false,
     type: 'GET',
     url: 'the_URL_of_the_PHP_on_my_server.php',
     complete: function(data) {
          window.location="the_URL_for_the_redirect";
     }
});

UPDATED

changed function success to complete difference is => complete will be called not matters what happened with request


UPDATE 2

think about @Quentin variant by html redirects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM