Skip to content
Advertisement

Loading Images into Gallery using PHP and JavaScript takes very long sometimes

A callback function triggers when my XMLHttpRequest has finished. I use an asynchronous JavaScript Function to load the content of a file that has been created by the PHP file_put_contents() function.

My problem is, that sometimes loading the gallery elements takes a very long time. I should rather return the html code I want to load as a string instead of writing it into a file.. but I do not know how?

This is my Javascript:

function xhr(php, form, after) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            after();
        }
    }
    xhr.open('POST', php, true);
    xhr.send(new FormData($(form)));
}

How can I get the corresponding PHP script to export a String? I would need something that puts $myExportString as parameter inside after() then I could use it like this:

xhr("../session/searchquery.php", "searchfilterterms", function( myExportString ) {         

    document.getElementById("someDiv").innerHTML = myExportString;

});

How can this be done?

Advertisement

Answer

There’s no need to save a file on the server. You can just return the generated HTML string in the response to your XmlHttpRequest, and then write some Javascript to put that HTML into your page.

Otherwise a) you’ve got the overhead of disk I/O, and b) you’re having to make 2 requests to the server (one to generate the HTML, and another to retrieve the file it’s been saved to). This is not efficient at all.

In the PHP, instead of saving the generated HTML string to the disk, you can echo it, e.g. something like

echo $finalVariableWithHTMLString;

(I don’t know your exact code as it’s not shown in the question). If you echo it, then it becomes the contents of the response to the AJAX call. That’s how you return a response to a HTTP request in PHP – you echo stuff to the output.

You can then get it from the xhr.responseText variable in the JavaScript. So you’d be able to write

after(xhr.responseText);

in your example, to pass the HTML to your after() function.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement