Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
Executing a PHP page from AJAX and waiting for the results

I'm fairly new to Javascript. I'd like to use Javascript to execute a PHP script on the server and capture the result (which is a few items of CSV text), and then use that result to update my webpage.

I already have a generic Javascript function to execute a PHP page, which is this:

function executePhpPage(url)
{
    // executes a PHP page
    try
    {
        httpxml = new XMLHttpRequest();
        httpxml.onreadystatechange = 
            function()
            {
                if (this.readyState == 4 && this.status == 200) 
                {
                    return httpxml.responseText;
                }
            }
        httpxml.open("GET", url, true);
        httpxml.send(null);
    }
    catch (e)
    {
        alert(e.message);
    }
}

However, control is returned to the caller when the thread of execution drops out of the bottom of the function, before any results are returned. Therefore, I've tried modifying it to this:

function sleep(ms)
{
    // see https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
    return new Promise(resolve => setTimeout(resolve, ms));
}

function executePhpPage(url) // returns the results of the page
{
    // executes a PHP page and returns the results
    try
    {
        httpxml = new XMLHttpRequest();
        httpxml.open("GET", url, true);
        httpxml.send(null);
        while (!(this.readyState == 4 && this.status == 200) )
        {
            sleep(10);
        }
        return httpxml.responseText;
        
    }
    catch (e)
    {
        alert(e.message);
    }
}

The call to the function is:

var host = window.location.protocol + "//" + window.location.host;
var url = host + "/AJAX_NewsletterSubscribe.php?email=" + cEmail + "&download=1";
alert(url);
results = executePhpPage(url);
alert(results);

'''alert(results)''' is never reached, the webpage becomes inactive and I have to kill it from the task manager. Presumably, it is looping round the sleep repeatedly.

How can I wait until the results come in before returning execution from executePhpPage and return the resulting data?

I'd prefer answers in straight Javascript rather than JQuery and or anything if possible. Thanks.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!