Setting PHP SESSION var from within JS - php

Is there a way to set a session variable from withing my JS function?
I have the following JS code:
$.ajax({
url: "ajax.php",
type: "POST",
data: {
tid: '.$testID.',
do:"'.$do.'"
},
success: function( html ) {
$("#partBox").html( html );
// add PHP here?
}
});
I would like to set the following var in the session, on SUCCESS:
$_SESSION['hgt'] = 'Math.ceil($("#partBox").height() / 2)';
I have no idea if this is even possible... Alternatively I could probably use cookies...

You can't set any PHP variables in JavaScript. Once the Page has finished loading PHP has done its job and is out of the picture. If you want to set a session variable using JavaScript you can do it one of two ways:
Use Ajax to send the value to a PHP script to set the session variable
Store it in a cookie and on the next page load have PHP use the value of that cookie to create the session varibale

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

Updating session using AJAX

I want the session to be updated whenever an element is clicked in the div, but it looks like my session is not updating whenever I use an ajax. I want the session to be updated, not just printing the data in my ajax.
here is my ajax:
$('.chat_div').click(function(){
var id = $(this).attr('id');
$.ajax({
url: 'plugins/get_id.php',
data: {id:id},
success: function(data)
{
alert("<?php echo $_SESSION['chat_mate_id'];?>");
}
});
});
here is my php file:
session_start();
$_SESSION['chat_mate_id'] = $_GET['id'];
You are generating an HTML document, which has some embedded JS in it. At the time you generate the HTML document, you output the value of a session variable into the JS as a string literal.
Next, you run the JS, which makes a second HTTP request, and updates the value of the session variable.
When the response arrives, you alert the value of the string you injected into the page when the original page loaded.
If you want to react to the new value of the session variable, then you have to use data that you get from the server after you update the value.
The output of running a PHP program a minute ago will not change retroactively. Ajax is not time travel.

How can I pass a variable from JSON to PHP?

I'm using JSON to produce some data on Wordpress which I need to store in a PHP session variable. Here's the current setup that I'm messing around with but having no luck:
jQuery(document).ready(function($) {
$.ajax({
url: 'url',
type: 'POST',
dataType:'json',
data: {foo: 145},
success: function(data){
console.log(data);
alert(data);
}
});
});
and the PHP:
session_start();
$_SESSION['bar'] = $_POST['foo'];
I can see the data in the console but nothing will display when I echo my sesh var. Using vardump returns an empty array. Where am I going wrong here?
(I realize there are plenty of other questions just like this, but believe me, I've tried them all - nada.)
Answer: You can't use javascript to store server side variables.
You must save the $_SESSION var in the PHP script that this AJAX calls. Which you have put URL?? In WordPress you can use JQuery to call a special hook which can be caught he functions.php that handles all AJAX.
There's info about this everywhere, see solution to this answer:
Using AJAX in a WordPress plugin
You would have to set a global variable for both languages and then transfer them via javascript you could do this on every page using php includes.

Store javascript select option into php variable

I want to retrieve a value from a HTML selection drop-down and store it into a PHP variable. I'm sure this has to be done in AJAX, but I'm not sure on the details. Is it possible to get that value of the option field and store it into a PHP variable this way?
$("#files").change(function() {
$.ajax({
type: "POST",
url: "parse.html",
data: {$'files'= $(this).val()},
success: function(response) {
//lolwut?
}
});
});
I want to store it in a php variable $x is what I just labeled it. The selection is title files.
Thanks.
You're pretty close. The data portion of the AJAX call should contain a key/value pair. Example:
data: {selectVal : this.value},
Now on your PHP backend, you can retrieve the variable with:
$selectValue = $_POST['selectVal'];
Do with it what you want, and you can return whatever you want to the client-side as well with echo. Whatever you echo back can now be picked up in the AJAX success callback under your variable response.
Also, set your url to your PHP page url.

Possible to pass a variable from jQuery with AJAX to PHP page and a session variable? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Passing javascript variable to PHP
Hi
I wonder if it's possible to pass a variable from a jQuery script to a PHP-page and put the variable into a session variable like this:
$_SESSION['mapZoomArea'] = (isset($_GET['mapza']) ? $_GET['mapza'] : "";
I'm not sure how to pass the variable and the url to the server? Preciate some help!
Thanks!
If you want a dedicated service specifically for writing this value into the session, you probably should make it a POST request (GET will work too, but GET requests should be for data retrieval, not for writing to the server).
Therefore, simply create a new PHP page, let's say "storezoomarea.php", and have jQuery make an Ajax POST request to that page:
$.ajax({url: "storezoomarea.php", type: "post", data: {"mapza": mapza}})
Then, on the server side, you can retrieve it from the _POST variable:
$_SESSION['mapZoomArea'] = (isset($_POST['mapza']) ? $_POST['mapza'] : "";
Not bad. Make sure you've called session_start(); first. Pass the variable in as a query string, 'http://whatever.com/?mapza=yourvariablevaluehere'. You can do this with jQuery by:
$.ajax({
url : 'urlhere',
data : { mapza : 'your variable value here' }
});
Ok.
Yes, you can pass that var to a php code, if you make an AJAX call, with jquery ($.Ajax(whatever)), and of course, in the file called with AJAX change the session var.
Hi you should use AJAX. Since you have JQuery available it is very simple.
More reading available here http://api.jquery.com/jQuery.ajax/
Example:
$.ajax({
type: "GET",
url: "some.php",
data: ({'mapza' : yourvariable}),
success: function(msg){
alert( "Data Saved: " + msg );
}
});
HTH :)

Categories