0

I use the following function to make an ajax call to a PHP that retrieves data from a MySQL database whenever an onChange-Event occurs. The result of the PHP is a JavaScript function including some data.

Basically, I copied all the code down to xmlhttp.send() from W3Schools. Then, facing the problem of calling the JavaScript on my page, I added the part with $.getScript(...).

It works, but I have a feeling that calling getRun.php?run=... twice cannot be the best way.

function getRun(str) {
if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
} else { 
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;
        } 
    };
    xmlhttp.open("GET","getRun.php?run="+str,true);
    xmlhttp.send();
    $.getScript("getRun.php?run="+str, function() {
        setTimeout();
    });
}

}

Do you have any hints on what would be a better way?

heckerf
  • 33
  • 1
  • 7
  • Instead of returning the full JavaScript function in your Ajax request through PHP, why not include the function in your script, run your Ajax request, only return the data you need and pass that to the function? – Milanzor Aug 29 '17 at 14:14

1 Answers1

0

To further explain my comment on your question:

  1. Define the function you want to run from your Ajax result
  2. Launch your Ajax request to your PHP backend.
  3. The PHP backend returns a certain result, be it a string or some JSON, up to you.
  4. Call the function in the Ajax success (or error, or complete even) callback.

E.g.

function getDataFromBackend(){

    // Your Ajax request
    // Seeing as you tried to use $.getScript, you might be using jQuery, so an example with jQuery
    $.ajax({
        method: 'POST',
        url: 'yoururl.php',
        data: {}, // You can put whatever data you wanna send in this object
        success: runMeWithData // The success callback runs the function when the Ajax request comes back without errors.
    });

}

function runMeWithData(dataFromAjax){
    console.log(dataFromAjax); // Show the output of your backend in the Console
}
Milanzor
  • 1,920
  • 14
  • 22
  • That sounds reasonable, thank you. Just have to figure out the exact code, but you guided me a good way. – heckerf Aug 29 '17 at 14:51