简体   繁体   中英

How to return a json object from a function in jquery with no ajax call?

So I am trying to make a web application, in which I need to show the details of the cart on the confirmation dialog() but I am not able to store the variable since it is asynchronous function calls. So I tried using function callbacks, but no break thru. Please help how to get the data into cart_items from the function getValueUsingClass() .

Created a deferred object but I don't how to use it. Help required so badly. I am so frustrated about this. So please help, thanks in advance

//this is client.js


    $(document).ready(function () {
        var dfd = $.Deferred();
        var cart_items = [
      //this is the variable that needs to be stored with the cart items which will be coming from getValueUsingClass() function.
        ];


        //collecting the items into a json object to send to the server 
        $(".checkboxlist").click(function () {
            cart_items = (getValueUsingClass());
            console.log(cart_items);
        })


    //function to store the values in cart_items but not able to store
        function getValueUsingClass(setValue) {
            /* declare a checkbox array */
            var chkArray = [];
            /* look for all checkboxes that have a class 'check' attached to it and check if it was checked */
            $(".checkboxlist:checked").each(function () {
                var element = this;
                var cart_item = {
                    id: this.id,
                    item: this.name,
                    cost: Number(this.value),
                    quantity: 1
                }
                chkArray.push(cart_item);
                setValue(cart_items);//tried to use this as a callback function
            })

            /* we join the array separated by the comma */
            function setValue(cart_items) {
                cart_items = chkArray;
                console.log("hell" + cart_items[0].id);
            }

            /* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */

plate is the cart for this, I am using local variable chkArray to store the print the data on the cart

            $(".plate").on('click', function () {
                $('.plate_items').html(" ");
                console.log(cart_items[0].id);
                for (itemIterator = 0; itemIterator < chkArray.length; itemIterator++) {
                    $('.plate_items').append('<li class="list-group-item">' + chkArray[itemIterator].cost + '</li>');
                }
            });

            return chkArray;
        }

        $('.proceed_btn').on('click', function () {
            console.log("hello");
            console.log(cart_items);
            let details = [{
                name: $('#name').val(),
                email: $('#email').val(),
                empid: $('#empid').val()
            }]
            console.log(details[0].name + details[0].email + details[0].empid);
            cart_items = cart_items.concat(details);


        })
    })
//this is index.html
    <html>
    <head>
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <header>
        <div class="container-fluid header">
            <span class="main_title" style="float:left">Eatachi</span>
            <nav class="nav navigation">
            </nav>
        </div>
    </header>

    <body>
        <div class="container">

            <!-- Trigger the modal with a button -->
            <button type="button" class="btn btn-info btn-lg plate" data-toggle="modal" data-target="#myModal">Plate</button>

            <!-- Modal -->
            <div class="modal fade" id="myModal" role="dialog">
                <div class="modal-dialog">

                    <!-- Modal content-->
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                            <form>
                                <div class="form-group">
                                    <label for="name">Name:</label>
                                    <input type="text" class="form-control" id="name">
                                </div>
                                <div class="form-group">
                                    <label for="email">Email ID:</label>
                                    <input type="email" class="form-control" id="email">
                                </div>
                                <div class="form-group">
                                    <label for="empid">Employee ID:</label>
                                    <input type="text" class="form-control" id="empid">
                                </div>
                                <h4 class="modal-title">Cart Details</h4>
                        </div>
                        <div class="modal-body plate_items">
                            <p>Some text in the modal.</p>
                            <ul class="list-group">

                            </ul>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-success proceed_btn">Proceed to payment</button>
                        </div>
                        </form>
                    </div>
                </div>
            </div>

        </div>

        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-1">
                </div>
                <div class="col-lg-10">
                    <div class="col-lg-4">
                        <header>
                            <h3>Veg Alacarte</h3>
                        </header>
                        <article class="well well-lg">


                            <div class="panel-heading" role="tab" id="collapseListGroupHeading1">
                                <h4 class="panel-title">
                                    <a class="collapsed" data-toggle="collapse" href="#collapseListGroup1" aria-expanded="false" aria-controls="collapseListGroup1">
                                        <img class="img-thumbnail news-pic center-block" src="imgs/1.jpg" />
                                    </a>
                                </h4>
                            </div>
                            <div id="collapseListGroup1" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseListGroupHeading1">
                                <ul class="list-group">
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="14" type="checkbox" value="50"> Veg Fried Rice Rs.50</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="15" type="checkbox" value="60"> Veg Biryani Rs.60</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="16" type="checkbox" value="70"> Paneer Fried Rice Rs.70</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="17" type="checkbox" value="50"> Veg Noodles Rs.50</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="18" type="checkbox" value="35"> Curd Rice Rs.35</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="19" type="checkbox" value="35"> Sambar Rice Rs.35</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="20" type="checkbox" value="35"> Veg Pulao Rs.35</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="21" type="checkbox" value="35"> Lemon Rice Rs.35</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="22" type="checkbox" value="15"> Veg Curry Rs.15</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="23" type="checkbox" value="10"> Curd Rs.10</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="24" type="checkbox" value="10"> Dal Rs.10</li>

                                </ul>

                            </div>
                            <ul class="list-group">

                            </ul>
                        </article>

                    </div>

                    <div class=" col-lg-4">
                        <header>
                            <h3>Diet</h3>
                        </header>
                        <article class="well well-lg">


                            <div class="panel-heading" role="tab" id="collapseListGroupHeading1">
                                <h4 class="panel-title">
                                    <a class="collapsed" data-toggle="collapse" href="#dietList" aria-expanded="false" aria-controls="collapseListGroup1">
                                        <img class="img-thumbnail news-pic center-block" src="imgs/2.jpg" />
                                    </a>
                                </h4>
                            </div>
                            <div id="dietList" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseListGroupHeading1">
                                <ul class="list-group">
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="25" type="checkbox" value="50"> North Diet Rs.50</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="26" type="checkbox" value="50"> South Diet Rs.50</li>
                                    <li class="list-group-item">
                                        <input type="checkbox" class="checkboxlist" id="27" type="checkbox" value="70"> South Diet Royal Rs.70</li>
                                </ul>
                            </div>
                            <ul class="list-group">

                            </ul>
                        </article>


                    </div>

                    <div class=" col-lg-4">
                        <header>
                            <h3>Non Veg Alacarte</h3>
                        </header>
                        <article class="well well-lg">


                            <div class="panel-heading" role="tab" id="collapseListGroupHeading1">
                                <h4 class="panel-title">
                                    <a class="collapsed" data-toggle="collapse" href="#nonVegList" aria-expanded="false" aria-controls="collapseListGroup1">
                                        <img class="img-thumbnail news-pic center-block" src="imgs/3.jpg" />
                                    </a>
                                </h4>
                            </div>
                            <div id="nonVegList" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseListGroupHeading1">
                                <ul class="list-group">
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="1" type="checkbox" value="130"> Chicken Biryani Rs.130</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="2" type="checkbox" value="130"> Fish Biryani- Rs.130</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="3" type="checkbox" value="130"> Prawn65 Biryani Rs.130</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="4" type="checkbox" value="100"> Chicken Dum Biryani Rs.100</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="5" type="checkbox" value="110"> Chicken Roast Biryani Rs.110</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="6" type="checkbox" value="120"> Chicken Boneless Biryani Rs.120</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="7" type="checkbox" value="70"> Egg Biryani Rs.70</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="8" type="checkbox" value="60"> Egg Curry with Roti Rs.60</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="9" type="checkbox" value="80"> Egg Curry with Paratha Rs.80</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="10" type="checkbox" value="70"> Chicken Fried Rice Rs.70</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="11" type="checkbox" value="70"> Chicken Noodles Rs.70</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="12" type="checkbox" value="60"> Egg Fried Rice Rs.60</li>
                                    <li class="list-group-item">
                                        <input class="checkboxlist" id="13" type="checkbox" value="60"> Egg Noodles Rs.60</li>



                                </ul>

                            </div>
                            <ul class="list-group">

                            </ul>
                        </article>


                    </div>
                </div>
                <div class="col-lg-1">

                </div>
            </div>
        </div>


        <div class="footer">

            <div class="copyright">
                <span id="copyright-year">©2018</span>

            </div>

        </div>


    </body>



    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="scripts/client.js"></script>


    </html>

<!-- end snippet -->

Async call in javascript doesn't return you an answer immediately but it returns you a promise that eventually it will give you the answer you'd expect. Usually, promises have a then method which is a callback function which the promise exposes to access the data when it is ready. So, the point is that you can make use of your data in this then method. For more detailed reference go here .

Actually, the problem is not with any function callbacks or asynchronous, the values I am setting to cart_items should be passed using push() method instead of assigning it directly.

 $(document).ready(function () {
        var dfd = $.Deferred();
        var cart_items = [
      //this is the variable that needs to be stored with the cart items which will be coming from getValueUsingClass() function.
        ];


        //collecting the items into a json object to send to the server 
        $(".checkboxlist").click(function () {
            cart_items = (getValueUsingClass());
            console.log(cart_items);
        })


    //function to store the values in cart_items but not able to store
        function getValueUsingClass(setValue) {
            /* declare a checkbox array */
            var chkArray = [];
            /* look for all checkboxes that have a class 'check' attached to it and check if it was checked */
            $(".checkboxlist:checked").each(function () {
                var element = this;
                var cart_item = {
                    id: this.id,
                    item: this.name,
                    cost: Number(this.value),
                    quantity: 1
                }
                chkArray.push(cart_item);
                setValue(cart_items);//tried to use this as a callback function
            })

            /* we join the array separated by the comma */
            function setValue(cart_items) {
                //cart_items = chkArray; this is the mistake
                 cart_items.push(chkArray);//this is the correct way because I am passing the reference but the following array will not accept the reference as a value.
                console.log("hell" + cart_items[0].id);
            }

            /* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */

plate is the cart for this, I am using local variable chkArray to store the print the data on the cart

            $(".plate").on('click', function () {
                $('.plate_items').html(" ");
                console.log(cart_items[0].id);
                for (itemIterator = 0; itemIterator < chkArray.length; itemIterator++) {
                    $('.plate_items').append('<li class="list-group-item">' + chkArray[itemIterator].cost + '</li>');
                }
            });

            return chkArray;
        }

        $('.proceed_btn').on('click', function () {
            console.log("hello");
            console.log(cart_items);
            let details = [{
                name: $('#name').val(),
                email: $('#email').val(),
                empid: $('#empid').val()
            }]
            console.log(details[0].name + details[0].email + details[0].empid);
            cart_items = cart_items.concat(details);


        })
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM