Search code examples
javascripthtmlfirebasegoogle-cloud-functionsxmlhttprequest

Functions redirect to webpage with XML request?


In my webpage i am uploading a image to firebase functions and processing that image and then wanted to load into another webpage named processed.html. I am using hosting and functions together.

this is the xml request :

var formData = new FormData();
    formData.append("file", sFile);
    formData.append("quality", sQuality);
    var ajax = new XMLHttpRequest();

    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", loadHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.open("POST", "/upload");
    ajax.send(formData);

function loadHandler(e) {
    //  
}

function errorHandler(e) {
    sFileLabel.innerHTML = e.target.responseText + 'Upload Failed';
} 

What i need is that i want to open webpage after the response finsih.

for that i tried the res.redirect(/processed?data=${base64data}); in firebase functions but it didn't worked as the page itself didn't redirected just logged as as xhr redirect response in network log. but no actual redirect of page.

how can i properly redirect to or load another webpage with that base64data as query so i can load that into that page.

Not loading the image in current page as other functionality provided in that page.


Solution

  • A redirect means what you asked for can be found here instead.

    A redirect does not mean load this page in the browser's viewport.

    You made the request with XMLHttpRequest. The browser will follow the redirect, get the resource from the URL it was redirected to, and make that data available in the response property of the XMLHttpRequest object.

    If you want a redirect to be loaded in the viewport, then you need to make the original request using a method that would load the response in the viewport. e.g. Use a regular form submission and do not involve XMLHttpRequest.


    If you want some logic that, depending on the response, sometimes modifies the current page with JS (sFileLabel.innerHTML = e.target.responseText + 'Upload Failed') and sometimes navigates to a new page, then you need to trigger the navigation with JS.

    location = "the new url"
    

    Of course, you need to determine what the new URL is, and an HTTP redirect will be followed transparently by the browser, so you can't read the Location header to determine it.

    That means you need to either hard code the URL client-side or change the server-side code so it returns data that the client-side JS can use to get the new URL. e.g. some JSON

    Content-Type: application/json
    
    {
        "success": true,
        "new_url: `/processed?data=${base64data}`
    }