1

I have a simple webstore and I'm trying to add multiple shipping options. There are two options and I want to store the option selected by the customer in a session (or alternatively a cookie).

The php script seems to work on its own but results in page reloading so I have been trying to implement ajax using jquery to send the data but either the code doesn't run or the page reloads.

I have tried to follow several answers, including substituting button for type="submit" but that results in the code not seeming to execute at all. Adding 'click' to .on triggers the code but also results in a reload. I've checked the console and can't see any issues. Thanks for any help.

jQuery

$(function(){
   $('#shipping_form').on('submit', function(e){
      e.preventDefault();

      var ship = $('input[name="shipping_val"]').val();
      $.ajax({
         type: 'GET',
         data: { discount: ship },
         success: function(data) {
            //go to next section
         }
      });
      return false;
   });
});

HTML/PHP

<?php
Session_start();
if(isset($_GET['shipping_submit'])){
  $shipping_get = $_GET['shipping_val'];
}else{
  $shipping_get = '3.99';
}
$_SESSION['shipping'] = $shipping_get ;

?>
<html>
<main class="container">


<form method="GET" name="shipping_form" id="shipping_form" action="">
  <p>Please choose your prefered shipping method.</p>
    <input type="radio" name="shipping_val" value="3.99" checked>
    <label for="shipping_val">
      Standard delivery
    </label>
    <input type="radio" name="shipping_val" value="6.99" >
    <label for="shipping_val">
      Express delivery
    </label>

    <button type="submit" id="shipping_submit" name="shipping_submit" >Update</button>
    <?php
    echo '<h1>' . $_SESSION['shipping'] . '</h1>';
    ?>
</form>```

cssyphus
  • 37,875
  • 18
  • 96
  • 111

1 Answers1

0

Your problem is likely that you are using AJAX to submit data to the same file you are calling it from. Your ajax end point (PHP-side) needs to be a different PHP file.

See this other question:

values not updated after an ajax response

cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • Thanks, if I put the ajax end point (PHP) in a seperate file is it possible to get ```$_SESSION``` back via ajax on success? I realise ajax can provide json. – user8878793 Apr 17 '20 at 15:25
  • Yes, you can *set* $_SESSION variables in that other PHP file, but you don't need to *return* a $_SESSION variable, you can return the data directly using `echo`. See [this other answer](https://stackoverflow.com/questions/17973386/ajax-request-callback-using-jquery/17974843#17974843) – cssyphus Apr 17 '20 at 15:47
  • You might also find [this one](https://stackoverflow.com/questions/37748657/how-to-validate-textarea-and-radio-button-in-a-loop/37749756#37749756) helpful. – cssyphus Apr 17 '20 at 15:52