连接HTML,Javascript和PHP与会话 [英] Connecting HTML, Javascript and PHP with Sessions

查看:98
本文介绍了连接HTML,Javascript和PHP与会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP,HTML和Javascript创建一个任务的购物车,但我仍然努力获得PHP的基础知识。



由于这是一个任务,我不会发布我的确切代码,但我会发布一些修改后的代码来描述我正在努力的一般概念。另外请注意,我在这篇文章中大量简化了程序,但我认为我已经包含了所有相关的内容。

首先,我在HTML中有一个表单,带选择选项的标签:

 <?php session_start(); ?> <! - 这是在页面的第一行 - > 
...
< form id =formexamplemethod =postaction =cart.php>
< option value =1>选项1< / option>
< option value =2>选项2< / option>
< / select>
< button type =buttononclick =addToCart()>添加到购物车< / button>
< / form>
< div class =test>< / div>

addToCart()是一个Javascript函数,我写入了一个单独的文件并导入在标题标签中。我知道这个函数起作用,因为它在我提出alert(test)时响应;。其中一行代码如下:

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

当我用p标签中的test替换append时, p>

cart.php是同一目录中的一个php文件。它存储了会话的数据:

 <?php 
$ PHPtest = 1;


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

/ *注意在我的实际代码中,表单有11个不同的选择标签,其中一些最多有10个选项。我将这些信息存储为$ _SESSION中的一个大型多维数组,以方便使用。 * /

?>

我试图在前面提到的相同的Javascript函数中创建一个循环,会话数据。循环开始于if(?php echo isset($ _ SESSION [\'cart\'] [$ _ POST [\'formexample1\']];?>) - 我删除了<之前这里是问号,所以你可以在我发布这篇文章时看到代码,这是我的程序失败的地方,看来我的问题是将PHP变量传递给Javascript
为了测试这个,我在开头写了下面的代码cart.php:


  $ PHPtest = 1; 

然后我将它写入到Javascript函数中:

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

根据Google的说法,这是在将PHP变量传递给Javascript时应该使用的格式。当我这样做时,警报只是简单地显示引号之间的内容(即<?php echo $ cartCheck;?>)。



我一直在网上寻找,据我所知,我正在做的是人们对会话的意见,assignin将PHP变量转换为Javascript和数组;所以为什么它不工作?



预先感谢。



编辑:



目前,我已经在cart.php中注释了$ _SESSION行。我正在练习$ PHPtest。



cart.php现在看起来像这样:

 <?php 

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

Javascript函数现在看起来像这样(带有添加的AJAX):

  function addToCart()
{
var test;
$ .ajax(
{
url:cart.php,
类型:post,
data:$ PHPtest,
成功:函数(响应)
{
test = $ .parseJSON(响应);
console.log(response); //将响应发送到控制台
},
error:function()
{
console.log(Error);
}
});
alert(test);
}

我也将includecart.php写在主页面的顶部。



该警报显示未定义。



编辑2
我已根据此答案更新了我的函数:



这是我现在拥有的:

  function addToCart()
{
var test;
$ .ajax(
{
url:cart.php,
类型:post,
data:数据,
成功:函数(PHPtest)
{
test = $ .parseJSON(PHPtest);
console.log(test); //将响应发送到控制台
},
错误:function()
{
console.log(Error);
}
});
alert(test);
}

我已经尝试过PHPtest和test的各种组合,但可以不能让它工作。现在我完全没有任何提醒。 解决方案

使用对PHP文件的Ajax调用来处理实时页面和PHP。

PHP在它碰到浏览器之前就被处理了。您无法即时使用它。



不能混淆前端和后端脚本(例如,AJAX调用) 。

编辑

如果使用jQuery,并且您的脚本是寻找一个职位。

  $。ajax({
url:script / location / run.php,
type:post,
data:name = value& your = post& data = gohere,
success:function(response){
console.log(response ); //将响应发送到控制台
},
error:function(){
console.log(这个,脚本出错,或者找不到 );
}
});

编辑2



购物车应设置类似于此;

 <?php 
session_start(); //在任何PHP文档中(不包括或不需要),在页面顶部需要使用会话

$ PHPtest = 1;


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

/ *请注意,在我的实际代码中,表单有11个不同的选择标签,其中一些最多有10个选项。我将这些信息存储为$ _SESSION中的一个大型多维数组,以方便使用。 * /

?>

但是,如果您设置了会话变量,则仍然无法直接使用PHP命令访问它们客户端(浏览器,AJAX调用的地方)



所以你需要在这里回显你的购物车,这样你才能在客户端访问它们。

  //在cart.php结尾处
echo json_encode($ _ SESSION ['cart']); //将会话购物车转换为JSON并发送到AJAX中的响应变量。

您的JS

  var cart =''; 
$ .ajax({
url:script / location / run.php,
type:post,
data:name = value& your = post& data = gohere,
成功:函数(响应){
//响应将保存您购物车的JSON值
cart = $ .parseJSON(response); //解码为JSON对象在JavaScript中;

//你可以像这样访问购物车变量
console.log(cart.formexample1);

},
error :function(){
console.log(um,脚本出错,或找不到);
}


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.

解决方案

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

这篇关于连接HTML,Javascript和PHP与会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆