Retrieve the information following a redirection

There is a page '/order/new' with 2 dropdown menus for customer and their address, along with a button that redirects to choose products to add to the order. The selected products are saved in an array called 'hh' which receives data from an AJAX call. However, when redirected, the selected customer and address information is lost.

I am looking for a way to retrieve the customer and their address after adding the product array.


global.hh = new Array();

module.exports = {

getProduct: (req , res ) => {
  var products = req.query.selectedProduct;
  var total = req.query.sumTotal;
 var btekh = hh.push(products)
}
getOrderProduct: (req , res) => {
  let query1 = "SELECT * FROM `product`";
  getConnection().query(query1 ,(err , result) => {
    if(err) {
     return res.status(500).send(err);
    }
    res.render('productOrder.ejs' , {
      products: result
    });
  });
},
addOrderProduct: (req, res) => {
  res.redirect('/order/new')
}


postOrder: (req ,res) => {
  var products = req.session.products;
    getConnection().query('INSERT INTO `order` ( clientId , addressId,orderStatusId) VALUES (?,?,?)', [req.body.selectUser, req.body.selectAddress,req.body.selectedStatus], (err,result) => {
    if (err) {
      console.log(err);
    }
  hh.slice(-1)[0].forEach(function (item) {
    let insertedOrder = result.insertId;
    let query = "INSERT INTO `orderProduct`( `orderIdProduct`, `productId`, `orderProductName`,`orderProductPrice`, `orderProductQuantity`, `orderProductTotal`) VALUES (?,?,?,?,?,?)";
    getConnection().query( query , [insertedOrder,item.check,item.name,item.p,item.q,item.total] , (err , result)=>{
      if (err) {
        console.log(err);
      }
      res.end();
  })
})
})
}
  res.redirect('/')
}
app.get('/order/new' , addOrderPage)
app.use('/postOrder' , postOrder);
app.use('/order/product' , getProduct);

AJAX code:

////////////////add users's address///////////////////////////
 $('#user').change(function(){

    var item = $('#user').val();
    $.ajax({
        type:'GET',
        data: { selectedId: item },
        url:'/users/address',
        success: function(data){
             $('#address').empty();
         $('address').append("<option disabled selected> Select Address..</option>");
         $.each(data, function (index, addressObj) {
                $('#address').append("<option value = '" + addressObj.addressId + "' > " + addressObj.addressName + " </option > ");
            });
        }
    });
   })

;
//////////////get the product to order/////////////
     $('#save').click(function () {
        var orderProduct = new Array();
        $("#table input[type=checkbox]:checked").each(function () {
                      var row = $(this).closest("tr");
                      var message0 = row.find('#check').val();
                      var message1 = row.find('.name').text().trim();
                      var message3 =  row.find('.currency').text().trim();
                      var message4 =  row.find(".foo").val();
                      const result =  {check: message0,name: message1,p: message3,q:  message4 ,total: message3 * message4}
                      var hh = orderProduct.push(result);
                });
                console.log(orderProduct);
                var totalPrice = 0;
             orderProduct.forEach(function (item , index) {
                totalPrice = totalPrice + item.total
              })
              $.ajax({
                type: 'GET',
                data: {selectedProduct: orderProduct , sumTotal: totalPrice},
                url: '/order/product',
                success: function (data) {
                  console.log(data);
                }
              })
               })

EJS template for '/new/order':

<header>
        <h2>New Order : </h2>
      </header>
      <form action="/postOrder" method="post" id="newForm" >
        <label> User Name:</label>
        <select name="selectUser" id="user" >
          <option disabled selected> Select User..</option>
      <% users.forEach((users) => { %>
        <option value="<%= users.id %>"  > <%=users.name %> </option>
        <%  })  %>
        </select>
        <br>
        <label>Address :</label>
        <select name="selectAddress" id="address">
          <option disabled selected> Select Address..</option>
      </select>
        <br>
        <label>Product</label>
      <a href="/orderProduct" id="addProduct"> add product</a>
        <br>
        <label>Status</label>
        <select name="selectedStatus">
        <% status.forEach((status) => { %>
            <option value="<%= status.statusId %>"> <%= status.statusText %></option>
        <%  })  %>
      </select>
      <br>
        <input type="submit" value="Save">
      </form>

Answer №1

within these sentences,

res.render('productOrder.ejs' , {
      products: result
    });

have you successfully retrieved all products from your database?

considering in your AJAX request,

$.ajax({
            type: 'GET',
            data: {selectedProduct: orderProduct , sumTotal: totalPrice},
            url: '/order/product',
            success: function (data) {
              console.log(data);
            }
          })

you're sending data but not utilizing it in your 'query1' statement here,

let query1 = "SELECT * FROM `product`";

I'm attempting to understand the progression of your program.

So a user visits your webpage, selects a product, your webpage communicates with your REST server with the product details, your REST server queries your database for that product, and then that information is displayed on this template?

res.render('productOrder.ejs' , {
      products: result
    });

EDIT: You need to handle user interactions using event listeners and manage user input with a storage method.

Your_client-side_JS_script.js

function handle_submit(e) {
  e.preventDefault();
  if (e.target.id === 'addProduct') {
    // When they click add product, you need to either pass their user details to the route and send them with the $.ajax GET request
    //... and keep track of the data like that
    // OR
    // track that data in a cookie,
    read up on cookies https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
  } else if (e.target.id === 'newForm') {
    console.log("Submit Form");
  }
};
$('#addProduct').on('click', handle_submit);
$('#newForm').on('submit', handle_submit);

I suggest using the cookie method. Set the cookie once, use it when needed, and then delete it when done.

Using the first method requires sending the data in your fetch (which doesn't necessarily require that data to fetch the products), and then managing that user_data throughout your backend to ensure it's not lost. It's too cumbersome. Opt for the cookie method instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The translation of the Ajax Jquery Post array into a C# List is not working as expected

We are implementing data binding using KO.JS with an observable array. Our approach involves utilizing Ajax jQuery Post to send the data over to the server. However, we have encountered an issue where the array from JSON is not being properly converted in ...

JavaScript Transforming an Array into an Object

After working with node and redis for a while, I've encountered an issue. When using hgetall in redis, it returns an object. { uid: '6203453597', first_name: 'Name', last_name: 'Surname', gender: 'male& ...

Automatically push updates to multiple servers simultaneously

I am currently running a Node.js web application on 3 servers to handle multiple user requests. The issue I am facing is that whenever I make updates to the source code, I have to individually access each server to retrieve the code from Bitbucket and re ...

Customize node.js response by overriding or adding another return statement

I have two variables, FirstName and LastName, that I need to include in the response data. It is important to note that the FirstName and LastName are not stored in the Student table. let result = await Student.get(id) let FirstName = "Paul" let LastName ...

What is the process to insert a record into a table by triggering an AJAX call upon clicking "save

I'm looking to dynamically update a table with data from a database using AJAX. Specifically, I want the table to reflect any new records added by the user without having to refresh the entire page. Below is my JavaScript code snippet for handling thi ...

A guide on rendering a JSON array received from a URL using AJAX in AngularJS

Upon receiving a JSON array from the following URL: , it appears like this:https://i.stack.imgur.com/1Xrf4.png Within my AngularJS controller, I have the following code: $('#example-1').DataTable({ "ajax" : 'http://blahblahbla ...

Automatically submitting forms without having to refresh the page

I have been searching for answers online, but none of them seem to help me. Additionally, I am struggling to grasp the concept of Ajax. I need everything to happen on a single page without any refreshing until the entire form is submitted. <form id=" ...

js-beautify: there was an error running the command in node.js

Can anyone help me with why I am having trouble running js-beautify? I installed it but it still doesn't work properly. ...

Tips for ensuring your anchor links function properly with Ajax interactions

I have been working on transferring data from a MySQL database using AJAX with JSON as the datatype. Below is the code I've used: $("#klik_cari").click(function() { //ajax configuration $.ajax({ url: "<?php echo ...

What is the best method for displaying the index page in node.js using ejs-templating instead of traditional express.static content?

When using a restaurant food menu generator, I am able to view it with HTML by utilizing the following code: app.get('/', function (req, res) { res.sendFile(__dirname + '/views/index.html'); }); This method uses express static. Bu ...

Are you familiar with manipulating the JSON data array retrieved from an Ajax response?

Is it possible to handle a response from AJAX request in PHP? I'm not very familiar with JavaScript, so I'm struggling with this one. This is what I have managed to put together: var base_url = 'http://dev.local/westview/public'; $(& ...

I am encountering difficulties trying to perform updates for node and npm

Currently running Ubuntu 18.04.6 LTS and trying to upgrade my nodejs to version 16, but facing challenges. I’ve already spent around 4 hours attempting to resolve this issue, with Stack Overflow being my last resort. Issues Encountered Encountering a ...

"Encountering a 'Cannot POST' error while working with

I am currently working on a form that dynamically adds user data to a table. You can view the final form layout here. However, when clicking on the "Use this account" button, an error message saying Cannot POST /like appears. The form is created using EJ ...

passport.socketio & client-side connection/reconnection only occurs upon server reboot

I have a real-time application that functions properly with express and passportJS without socket authentication. However, when I integrate passport.socketio, I encounter an issue where the sockets will only connect after restarting the server. On the ser ...

Encountering a "code redeemed error" when utilizing Google OAuth

Currently, I am working on a project that involves user login through a Google account on localhost. The Google signup functionality has been successfully implemented. However, upon logging in from my account, I encountered the following error message: To ...

What would cause the nsfw property to be absent from a TextChannel in client.on("messageCreate") event?

Currently working with Typescript in combination with Discord.js v14, I'm encountering the following error: Property 'nsfw' does not exist on type 'DMChannel | PartialDMChannel | ... Below is the snippet of problematic code: client.on( ...

When using jQuery and AJAX, the functions each, if, post, and .html work properly but occasionally erase data inexplicably

I have a PHP page containing FedEx and UPS tracking numbers stored in a MySQL database, which are displayed within DIVs with the class "trackingnumber". Using JavaScript, I loop through these divs to retrieve the ID and then send it to a PHP page that fetc ...

The option menu for selecting one item appears empty instead of displaying the default first string value

My editable selectOneMenu is working correctly in terms of resetting/repopulating when the previous selectOneMenu changes. However, it always displays blank instead of showing the first value - 'Please select/Enter statement' <p:selectOneMenu ...

Guide to building a MongoDB database object in conjunction with Next.js

I recently set up MongoDB in my Next.js application using a tutorial I found here: https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb. Within a file called mongodb-config.js, the configuration looks like this: import { MongoClient } ...

Encountering problems with TypeScript in a Node application when using the package manager

I am facing an issue while trying to package my node app into an exe using "pkg". I work with TypeScript, and when I attempt to run pkg index.ts --debug, an error pops up. Node.js v18.5.0 Warning Failed to make bytecode node18-x64 for file /snapshot/ ...