Results 1 to 4 of 4

Thread: How to add my ordering items in a table before saving them in DB

  1. #1

    Thread Starter
    Lively Member
    Join Date
    May 2016
    Posts
    124

    How to add my ordering items in a table before saving them in DB

    Hi. I'm new to PHP development. I'm working for my practice on a dummy website. Its kind of sale project.
    Its an ordering Form. Where I have list of items to select from. Once the item is selected, their quantity is entered and their unit price is retrieved and put into textbox. After that there is an Add Item button. I want that when I press the add item button so the selected item is added to the table below. When I finish entering all my items into the table so that table shows me Total amount, and a Button below that for saving the record.
    When I press the save button so all the entries of the table get stored against the Order number.

    When I was working with vb.net so there I had a DataTable, DataSet and Datagrid to work upon. But I don't know that do I have anything similar in PHP.

    Question:
    Do I have any option like dataTable or Dataset in PHP. Where I could add items like this?

    If my delivered idea is not clear so I can explain more?

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    10,183

    Re: How to add my ordering items in a table before saving them in DB

    I wouldn't use PHP for you front-end operations. What I would be doing is the following:
    1. Use JavaScript to make an AJAX get request to a PHP endpoint that returns every item you want to display in a JSON array
    2. Once you have the data, use JavaScript to iterate over the collection to create the DOM representation
    3. When the user clicks on the add item button, use JavaScript to push that item, along with the quantity, to an array that is persisted in localstorage
    4. When the user is finished adding items and they want to save their list, use JavaScript to make an AJAX post request to a PHP endpoint that takes the item array


    Are you comfortable separating the front-end from the back-end like that?

  3. #3

    Thread Starter
    Lively Member
    Join Date
    May 2016
    Posts
    124

    Re: How to add my ordering items in a table before saving them in DB

    Hmmmm. For my front-end I had no idea what to do. So after searching and asking and now you hit the target. I started learning jQuery instead of JS. Because everyone said in tutorials that JS was much complex than jQuery. So I followed and following a tutorial where fundamental jQ is taught. I thought that it would help. But at the end of tutorial it did not do what I was looking for.

    Then I found an AJAX tutorial where the guy is working on something I need.

    @dday, Sir I did not understand few things in your post but some of them and I got a little idea.

    What I know right now sir is that I have some of understanding of jQ and some of its events. and now I've started AJAX from a couple of tutorial, they are not teaching that what is actually happening in their videos.

    Guide me that am I going right way?

  4. #4
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    10,183

    Re: How to add my ordering items in a table before saving them in DB

    To clarify, jQuery is a JavaScript library. When you're executing jQuery code, it is ultimately running JavaScript, just using a more flavorful syntax. I personally enjoy working with both, but I would suggest learning JavaScript before learning jQuery.

    In terms of step 1 (Use JavaScript to make an AJAX get request to a PHP endpoint that returns every item you want to display in a JSON array), imagine you have the following PHP code:
    PHP Code:
    <?php
        http_response_code
    (200);

        
    $products = array(
            array(
    "ProductId" => 1"ProductName" => "Widget1""Cost" => "5.00"),
            array(
    "ProductId" => 2"ProductName" => "Widget2""Cost" => "3.50"),
            array(
    "ProductId" => 3"ProductName" => "Widget3""Cost" => "3.00"),
            
    // etc...
        
    );

        echo 
    json_encode($products);
    ?>
    Then you could submit an AJAX GET request by using the following JavaScript code:
    Code:
    window.onload = function() {
        const request = new XMLHttpRequest();
        request.onreadystatechange = function() { 
            if (request.readyState == 4 && request.status == 200) {
                 const products = request.responseJSON;
                 // TODO: setup step 2
            }
        }
    }
    
    request.open('GET', 'my-php-file.php', true );            
    request.send(null);
    At this point, upon a successful request, your products will be stored in the variable products. You will see that I have a comment just afterwards reserved for step 2.

    Now that you have the products, you should iterate over the array and create your DOM.

    The DOM can be something simple like this:
    HTML Code:
    <ol>
      <li><a href="#" data-productId="[id]">[name] - $[cost]</a></li>
      <!-- etc... -->
    </ol>
    What you could do is setup a function to create the DOM, then call that function where the comment is. The function could be like the following:
    Code:
    const buildProductsList = function(products) {
        products = products || [];
    
        const orderedList = document.createElement('ol');
        for (const key in products) {
            if (Object.prototype.hasOwnProperty.call(products, key)) {
                const product = products[key];
                const listItem = document.createElement('li');
                listItem.innerHTML = `${product.ProductName} - ${product.Cost}`;
                listItem.dataset.productId = product.ProductId;
                orderedList.appendChild(listItem);
            }
        }
    
        return orderedList;
    }
    Now your total code would look like this:
    Code:
    window.onload = function() {
        const request = new XMLHttpRequest();
        request.onreadystatechange = function() { 
            if (request.readyState == 4 && request.status == 200) {
                 const products = request.responseJSON;
                 const orderedList = buildProductsList(products);
            }
        }
    }
    
    const buildProductsList = function(products) {
        products = products || [];
    
        const orderedList = document.createElement('ol');
        for (const key in products) {
            if (Object.prototype.hasOwnProperty.call(products, key)) {
                const product = products[key];
                const listItem = document.createElement('li');
                const anchor = document.createElement('a');
                a.innerHTML = `${product.ProductName} - ${product.Cost}`;
                a.dataset.productId = product.ProductId;
                listItem.appendChild(anchor)
                orderedList.appendChild(listItem);
            }
        }
    
        return orderedList;
    }
    Now that the DOM is being build dynamically, you will need to bind the event handler (step 3).

    I can help out more later, but for now I need to head home.

    Update
    I'm home now, so I can finish. I've also updated the method to create an anchor.

    Inside of the for/in loop, you need to setup the event handler for the anchor which can be done by using addEventListener method. For now we will setup a simple function that calls console.log to be used as a placeholder for the second part of step 3:
    Code:
    const buildProductsList = function(products) {
        products = products || [];
    
        const orderedList = document.createElement('ol');
        for (const key in products) {
            if (Object.prototype.hasOwnProperty.call(products, key)) {
                const product = products[key];
                const listItem = document.createElement('li');
                const anchor = document.createElement('a');
                anchor.innerHTML = `${product.ProductName} - ${product.Cost}`;
                anchor.dataset.productId = product.ProductId;
                listItem.appendChild(anchor)
                orderedList.appendChild(listItem);
                document.addEventListener('click', (e) => {
                    console.log(e.target.dataset.productId);
                });
            }
        }
    
        return orderedList;
    }
    Now that the ordered list is created, each individual list item is created, each individual anchor is created, and now the anchor's click event has been bound we can prompt the user for the quantity. This can be done by using the prompt method. Once you have the quantity you can push it along with the id to local storage:
    Code:
    document.addEventListener('click', (e) => {
        const productId = e.target.dataset.productId;
        const quantity = prompt('Quantity:');
        const cart = localStorage.getItem('cart') || [];
        cart.push({
            ProductId: productId,
            Quantity: quantity
        });
        localStorage.setItem('cart', cart);
    });
    The final piece to this is when the user goes to "checkout". At that point, you would get the cart from the localstorage, and send it to your endpoint. I can't really help with this without seeing how you plan on handling the incoming data.

    Now all of this uses incredibly simple CSS and JavaScript. You can make it pretty by styling everything, adding a bit more business logic, but hopefully this gives you an idea of how the process would work.
    Last edited by dday9; May 3rd, 2021 at 10:19 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width