简体   繁体   中英

Sent data using Jquery Ajax to another page not working

I sent some data using ajax from test.php to another page order.php, but when i navigate to order.php and try to echo the data, I get the " Undefined index..." error message.

I have done console.log in the text.php file and confirmed that the data values were successfully set. But it doesn't reflect on the order.php file. I also started session in both files.

NOTE: Before i can send ajax data to DB, I will need to get the data via $_POST['data'] in order.php and save in a variable so that i can proceed to insert the values in the DB. In this case, I CAN'T even get the data. For some reason, the data posted to order.php did not get to the file. That's the issue I want to resolve. How can I get my ajax post data to order.php so that i can use it for something else?

Please what could be wrong with my code? See Code Below:

test.php

<script type="text/javascript">
            $(document).ready(function(){
                $(".addItemBtn").click(function(event){
                    var $form = $(this).closest(".formclass");
                    var qty = $form.find(".naira-input").val(); //form input`
                    var total = $('.amount').html(); //from javascript innerhtml

                    
                $.ajax({
                     url:'order.php',
                     method:'post',
                     data:{grandTotal:total, nairaRate:qty}, // dont worry about this. The values are succesfully set in console.log
                     success:function(response)
                     {
                          console.log(response+' values were sent successfully');// I tested and confirmed that data was sent successfully
                    }
                     
                });
            });
        });


        </script>

order.php

    <?php
    session_start();
    
 $_SESSION['grandTotal']= $_POST['grandTotal'];
      $_SESSION['nairaRate']=$_POST['nairaRate'];

    echo $_SESSION['grandTotal']; // I get Undefined index error here
    echo  $_SESSION['nairaRate']; // I get Undefined index error here
    
    ?>

When you navigate to order.php the code which assigns values to the session runs again , only thing time you haven't made a post request so the values aren't set.

Don't use the same endpoint for displaying the data as you do for setting it.

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