dongyihao1099 2016-02-27 01:11
浏览 32

使用Sessions连接HTML,Javascript和PHP

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.

  • 写回答

1条回答 默认 最新

  • dongzhiqi0332 2016-02-27 02:00
    关注

    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");
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型