I have a a problem when trying to send data from one page to another via using SESSION. In page 1 I have a form like:
<form id="myForm" name="myForm" action="" method="post">
<input name="item_1">......</input> // an input for a number
<input name="comment1">......</input> // an input for text
</form>
to avoid refreshing, I use
function submitOnclick()
{
$.post("thisPage.php", $("#myForm").serialize());
redirectToAnotherPage();
}
then I tried to store data via using SESSION
function redirectToAnotherPage(){
<?php $_SESSION['item_1']=$_POST['item_1'] ?>;
<?php $_SESSION['comment1']=$_POST['comment1'] ?>;
location.href='anotherPage.php';
}
but the $POST result is empty, I tried to replace $_POST['item_1'] with a number 1 and it did store the number to item_1, so I assume it is because $_POST['item_1'] has some problems, I don't know why I can't get the form data in one page without submitting / refreshing,
Any help will be appreciated, thanks!
I don't think you can set a PHP session variable like that inside your javascript function. PHP is separate to javascript since PHP is serverside, those values will be read and assigned when the page first pre-processes.
There will be no change, whether the javascript function gets called or not.
Even without AJAX< just a simple PHP form will do. Please see below:
<form id="myForm" name="myForm" action="anotherPage.php" method="post">
<input name="item1">......</input>
<input name="comment1">......</input>
</form>
To submit using javascript, just use something like this on your function:
function submitForm() {
document.myform.submit();
}
the problem is name
of your input is not same with your $_POST
index
your input: <input name="item1">
your post index: $_POST['item_1']
and also its not right way to use PHP function inside Js, this:
function redirectToAnotherPage(){
<?php $_SESSION['item_1']=$_POST['item_1'] ?>;
<?php $_SESSION['comment1']=$_POST['comment1'] ?>;
location.href='anotherPage.php';
}
you need to set $_SESSION
directly in thisPage.php
(ajax post url)
EDIT :
dont use serialize()
, this way instead:
function submitOnclick()
{
$.post(
"thisPage.php",
{item_1 : $('input[name="item_1"]').val(),
comment1 : $('input[name="comment1"]').val()
}
);
redirectToAnotherPage();
}
good Luck !!!