Skip to content Skip to sidebar Skip to footer

How To Use Ajax To Assign Javascript Variable To Php Variable

I have the following function and I am wanting to assign the variable 'Quantity' to php variable using Ajax but, I am not don't know much about ajax so can someone please give me t

Solution 1:

There are ways. You can use PHP session variables to do this. You can use the snippet below to save a take a POST variable and save it as a PHP session variable.

<?php

header('Content-Type: application/json; charset=UTF-8');

session_start();

if ($_POST['foo'] == true) {
  $_SESSION['foo'] = $_POST['foo'];
  echo json_encode(true);
}
else {
  echo json_encode(false);
}

?>

Now you need your JavaScript to connect to the PHP script and, it looks like you're using jQuery already, so we'll do it like this:

$.post('/_/ajax/init_session.php', { foo: 'bar' }, function(data) {
  console.log(data);
}, json);

The JS snippet above asks the PHP script to save $_SESSION['foo'] as 'bar'. When the data has been received, your browser's JavaScript console displays either true or false, depending on if the value has been saved or not.

Post a Comment for "How To Use Ajax To Assign Javascript Variable To Php Variable"