Ad

Update EJS Variables On AJAX Request

- 1 answer

I'm building a custom Shopify order management app using Node.js, Express and EJS as the templating engine. I want to have the page show the updated JSON data from the Shopify API without refreshing the page, e.g. new orders, order count etc.

I have managed to use an AJAX request which sends a GET request to:

app.get('/shopifycall', function(req, res) {
    res.send(jsonOrderCount);
});

The GET request returns the JSON data. I'm not sure how I can update the present .ejs variables that are set on initial API request/page render?

app.js

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

const app = express();

//View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

// Set Static Path
app.use(express.static(path.join(__dirname, '/public')));

var requestLoop = setInterval(function () {

var request = require("request");

  var options_orders = {
    method: 'GET',
    url: 'https://macwear-clothing-embroidery.myshopify.com/admin/orders.json',
    headers: {
      'Postman-Token': '',
      'Cache-Control': 'no-cache',
      Authorization: ''
    }
  };

  var options_order_count = {
    method: 'GET',
    url: 'https://macwear-clothing-embroidery.myshopify.com/admin/orders/count.json',
    headers: {
      'Postman-Token': '',
      'Cache-Control': 'no-cache',
      Authorization: ''
    }
  };


  request(options_orders, function (error, response, body) {
    if (error) throw new Error(error);
    jsonOrderData = JSON.parse(body);
    console.log(body);
  });

  request(options_order_count, function (error, response, body) {
    if (error) throw new Error(error);
    jsonOrderCount = JSON.parse(body);
    console.log(body);
  });

}, 8000);


app.get('/shopifycall', function (req, res) {
  res.send(jsonOrderCount);
});

app.get('/', (req, res) => {
  res.render('index');
});

app.listen(3000, () => {
  console.log('Starting MOS2...');
  console.log('Loaded on port 3000');
});

ajax.js

window.onload = function () {
    init();
};


function init() {
// Run AJAX JSON Call
setTimeout(getJSON, 9000);
}

// Shopifycall - AJAX

function getJSON() {
    $.ajax({
        type: 'GET',
        url: 'shopifycall',
        dataType: 'json'
    })
    .done(function(data){
        console.log('GET Response:', JSON.stringify(data, "", 2));
        console.log(data);

    })
    .fail(function(jqXHR, textStatus, err){
        console.log("AJAX ERROR", textStatus);
    });

    setTimeout(getJSON, 9000);
}

index.ejs

    <div class="infoSection">
        <h1 class="infoTitle" id="count">Current Orders: <%= jsonOrderCount.count %></h1>
        <h1 class="infoTitle">Time: <span id="time"></span></h1>
    </div>
    <div class="sectionMark"></div>
    <div class="orders">
        <div class="filter">
            <div class="orderFilter">
                <span><i class="fas fa-filter"></i></span>
                <span class="custom-dropdown big">
                    <select>
                        <option>Filter Orders</option>
                        <option>Flagged Orders</option>
                        <option>Unsent Needle Sheet</option>
                        <option>Sent Needle Sheet</option>
                        <option>Accepted</option>
                        <option>Rejected</option>
                        <option>Awaiting</option>
                        <option>Past Week</option>
                        <option>Past Month</option>
                    </select>
                </span>
            </div>
        </div>



            <% jsonOrderData.orders.forEach(function(item) { %>

                <div class="order itm<%= item.number %>">
                    <div class="orderDetail">
                        <strong>Order #: <%= item.order_number %></strong>
                    </div>
                    <div class="os"> Order Status: <%= item.financial_status %></div>
                    <div class="ns"> Needle Sheet:
                                            </div>
                    <div class="as"> Acception Status:</div>

                    <div class="btn upload" id="<%= item.number %>">
                        <div class="orderBtns">
                            <i class="fas fa-file-upload"></i>
                        </div>
                    </div>
                    <div class="btn send">
                        <div class="orderBtns">
                            <i class="fas fa-paper-plane"></i>
                        </div>
                    </div>
                    <div class="btn info">
                        <div class="orderBtns">
                            <i class="fas fa-info-circle"></i>
                        </div>
                    </div>
                    <div class="btn flag">
                        <div class="orderBtns">
                            <i class="fas fa-flag"></i>
                        </div>
                    </div>
                    <div class="btn close">
                        <div class="orderBtns">
                            <i class="far fa-times-circle" aria-hidden="true"></i>
                        </div>
                    </div>
                </div>

                <div class="fileUpload up<%= item.number %>" id="m<%= item.number %>">
                    <div class="fileUploadContent">
                        <h2>Customer: <%= item.email %></h2>
                        <div class="uploadFile">
                            <span>Upload File ></span>
                        </div>
                        <div class="optionalMessage">
                            <span>Optional Message:</span>
                            <textarea class="customTextArea"></textarea>
                        </div>
                        <div class="modalOptions">
                            <div class="mButton ok"><span>Ok</span></div>
                            <div class="mButton cancel"><span>Cancel</span></div>
                        </div>
                    </div>
                </div>

            <% }); %>
Ad

Answer

Do you understand that your EJS template is nowhere to be found in the client. It was long ago changed into HTML and sent to the browser. So, the client can't do any EJS at that point in the client.

So, your choices are these:

  1. Reload the page and let your server rerender the entire page and the browser will then display the rerendered page.
  2. Change your Ajax call on the server to return a newly rendered page body (the whole page body) and then have the client code replace the current page's body with the HTML returned from the Ajax call.
  3. Do client-side rendering instead of server-side rendering. Then, you can send the EJS template to the client and then anytime it gets new JSON from the server, it can rerender the EJS template and insert it into the current page.
  4. Manually insert JSON data into the page without EJS. When you get the JSON back from the server, process it and manually enter it into the right places in the page.
Ad
source: stackoverflow.com
Ad