Taylor Liss
Taylor Liss

Reputation: 593

How to make page change with GET request in JavaScript with Node.js and Express?

In this app, the user has a table they can enter data into. Each row has an "Edit" button, and when they click that button, I want to take them to a new page called "/update" where they can modify the values in that row.

I have it now so that when they click the the update button, it runs the editRow function, passing along the id of the table, and the data in the row. However, I'm having trouble figuring out how to get the routes to work correctly.

I'm using Node.js, Express, Handlebars but no jQuery.

app.js (server side)

app.get('/update', function(req,res){
    var context = {};
    context.tableID = req.ID;
    context.element = req.element;
    res.render('update', context);
});

update.handlebars

<h1>test for now</h1>

main.handlebars

<!doctype html>
<html>
<head>
    <title>Workout Tracker</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="scripts/buttons.js" type="text/javascript"></script>
</head>
<body>
    {{{body}}}
</body>
</html>

buttons.js (client side)

function editRow(tableID, element) {

    var httpRequest;

    httpRequest = new XMLHttpRequest();

    if (!httpRequest) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
    }

    httpRequest.open('GET', 'http://localhost:3000/update');
    httpRequest.send();
};

With the new configuration above, I am now able to reach the /update code, but the render doesn't seem to be occurring. There are no error messages in server or client-side console.

Upvotes: 1

Views: 2362

Answers (1)

Brian Glaz
Brian Glaz

Reputation: 15676

As your error says, there is no get function on a XMLHttpRequest object. I think you meant to use req.open instead.

You can refer to this documentation which will show you how to make reuqests using XMLHttpRequest: https://developer.mozilla.org/enUS/docs/AJAX/Getting_Started#Step_3__A_Simple_Example

Upvotes: 2

Related Questions