0

I've a page '/order/new' that include 2 dropdown menues for customer & its address & a button that redirect to choose product to add to the order and I get the products in an array and pass the array to the '/order/new'..but when i redirect I don't get the selected customer & its address..I save the products which will be added in order in global array called hh which its get the data from ajax

I want to get the customer & its 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);

my 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);
                }
              })
               })

My ejs 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>
Eman Emad
  • 77
  • 1
  • 4
  • 13

1 Answers1

0

in these lines,

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

are you successfully getting all products from your DB back?

because in your AJAX call,

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

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

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

I'm trying to get the flow of your program.

So the user goes to your webpage, they select a product, your webpage pings your REST server with the product information, your REST server pings your database looking for that product, then that data is rendered to this template here?

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

EDIT: You have to handle the user interaction with event listeners and the user input with some 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 recommend the cookie method. You set the cookie once, use it when you need it, then delete it when you're done.

With the first method, you have to send the data in your fetch (which doesn't need that data to get the products), then you have to manage that user_data throughout your back-end making sure it doesn't get lost. It's too much work. Use the cookie method instead.

dar
  • 97
  • 5
  • I use ajax to get the selected products to be added to the order & i got it in hh array.. i updated my question see it & answer please – Eman Emad Aug 03 '19 at 12:24
  • Ok, so you have a function 'getProduct: (req , res ) => {}' that pushes 'var products = req.query.selectedProduct;' that product to the global array hh. Are you sure your other files can read that global array? – dar Aug 03 '19 at 12:49
  • yes..I can get this array in my postOrder function..But if you've better idea,tell me – Eman Emad Aug 03 '19 at 12:55
  • Your REST API server is retrieving info from the DB. You then redirect the user to a different route '/order/new', but you're not sending the information to the new route handler. I assume it looks something like 'app.get('/order/new')'. Try [link](https://stackoverflow.com/questions/19035373/how-do-i-redirect-in-expressjs-while-passing-some-context). You can either pass the information through the URL as a query string (not recommended), or use the 'req' object to pass data. You know how you get POST data in 'req.body'? You can add data to the 'req' object. Ex. req.product = hh; – dar Aug 03 '19 at 14:38
  • I updated my question hope it make it more obviuos..I want to choose the user and address from dropdown menu and go to '/addProduct' to select product to order & when i click save it redirect me to '/new/order' with an array of product 'hh' & show the selected user & address in dropdown men again – Eman Emad Aug 04 '19 at 12:16
  • Ok, so when the use clicks add product, they are being redirected to /orderProduct... then they get redirected to a product page where they can choose a product. Is that process working? are you capturing the product they choose and, I assume, going back to the main page so they can view "User", "Address", "Product", "Status" again? You have two main route changes going on, the 'add product' anchor tag AND the 'save' button. Both are going to require different approaches. – dar Aug 05 '19 at 11:41
  • yes, that's how it works but I want when i choose product and get back to the page that show user address & status the selected user & address which i select befor click on 'add product' show on my drop down menu – Eman Emad Aug 05 '19 at 12:10
  • Ok, got it. Look at my edited code above. Your going to need to handle this with eventListeners and some sort of storage method. – dar Aug 05 '19 at 12:29