PHP session variable not persisting through AJAX call - javascript

I wanted to use HTML links to change a session variable in PHP. To do this, I set up an HTML "a" tag that would call a javascript function that looks like this:
function changeValue(name){
data = "key='person'&value=" + _name;
$.ajax({
url: www_root + "/funcs.php?func=set_session_var",
type: "post",
data: data,
success: function(data){
console.log(data);
}
});
}
Then, I had the funcs.php script which had the set_session_var function like this:
function set_session_var(){
session_start();
$key= trim($_GET["key"]);
$value= trim($_GET["value"]);
$_SESSION[$key] = $value;
session_write_close();
echo $key;
}
Then, the original php/html page would reload, but it would first load an external page (call it item.php) that settled all of the php session stuff. Looks like this:
session_start()
$session_id = session_id();
$sc = $_SESSION['person'];
However, the $sc variable always shows up as empty, despite the AJAX success function returning the right value. I've checked the session_id's for both scripts, and they are the same. I have also tried to set a session variable in item.php, and it persists. It's just that when I set a session variable using the funcs.php script it doesn't save.
Any and all ideas are appreciated!

You're sending quotes:
data = "key='person'&value=" + _name;
^------^
which means you're effectively doing:
$_SESSION["'person'"] = $value;
^------^-
Note that those single quotes have become PART of the session key name.
Try
data = "key=person&value=" + _name;
^----^--- no quotes
instead.

Related

Store JavaScript variable in a php variable without page refresh

I've been been through numerous articles on here and tried dozens of variations including ajax. What I want to do is click a button and store the id of that button in a php variable without having to refresh the page.
I've tried using isset and POST and I get some variation of Undefined key array.
Ajax was suggested but when I use ajax I can get the variable stored, but I'm unable to get it into a php variable.
Current setup...
I have an HTML button from which I need the id stored in a php variable so I can use it in another SQL statement. This button is part of an HTML table of MySQL records returned from the db.
<input type='button' value='Edit' name='editbtn' onclick='edit(this.id)' id = '" . $row['id'] . "'/>
JavaScript...
function edit(clicked_id){
var selid = clicked_id;
var seleid = selid.toString();
$.ajax({
type: 'post',
data: {name: seleid},
datatype: 'text',
success: function(data){
console.log(name);
alert("Success, data is: " + data); // This correctly returns the id of the button clicked
},
});
}
The PHP at the top of the page is...
if(isset($_POST['name']) && !empty($_POST['name'])){
ob_clean();
$varid = $_POST['name'];
echo $varid;
exit;
}
PHP is not receiving anything. Is there a way to do this? I guess it's a backend/frontend issue?
Note: I have been able to store a JavaScript variable in an HTML tag but I've been unable to use it as part of a SQL statement, even after trimming the tags off of it.
Please help and thank you!
Try something like this in your php code :
$data = json_decode(file_get_contents('php://input'), true);
if(isset($data['name']) && !empty($data['name'])){
ob_clean();
$varid = $_POST['name'];
echo $varid;
exit;
}

how to recover and pass multiple php variables in my AJAX call

I need to pass my PHP variables defined (earlier in my page) in my Ajax call.
And I have a lot of variables defined so I cannot do it var by var in my code.
My first question is, is there a way in PHP to loop on every defined variable ? like get my $var1, $var2
I think I could do it earlier in my PHP page between <script> tags but this is really not clean.
My AJAX call is like so:
function add_content_in_divs(class_name, target_div) {
var page_name = 'displayer/' + class_name + '_informations.php'
$.ajax({
url:page_name,
type: 'GET',
data: {//need to pass my PHP vars here},
success: function (resp){
target_div.html(resp);
}
})
}
My final goal is to include a part of PHP code in my div, knowing that this include contains $vars defined in my main PHP page. So my includes parts of code doesn't recognize my PHP vars in.
There is an example of code part I have to include.
if (isset($detail)) {
echo '<div class="row"><span class="font-weight-bold">City detail: </span>' . $detail . '</div>';
}

How to get values from url to js?

I am having the trouble to find a solution how I can get the values from the object which is requested from link from my web..
The thing is that I was created method in PHP to get the data from the database of the values of one object which I have to parse in my modal window so I don't have to refresh page to get details about my product.
Here is PHP code to get the details which perfectly works and my URL returning the $data object with values.
Controller.php
public function orderinfo($id){
$orderInfo = $this->adminsModel->getOrderInfo($id);
$data=['orderInfo'=>$orderInfo];
$this->view('admin/orderinfo',$data);
}
And the model function for php:
public function getOrderInfo($id){
$this->db->query("SELECT * FROM ORDERS WHERE id ='$id'");
$row = $this->db->single();
return $row;
}
And the thing is that I learned easily how to get id in javascript of my object which has the id in database.
here is code to get id and i understand it how it works:
HTML:
<a class="fa fa-file-audio-o edu-back-restart" href="#"
data-toggle="modal" data-target="#InformationproModalftblack"
id="<?php echo $activeOrders->id; ?>"
onclick="showDetails(this)">INFO</a>
NOTWORKING CODE:/mytry/
Javascript to get object id and to get object and its values (object and values is my problem):
<script>
function showDetails(a) {
$("#"+a.id).click(function () {
alert(a.id);
});
//NOT WORKING-How to get object from url?
$.ajax({
url: "localhost/test/orderinfo/280",
method: "GET",
datatype: Object,
success: function(response){
var customer =response;
console.log(response);
}
});
}
</script>
I don't know how to get whole object from that url with js or ajax and i don't know how to get object values as : id, name, street..
Thank you so much for you help...
sorry if i have some mistakes in explanation the problem.
When you are running the ajax call, the URL field should be referencing the PHP script that you are trying to run, e.g:
url: "localhost/test/orderinfo/Controller.php",
Next, make sure the PHP script is calling the orderinfo() function at some point. If you have this function in a larger script and don't have any logic for invoking it, I would recommend putting the function in a smaller PHP file whose sole purpose is to return the output of that query. For example:
//Whatever you need to import to make your query calls
//Whatever variables you need to initialize for your query calls
$temporary_id = "ABC123";
public function orderinfo($id){
$orderInfo = $this->adminsModel->getOrderInfo($id);
$data=['orderInfo'=>$orderInfo];
$this->view('admin/orderinfo',$data);
}
return orderinfo($temporary_id);
If you could provide any information about the object you are returning as well as the output of that console log, that would be extremely helpful.
Edit: Just noticed the comments, you could pass the id value in as data:
url: "localhost/test/orderinfo/Controller.php",
data: {'id':id_variable},
And then in the PHP, get the id value using $_SESSION['id'];.
Alternatively, you could pass it as a URL parameter:
url: "localhost/test/orderinfo/Controller.php?id=ABC123",
data: {'id':id_variable},
And get in the PHP using:
$id = $_GET['id'];
The value of the ID should be stored in that PHP variable as ABC123.
Hope this helps.
The best way for sending data from PHP to JS is encoding them as JSON object with json_encode.
public function orderinfo($id){
$orderInfo = $this->adminsModel->getOrderInfo($id);
$data=['orderInfo'=>$orderInfo];
$this->view('admin/orderinfo',json_encode($data));
}
so in your JS you can decode it with parseJSON like
<script>
function showDetails(a) {
$.ajax({
url: "/test/orderinfo/280",
method: "GET",
datatype: JSON,
success: function(response){
var obj = jQuery.parseJSON(response);
console.log(obj);
}
});
}
</script>
Note that you don't need to return whole $data in this object, and probably you even should not do it for performance and security reasons.
Instead, just prepare the object with only the data required for JS and send them as shown.

Failing to send to $_POST but $_SESSION says something else

I do not know what is happening with my code, when I run it, sometimes SESSION says there is an array is stored and sometimes it doesn't. I am using a debugger to check the session. When I use isset($_POST), the return value is always false. I am using ajax to pass an array to php.
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
Javascript:
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
window.location.href = 'example.php';
var jExample = JSON.stringify(array);
$.ajax({
data:{'jExam':jExample},
type: 'POST',
dataType: 'json',
url: 'example.php'
});
});
EDIT:
Figured out why the arrays are stored into SESSION, once I click on the button that opens the other page, and then type in the page before in the url, the array is stored into the SESSION. Don't know why. Still can't figure out why ajax is not sending to post.
EDIT 2:
I created a file that handles the request called handle.php. So the php script on top is added into handle.php instead of the webpage. But I am getting a "Parse error: syntax error, unexpected 'if' (T_IF)". The code is still the same on top.
handle.php:
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
EDIT 3:
I am using the ajax to pass an array to php in order to store it into session, in order to use the array in another page. The problem is that the array is not passing into $_POST. What I am hoping is that the array can actually pass so I can use it on another page.
SOLVED:
All i did was add a form that has a hidden value. And the value actually post
<form id = "postform" action = "cart.php" method = "post">
<input type = "hidden" id="obj" name="obj" val="">
<input type = "submit" value = "Show Cart" id = "showcart">
</form>
In the Javascript:
$(document).ready(function(){
$("#showcart").click(function(){
var json = JSON.stringify(object)
$('#obj').val(json);
$('#obj').submit();
});
});
Thank you for everyone at has answered but hope this helps others.
If example.php is the php file which handles the request, you need to change your js code to
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
var jExample = JSON.stringify(array);
$.ajax("example.php", {
data:{'jExam':jExample},
type: 'POST',
dataType: 'json'
});
});
And you should add the complete-Parameter if you want to handle the response.
Your mistake is, you are redirecting the page using window.location.href before you even send your request. Therefore, your request never gets sent and the PHP-File is called directly instead, not via AJAX, not with the nessecary data. Therefore, you are missing the data in the PHP-File.
You will want to try and make this setup a bit easier on yourself so here are a few things that can help you simplify this. You may or may not have some of these already done, so disregard anything you already do:
Use a config file with concrete defines that you include on 1st-level php files
Just pass one data field with json_encode()
Don't send json as a data type, it's not required, troubleshoot first, then if you need to, make it default as the send type
Use a success function so you can see the return easily
Make functions to separate tasks
/config.php
Add all important preferences and add this to each top-level page.
session_start();
define('URL_BASE','http://www.example.com');
define('URL_AJAX',URL_BASE.'/ajax/dispatch.php');
define('FUNCTIONS',__DIR__.'/functions');
Form:
Just make one data that will send a group of data keys/values.
<button class="cart" data-instructions='<?php echo json_encode(array('name'=>'Whatever','price'=>'17.00','action'=>'add_to_cart')); ?>'>Add to Cart</button>
Gives you:
<button class="cart" data-instructions='{"name":"Whatever","price":"17.00","action":"add_to_cart"}'>Add to Cart</button>
Ajax:
Just send a normal object
$(document).ready(function(){
// Doing it this way allows for easier access to dynamic
// clickable content
$(this).on('click','.cart',function(e)){
e.preventDefault();
// Get just the one data field with all the data
var data = $(this).data('instructions');
$.ajax({
data: data,
type: 'POST',
// Use our defined constant for consistency
// Writes: http://www.example.com/ajax/dispatch.php
url: '<?php echo URL_AJAX; ?>',
success: function(response) {
// Check the console to make sure it's what we expected
console.log(response);
// Parse the return
var dataResp = JSON.parse(response);
// If there is a fail, show error
if(!dataResp.success)
alert('Error:'+dataResp.message);
}
});
});
});
/functions/addProduct.php
Ideally you would want to use some sort of ID or sku for the key, not name
// You will want to pass a sku or id here as well
function addProduct($name,$price)
{
$_SESSION['cart'][$name]['name'] = $name;
$_SESSION['cart'][$name]['price'] = $price;
if(isset($_SESSION['cart'][$name]['qty']))
$_SESSION['cart'][$name]['qty'] += 1;
else
$_SESSION['cart'][$name]['qty'] = 1;
return $_SESSION['cart'][$name];
}
/ajax/dispatcher.php
The dispatcher is meant to call actions back only as an AJAX request. Because of the nature of the return mechanism, you can expand it out to return html, or run several commands in a row, or just one, or whatever.
# Add our config file so we have access to consistent prefs
# Remember that the config has session_start() in it, so no need to add that
require_once(realpath(__DIR__.'/../..').'/config.php');
# Set fail as default
$errors['message'] = 'Unknown error';
$errors['success'] = false;
# Since all this page does is receive ajax dispatches, action
# should always be required
if(!isset($_POST['action'])) {
$errors['message'] = 'Action is require. Invalid request.';
# Just stop
die(json_encode($errors));
}
# You can have a series of actions to dispatch here.
switch($_POST['action']) {
case('add_to_cart'):
# Include function and execute it
require_once(FUNCTIONS.'/addProduct.php');
# You can send back the data for confirmation or whatever...
$errors['data'] = addProduct($_POST['name'],$_POST['price']);
$errors['success'] = true;
$errors['message'] = 'Item added';
# Stop here unless you want more actions to run
die(json_encode($errors));
//You can add more instructions here as cases if you wanted to...
default:
die(json_encode($errors));
}

append javascript variable after page load

How do I add a javascript variable to a page after the page loads? I have a PHP ajax function that I need to return a javascript variable. I've tried echoing the variable between script tags and it's not working.
The way I do this, is to create a php document that just echos out the variable, with no markup, and not even any trailing linebreaks.
<?php echo($var); ?>
Then ajax that page, and in the success clause of the ajax call, just do;
success: function(result) { myGlobalJavascriptVariable = result; }
If you don't know the variable name at page load, you could do it this way:
Javascript:
$.ajax({url:'/releventScript.php',
data: RelevantData,
dataType:'json',
success:function(data){
window[data.varName]=data.varValue;
}
});
PHP Script
$response=array('varName'=>'Foo',
'varValue'=>'Bar');
header('Content-Type: text/json');
echo json_encode($response);
exit;
This will allow you to dynamically create variables in the global namespace.

Categories