HTML
<div pid="14" class="buybutton">Buy</div>
Javascript
<script>
$(document).ready(function() {
$(".buybutton").click(function(){
console.log("Clicked Button");
var pid = $(this).attr("pid");
console.log(pid,"= Product ID");
$.post("/redirecttoproduct.php", {"pidofproduct": pid});
});
});
</script>
Console:
Clicked Button
14 = Product ID
redirecttoproduct.php
<?php
session_start();
$_SESSION['redirectproductpid'] = $_POST['pidofproduct'];
?>
Trying to echo SESSION, nothing shows up
<?php
$productpid = $_SESSION['redirectproductpid'];
echo $productpid;
?>
Nothing shows up - Any ideas?
Did you missed the session_start(); in this page? session_start() is necessary when you use $_SESSION.
<?php
session_start();
$productpid = $_SESSION['redirectproductpid'];
echo $productpid;
?>
I suggest do a callback function first to check if the post request is successfully submitted, one of the reason your $_SESSION variable doesn't return any value is because your js code doesn't post any values to it at all, in result no data is being assigned to your $_SESSION var, ie:
$.post("/redirecttoproduct.php", {"pidofproduct": pid})
.done(function() {alert( "success" );})
.fail(function() {alert( "error" );});
And it would be more convenient if you could supply an absolute path to your $.post request like your website's dir url ie: $.post("//yourwebsite.com/redirecttoproduct.php") with this relative path errors can be significantly avoided, and make sure your not submitting invalid values that would not pass your XSS filters (if there are any), hope this helps, cheers!
Related
I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
I'm posting 3 arrays of data to a php file(checkout.php) on the server via jquery post.
$.post("checkout.php", {items_name : JSON.stringify(items_name), items_price : JSON.stringify(items_price), items_amount : JSON.stringify(items_amount)}, function(data){
console.log(data);
//those three are arrays(items_name, items_price & items_amount
});
window.location.href = "checkout.php";
Then I receive the data arrays in the checkout.php and store them in $_SESSION.
$items_name = json_decode($_POST['items_name']);
$items_price = json_decode($_POST['items_price']);
$items_amount = json_decode($_POST['items_amount']);
session_start();
$_SESSION['items_name'] = $items_name;
$_SESSION['items_price'] = $items_price;
$_SESSION['items_amount'] = $items_amount;
When the page redirects to checkout.php after making the jquery post, when i try to access data from session, it doesn't show anything.
session_start();
print_r($_SESSION);
Where am I doing wrong?
The jQuery post call is executed asynchronously, so your code continues down to the redirect immediately without waiting for the php script to finish on the server. Add your redirect to the success/complete callback for post.
$.post("checkout.php", {items_name : JSON.stringify(items_name), items_price : JSON.stringify(items_price), items_amount : JSON.stringify(items_amount)}, function(data){
// whatever
window.location.href = "checkout.php";
});
checking if only $_POST is set, doesn't work. But making it more specific works.
if(isset($_POST['items_name'])){
//Code here
}
Now this works fine.
I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
Say I have a simple html button on main.php that looks like this:
<button type="button" name="button" id="button">Search</button>
<div id="results">
<?php
session_start();
echo #$_SESSION['numbers'];
?>
</div>
This button calls an ajax query to session.php that looks like this:
session_start();
$_GET['numbers'] = $_SESSION['numbers'];
Is there a way to refresh or relead the div on main.php with JQuery/AJAX so that it will echo the now set $_SESSION['numbers']?
the function jquery.ajax has an argument that works as an callback that is called when your ajax returns. (see link )
edit your session.php in that way that it returns the value from the session.
and write something like:
$.ajax({
url: 'session.php',
data: {numbers:1337},
success: myEventhandler
});
function() myEventhandler( value ) {
$('#result').text( value );
}
the returning callback than outputs the value that comes from session.php.
btw, wouldn't that make more sense?
$_SESSION['numbers'] = $_GET['numbers'];
you're doing an assignment to the get array and are using it not later on.
You have to echo what you want in session.php, such as
echo $_GET['number'];
and than when calling ajax in main.php, you can use the response data to modify current page, such as
$.get('session.php', function(response) {
$('#result').text(response);
});
if not familiar with jQuery's ajax method, the ajax api might be helpful.