Skip to content
Advertisement

My page is not rendering when calling URL from AJAX

I have made a route which is called in a specific event(click event) through AJAX. My route is called but the page is not rendered with the call.

My AJAX function:

function showProfile(user_id) {
console.log("show pro:" + user_id);
$.ajax({
    url: "/users/profile?id=" + user_id,
    type: "GET",
    success: function (data) {
    }
});

}

My route:

router.get('/profile',middleware.ensureAuthenticated, function (req, res) {
console.log(req.query.id);
res.render('profile');

});

My code through which I am making the AJAX call

$.ajax({
        type: "GET",
        url: "/users/friendSearch/" + q,
        success: function (data) {
            console.log("here");
            //data = JSON.parse(data);
            var output = "";
            data.forEach(function (t) {
                output += '<div class="card three wide column" ' +
                    'onclick=showProfile(' + t.oAuth_id + ')>' +
                    '<div class="image">' +
                    '<img src="/assets/matthew.png">' +
                    '</div>' +
                    '<div class="content">' +
                    '<div class="header">' + t.firstName + " " + t.lastName + '</div>' +
                    '</div>' +
                    '<div class="extra content">' +
                    '<div class="ui button" onclick=addFriend('+t.oAuth_id+') ' +
                    'id="follow">' +
                    'Follow' +
                    '</div>' +
                    '</div>' +
                    '</div>'
            });
            document.getElementById("user_placeholder").innerHTML = output;

        }
    });

I am dynamically creating the HTML code and have added an onclick method in the div

I am able to print the id which I am sending through the AJAX call but my EJS page is not loading Thanks

UPDATE: I am getting a 304 on response

Advertisement

Answer

I suppose this is a problem with invoking a res.render() route via AJAX since it simply returns the HTML string (as you probably see in your Response Preview in your Developer Tools -> Network -> Response Preview), and not do anything else. So, I would suggest using something like this in concept:

function showProfile(user_id) {
    console.log("show pro:" + user_id);
    $.ajax({
        url: "/users/profile?id=" + user_id,
        type: "GET",
        success: function (data) {
            document.getElementById("userprofile").innerHTML = data
        }
    });
}

…in order to render the HTML data that the /profile route responded with, into

<div id="userprofile"></div>

Or, you can take a different approach by using res.json() to return data instead and manually outputting it to the HTML.

Answer to similar problem to yours: Express.js res.render not redirecting, just displayed in console

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