0

I'm trying to create a shopping cart for an assignment using PHP, HTML and Javascript, but I'm struggling to get even the basics of PHP working.

Since it's an assignment I'm not going to post my exact code, but I'll post some modified code describing the general concepts I'm struggling with. Also note that I've heavily simplified the program in this post, but I think I've included everything relevant.

To start off, I have a form in the HTML, with selection-options tags:

<?php session_start(); ?> <!-- This is on the first line of the page -->
...
<form id="formexample" method="post" action="cart.php">
<select name="formexample2">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>
<select  name="formexample2">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>
<button type="button" onclick="addToCart()">Add to Cart</button>
</form>
<div class="test"></div>

"addToCart()" is a Javascript function, which I've written into a seperate file and imported in the "header" tags. I know the function works because it responds when I put in "alert("test");". One of the lines in is as follows:

$(".test").append("<?php include \"cart.php\"; ?>");

When I replace the append with "test" in "p" tags it appears without problems.

"cart.php" is a php file in the same directory. It stores the data for the session:

<?php   
$PHPtest= 1;


$_SESSION['cart'][$_POST['formexample1']] = $_POST['formexample1'];
    $_SESSION['cart'][$_POST['formexample1']][$_POST['formexample2']] = [$_POST['formexample2']] 

/* Note that in my actual code the form has 11 different select tags, some with up to ten options. I'm storing the information as a big multidimensional array in $_SESSION for ease. */

    ?>

I'm trying to create a loop in the same Javascript function I mentioned before, in which I access the session data. The loop starts off with "if(?php echo isset($_SESSION[\'cart\'][$_POST[\'formexample1\']]; ?>")" - I removed the < before the question mark here so you can actually see the code when I make this post. This is where my program fails. It seems my problem is passing the PHP variable to Javascript. To test this I wrote the following at the beginning of cart.php:

$PHPtest = 1;

I then wrote this into the Javascript function:

var test = "<?php echo $PHPtest; ?>";
alert(test);

According to Google, this is the format you should use when passing a PHP variable to Javascript. When I do it, the alert simply shows exactly what's between the quotation marks (i.e. < ?php echo $cartCheck; ?>).

I've been looking online and as far as I can tell I'm doing exactly what people are saying about sessions, assigning PHP variables to Javascript and arrays; so why isn't it working?

Thanks in advance.

EDIT:

I've commented out the $_SESSION lines in cart.php for the moment. I'm practising with $PHPtest.

cart.php now looks like this:

<?php   

session_start(); 
$PHPtest = 1;
echo json_encode($PHPtest);
?>

The Javascript function now looks like this (with added AJAX):

function addToCart()
{
var test;
    $.ajax(
    {
        url:"cart.php",
        type:"post",
        data:"$PHPtest",
        success:function(response) 
        {
            test = $.parseJSON(response);
            console.log(response); //sends the response to your console
        },
        error:function() 
        {
            console.log("Error");
        }
    });
    alert(test);
}

I've also moved written "include "cart.php"" at the top of the main page. See the discussion under Josh S's reply to see how I got here.

The alert shows "undefined".

EDIT 2 I've updated my function based on this answer here: Get variable from PHP file using JQuery/AJAX

This is what I have now:

function addToCart()
{
    var test;
    $.ajax(
    {
        url:"cart.php",
        type:"post",
        data: data,
        success:function(PHPtest) 
        {
            test = $.parseJSON(PHPtest);
            console.log(test); //sends the response to your console
        },
        error:function() 
        {
            console.log("Error");
        }
    });
    alert(test);
}

I've tried various combinations of "PHPtest" and "test" but can't get it to work. Now I get no alert at all.

Community
  • 1
  • 1
  • what happens when you do `alert("")`? – ewizard Feb 27 '16 at 01:20
  • The alert shows what exactly what's in between the quotation marks i.e. it shows the angular brackets, the question mark and the rest. – user5988698 Feb 27 '16 at 01:35
  • are you using it in a ` – ewizard Feb 27 '16 at 01:36
  • 1
    The Javascript is included with "". The cart.php is then included in a Javascript function with "$(".test").append("");". – user5988698 Feb 27 '16 at 01:40
  • maybe you should use the `load()` function like here http://stackoverflow.com/questions/16933989/how-do-i-load-a-php-include-into-a-page-with-ajax-whilst-the-page-is-loading - so...`$(".test").load("path/to/cart.php");`. maybe it wasnt working because the php wasnt being loaded correctly. – ewizard Feb 27 '16 at 01:42
  • I've just done it, but the alert hasn't changed. – user5988698 Feb 27 '16 at 01:50

1 Answers1

0

Use an Ajax call to a PHP file to work with a live page and PHP.

PHP is processed before it hits the browser. You can't use it on the fly.

You can't mix front-end and back-end scripting without a bit of trickery, (e.g., AJAX calls).

EDIT

If using jQuery, and you're your script is looking for a post.

$.ajax({
    url:"script/location/run.php",
    type:"post",
    data:"name=value&your=post&data=goeshere",
    success:function(response) {
        console.log(response); //sends the response to your console
    },
    error:function() {
        console.log("um, error with the script, or it can't be found");
    }
});

EDIT 2

Cart should be set up similar to this;

<?php
session_start(); //On any PHP document (that are not includes or require) this is required at the top of the page to use sessions

$PHPtest= 1;


$_SESSION['cart']['formexample1'] = $_POST['formexample1'];
    $_SESSION['cart']['formexample2'] = $_POST['formexample2'] ;

/* Note that in my actual code the form has 11 different select tags, some with up to ten options. I'm storing the information as a big multidimensional array in $_SESSION for ease. */

?>

However, if you set your session variables, you still can't access them directly using PHP commands on the client side (the browser, where the AJAX was called)

so you need to echo your cart out here so you can access them on the client side.

//at the end of cart.php
echo json_encode($_SESSION['cart']); //will convert your session cart to JSON and send to the response variable in your AJAX.

your JS

var cart = '';
$.ajax({
    url:"script/location/run.php",
    type:"post",
    data:"name=value&your=post&data=goeshere",
    success:function(response) {
        //response will hold the JSON value of your cart
        cart = $.parseJSON(response); //decodes to a JSON object in JavaScript;

        //you can access the cart variables like this
        console.log(cart.formexample1);

    },
    error:function() {
        console.log("um, error with the script, or it can't be found");
    }
Josh S.
  • 612
  • 3
  • 8
  • Thanks. I'm reading about AJAX now. I'll come back if I have any more questions. – user5988698 Feb 27 '16 at 02:21
  • I've moved the include of cart.php to the beginning of the file and am adding "if(isset($_POST)){...}" to the beginning of cart.php to avoid errors. I think I then need to use an AJAX function to retrieve the value of the session variable, but I'm not sure which one to use - from what I'm reading I think I need to use "$.get()"? I'm reading about it (https://api.jquery.com/jquery.get/) and am confused about the parametres. The "url" is obviously the name of the .php file (it's in the same directory), but I have no idea what to put into the other parametres. The examples aren't clear to me. – user5988698 Feb 27 '16 at 02:46
  • Also, make sure your script that your ajax is calling has the session_start() on that page as well, or it won't be able to interact with your session. – Josh S. Feb 27 '16 at 03:08
  • So I'd put "cart.php" after url, and "$_SESSION['cart'][$_POST['formexample1']][$_POST['formexample2']]" after "data"? Is that correct? And would I store it in another variable like "$variable = $.ajax({...});"? Thanks. – user5988698 Feb 27 '16 at 03:19
  • Whoa whoa whoa.. back up to square one haha. It appears you do not understand the concepts. $_SESSION['cart'][$_POST['formexample1']] = $_POST['formexample1']; should be $_SESSION['cart']['formexample1'] = $_POST['formexample1']; You assign $_SESSION like a multi-dimension array. – Josh S. Feb 27 '16 at 03:22
  • i'm going to update my answer to try and help ya in the right direction. – Josh S. Feb 27 '16 at 03:23
  • Thanks! Sorry for the hassle! – user5988698 Feb 27 '16 at 03:27
  • Take a look, see if you can understand it a little better now – Josh S. Feb 27 '16 at 03:31
  • I've added "session_start();" to the top of cart.php and also added "echo json_encode($PHPtest);". In the Javascript function, I've declared "var test;" separately, and then written out the $.ajax, replacing ""script/location/run.php" with "cart.php", ""name=value&your=post&data=goeshere"" with "$PHPtest", and "cart" with "test". I'll edit the code into my post above. – user5988698 Feb 27 '16 at 03:44
  • I've updated my original question with what I have now. I'm getting "undefined" from "alert(test)". – user5988698 Feb 27 '16 at 03:51
  • I've updated my original question again. I'm still not sure what to put where in the $.ajax(). I've tried following the pattern from online examples, but I can't get it to work. – user5988698 Feb 27 '16 at 04:44