Connecting Html, Javascript And Php With Sessions
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 go
Solution 1:
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.phpecho 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 thisconsole.log(cart.formexample1);
},
error:function() {
console.log("um, error with the script, or it can't be found");
}
Post a Comment for "Connecting Html, Javascript And Php With Sessions"