6

I am tring to figure out how to use ajax in node.js I have this for now. How do i display for example order[0].name and order[1].name inside my div id="champ" when I press the button named Press.

app.js

var express = require("express");
var app = express();
app.use(express.static("public"));
app.set("view engine", "ejs");

var order = [
    {
        id: 1,
        name: "James",
        drink: "Coffee"
    },
    {
        id: 2,
        name: "John",
        drink: "Latte"
    }
];

app.get("/", function (req, res) {
    res.render("home", {order: order});
});

home.ejs

<!DOCTYPE html>

<html>
    <head>
        <title>
            AJAX calls
        </title>
    </head>
    <body>
        <h1>Ajax</h1>

        <% for (var i = 0; i< order.length; i++) { %>
            <div id="champ">

            </div>
        <% } %>

        <button>Press</button>

        <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
        <script type="text/javascript" src="javascripts/script.js"></script>
    </body>

</html>

script.js

$(function() {

    $("button").on("click", function () {
        $.ajax({
        type: 'GET',
        url: '/',
        success: function(result) {
             $('#champ').html(result);
        }
      });

    })

});

2 Answers 2

2

Your ajax call is going to return everything in home.ejs I think. It's been awhile since I've done express, but I think the render method will render your .ejs template. Meaning when you make the ajax call your entire template will be put into the $('#champ') selector. Also the $('#champ') selector is going to match on every div, but you're using an id on that element, and id's are reserved for individual items.

You already have the order data when you make a GET request to "/". So you could just build the div's on the server:

<% for (var i = 0; i< order.length; i++) { %>
    <div id="champ">
        <span><%= order[i].id %></span>
        <span><%= order[i].name %></span>
        <span><%= order[i].drink %></span>
    </div>
<% } %>
Sign up to request clarification or add additional context in comments.

4 Comments

You beat me to it and you are correct! That second paragraph and the code are most important
Hi. Thanks Richard. Yeah. It is returning everything. I know i can build the divs like that but I just made this simple example tring to grasp how to use and what can I do with ajax in node. Maybe I am way off with my example but if someone has an idea of a working code and how to achieve something similar it would be of a help to write it here.
I just added another answer.
How can I get updated response without reloading ejs page ?
1

I'm just copying code and making it up, it should point you in the right direction:

app.js:

var express = require("express");
var app = express();
app.use(express.static("public"));
app.set("view engine", "ejs");

var order = [
  {
    id: 1,
    name: "James",
    drink: "Coffee"
  },
  {
    id: 2,
    name: "John",
    drink: "Latte"
  }
];

app.get("/", function (req, res) {
    res.render("home");
});
app.get("/orders", function (req, res) {
    res.send(order);
});

home.ejs

<!DOCTYPE html>

<html>
  <head>
    <title>
      AJAX calls
    </title>
  </head>
  <body>
    <h1>Ajax</h1>

      <div id="target">
      </div>

    <button>Press</button>

    <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
    <script type="text/javascript" src="javascripts/script.js"></script>
</body>

</html>

script.js

$(function() {
  $("button").on("click", function () {
    $.ajax({
      type: 'GET',
      url: '/orders',
      success: function(order) {
        var html = '';
        for (var i = 0; i< order.length; i++) {
            html += '<h2>' + order[i].name + ' ' + order[i].drink + '</h2>';
        }
        $('#target').html(html);
      }
    });
  });
});

1 Comment

Thanks. I tried it. Something is not quite right in script.js. html is returning undefined and instead of order maybe it should be result. I will try changing around for it to work. Only concern is that I was trying to avoid logic in script.js and keep it all in ejs except the calls. Also we are making /orders just for this. When I have a lot of data to send this way from that database with lots of routes I can se becoming pretty messy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.