Saturday 10 June 2017

How to redirect from an ajax request given that I need to render the page sever side from data I pass via ajax?

This is JavaScript on my page that is trying to redirect the user to /editUpload after it renders on the server given the data that's passed to it:

function editUpload(id) {
    id = {
        "id": id
    }
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            document.html = xmlHttp.responseText; //What should this line be?
    }
    xmlHttp.open("GET", '/editUpload', true); // true for asynchronous
    xmlHttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    var dataAsJson = JSON.stringify(id);
    xmlHttp.send(dataAsJson);
}

This is how the server responds to that request:

router.get('/', function(req, res, next) {
    //do stuff with id
    res.render('editUpload', {thingIDidWithId: data}); //or should this be return res.render('editUpload'); ?
});

I know that I could instead call window.location = '/editUpload?=id'

xmlHttp.responseText is returning the correct html, I want that to be the html of the page after the ajax call returns.



via Glen Pierce

No comments:

Post a Comment