Murad Elboudy
Murad Elboudy

Reputation: 483

How to make an ajax call in an express view

Is this AJAX code valid? I want the view to keep calling the same page so that if a user uploads a picture it simply appears to everybody on that page rather than having to refresh every now and then. I'm new to AJAX and still figuring it out. The picture do appear but not like I want them to. They're not getting styled by my css.

<script>
        $(function(){
            $.ajax({ url: 'http://localhost:3000/board'
                , type: 'GET'
                , dataType: 'html'
            })
            .done(function(data) {
                <% print.forEach(function(posts){ %> 
                    $('html').append('<div class="post-container">');
                        $('html').append('<h2> <%= posts.Title %> </h2>');
                        $('html').append('<hr>');
                        $('html').append('<a target="_blank" href=<%= "/viewer?id=" + posts.ID %>><img class="post-img" src=<%= "uploaded/" + posts.Img_path %>></a>');
                    $('html').append('</div>');
                <% }); %>
            })
            .fail(function() {
                console.log("Something went wrong!");
            });
        });

    </script>

And this is the route:

router.get('/board', function(req, res){
    connection.query('SELECT * FROM posts, function(err, result){
        if(err){
            throw err;
        }else{
            res.render('board', {print: result});
        }
    });
});

Upvotes: 0

Views: 40

Answers (1)

vijayP
vijayP

Reputation: 11502

Could you please try with following .done() handler:

.done(function(data) {
    <% print.forEach(function(posts){ %> 
        $('html').append('<div class="post-container">'+
                '<h2> <%= posts.Title %> </h2>'+
                '<hr>'+
                '<a target="_blank" href=<%= "/viewer?id=" + posts.ID %>><img class="post-img" src=<%= "uploaded/" + posts.Img_path %>></a>'+
                '</div>');
    <% }); %>
})

Otherwise your ajax call is fine.

Upvotes: 1

Related Questions