简体   繁体   中英

Why don't change $_SESSION variables (PHP) when use AJAX?

I can not understand a simple problem. Is there a website where I need to add a change of currency on the page (RUR / EUR / USD) using AJAX. I think the best option — it's written in $_SESSION selected currency and use it later on my PHP code (for display price, etc).

My index.php file:

<?php 
  session_start(); 
  if (!isset($_SESSION['currency'])) $_SESSION['currency'] = 'rouble';
?>

<!-- Links -->
<a href="#" class="currency__change" data-currency="dollar">Dollar</a>
<a href="#" class="currency__change" data-currency="euro">Euro</a>
<a href="#" class="currency__change" data-currency="rouble">Rouble</a>

<!-- Add jQuery and script -->
<script src="jquery-2.2.4-min.js"></script>
<script src="ajax.js"></script>

Here my ajax.js file:

;(function($, window, document, undefined) {
  // On document ready.
  $(document).ready(function() {
    // Change currency.
    $('.currency__change').on('click', function(event) {
      // Prevent default.
      event.preventDefault();
      // Send AJAX request.
      $.ajax({
        type: 'POST',
        url: 'Ajax.php',
        data: { 'currency': $(this).data('currency') },
        success: function() {
          location.reload();
        },
        error: function() {
          alert('Error! Try again later.');
        }
      });
    });
  });
})(jQuery, window, document);

And now, my Ajax.php file:

<?php
  session_start();
  // Change currency.
  if ($_POST['currency']) {
    unset($_SESSION['currency']);
    $_SESSION['currency'] = $_POST['currency'];
  }
?>

Session start normally, I get session file on my server (with default value) with the right headers:

在此处输入图片说明

But if I click AJAX link — variable in $_SESSION['currency'] don't change.
Why?

Session are saved on the server and not on the user browser. To now who is the owner of the session saved session php set a cookie in the user browser called PHPSESSID with a unique id to identify that specific user. When you call the function session_start() php use PHPSESSID to load the saved session for that user.

To check if session are working add print of the session in the index.php after set the default session.

<?php 
  session_start(); 
  if (!isset($_SESSION['currency'])) $_SESSION['currency'] = 'rouble';
?>

<!-- Currency -->
Selected currency: <b><? echo $_SESSION['currency']; ?></b><br>

<!-- Links -->
<a href="#" class="currency__change" data-currency="dollar">Dollar</a>
<a href="#" class="currency__change" data-currency="euro">Euro</a>
<a href="#" class="currency__change" data-currency="rouble">Rouble</a>

<!-- Add jQuery and script -->
<script src="jquery-2.2.4-min.js"></script>
<script src="ajax.js"></script>

If you need to access to the currency from javascript than you can store it directly in the cookies or crate a javascript function that make a ajax call to php that return the stored currency.

Here you can found how to store and read cookies in javascript: http://www.w3schools.com/js/js_cookies.asp

Here you can found more info on php session: http://php.net/manual/en/intro.session.php

Some advice: You don't need to unset the session you can just overwrite it. You can't use if($_POST['currency']) with all php version but fore sure you can do it from the version 5.6

I would suspect that your variable $(this).data('currency') is not being set, and your if ($_POST['currency']) check is not passing.

Try sending just a string value in for if ($_POST['currency']) to test the theory.

data: { 'currency': 'Dollar' },

you could also put a console.log() in to see if anything is in the variable.

console.log("Anything here?",$(this).data('currency'));

Aditionally

You could implement some php error logging to see what your incoming data looks like.

<?php
  session_start();
  // Change currency.

  error_log(print_r($_POST,true));

  if ($_POST['currency']) {
    unset($_SESSION['currency']);
    $_SESSION['currency'] = $_POST['currency'];
  }
?>

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