Updating session using AJAX - php

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.

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

Json result into PHP variable

I have a script that calls dat from my table and returns it in JSON format. How do I echo out the var nps and data as php variable.
My script:
$.ajax({
type: "POST",
url: "../charts/1-2-4-reports_nps.php?TAG=<?php echo $_SESSION['SectionVar'];?>&From=<?php echo $_SESSION['StartDate'];?>&To=<?php echo $_SESSION['EndDate'];?>",
cache: false,
success: function(data){
var nps = data[0].name;
console.log(nps);
var data = data['data'];
console.log(data);
$("#div1").append($("<div/>", { id: "div2", text: nps }));
}
});
My Json returns:
[{"name":"nps","data":[35]}]
Something like $nps = data['nps'] and echo the result of $nps.
I think initially you were confused about the contexts your code is running in. var nps = data['nps']; is JavaScript. It runs in the browser, and it runs after the page is loaded.
$nps by contrast is a PHP variable, and PHP runs on the server, and it runs before the page is loaded. In fact it is the PHP which creates the HTML, CSS, Script etc which is then downloaded to the browser. After that is downloaded, the JavaScript executes separately.
There is no direct connection between the two languages, other than you can use PHP to generate JavaScript (just like you use it to generate HTML).
Once you understand that, then you realise that to display your nps variable further down the page, you need to use JavaScript to manipulate the web page and insert the data.
The first issue to resolve with that is that the data being returned from the server is coming back as a string that looks like JSON, but not an actual JSON object. You can add
dataType: "json"
to your ajax options, and that tells jQuery to treat the returned data as an object instead of a string.
The next problem is that data is an array, containing a single object, and you were trying to read it like it was just a plain object.
So you get data out of it, and, as you requested, display each value in a new div which gets inserted into an existing div, you can do the following :
function success(data)
{
var nps = data[0].name;
var dt = data[0].data[0];
$("#div1").append($("<div/>", { id: "div2", text: nps }));
$("#div3").append($("<div/>", { id: "div4", text: dt }));
}
You can see a working example (with simulation of the ajax call, but using the correct data structure) here: https://jsfiddle.net/yukot05x/5/

Refresh a div automatically when a PHP variable is updated

I have a div that calls a variable. When that variable changes, users need to refresh the page to see the new value. The variable is pulled from a separate PHP file.
I'm wondering if there's a way to use ajax to automatically update the div without the user refreshing the browser when it sees the PHP variable has been updated.
You could periodically check if there have been any change to the variable using ajax and if that is the case you could update the div.
var previousValue = null;
function checkForChange() {
$.ajax({
url: 'http://example.com/getVariableValue.php',
...
success: function(data) {
if (data != previousValue) { // Something have changed!
//Call function to update div
previousValue = data;
}
}
});
}
setInterval("checkForChange();", 1000);
I havn't tested the code, but it should be something like that. Will get data from http://example.com/getVariableValue.php, you'll have to fill in some information about the AJAX request. I'm assuming you know how to modify the code for your specific data format, be it XML, JSON or text.

Setting PHP SESSION var from within JS

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

Sending Data From A PHP Script Back To A JQuery AJAX Request

I am creating a web application and have the following problem.
In my application the user is working within a single page, they draw on a canvas. There is a single button called "Save". This takes the users ID and whatever they have created in the canvas and sends it to a database. This all works fine. The save function resemebles this:
$.ajax({
url: "/database/write.php",
type: "POST",
data: {
docName: name,
docData: document_Data,
docMode: "new"
},
success: function(html) {
alert("Successfully Saved NEW document");
set_Mode();
},
});
The above AJAX request does send the three values to the PHP script which then successfully creates a new document in the database, what i need to do now is change the application mode from saving a new document to editing the previously saved document. This means that when a user saves again, they will write to the same row, overwriting the previous version of the document.
When i send the data to the write.php it does write the data to the DB and the queries the database for that inserted document and retrieves its unique document ID. with that ID the application can the select that document and overwrite it. To retrieve the document ID from the query, i use the following code in write.php
write.php
$_SESSION['DOCUMENT_ID'] = $DOCUMENT_ID;
This $DOCUMENT_ID is the document ID retrieved from the SELECT query. The script then finishes and transfers control back to the main application page.
Back on the application page i try to retreive the value but it doesnt seem to work. I can retrieve $_SESSION values that were set when the user first accesses the application (id) but now values set by the write.php (DOCUMENT_ID) page. For example, below shows the function called after the AJAX request has been successful:
function set_Mode()
{
var PHPvar_01 = <?php echo($_SESSION['id']); ?>;
alert(PHPvar_01); //WORKS FINE
var PHPvar_02 = <?php echo($_SESSION['DOCUMENT_ID']); ?>;
alert(PHPvar_02); //DOES NOT WORK.
};
How should i go about sending data retrieved from the PHP query script to the application, because $_SESSION does not seem to work here.
Thanks for any feedback.
at the end of write.php :
echo json_encode(array('id'=>$_SESSION['id'], 'DOCUMENT_ID'=>$_SESSION['DOCUMENT_ID']));
in your ajax call :
success: function(data) {
data = eval('('+data+')');
alert("Successfully Saved NEW document");
set_Mode(data.id, data.DOCUMENT_ID);
},
this should do the tricks !
In your write.php, you should echo the $DOCUMENT_ID at the end of the page, and then your success function will receive that in the html argument. Then you should call set_Mode with the html variable that was passed into the success function.
You can't call set_Mode until after the page is loaded, and after you know the document ID. You are writing the document ID into the set_Mode function before you know it, in the initial page load.
Well, your PHP code gets executed only once upon the initial loading of the page. The server detects a request to your site, loads the PHP document internally, parses it and delivers it to the client.
Therefore, when the AJAX call returns, the entire PHP script is not executed again, because the user didn't request the whole page but only sent a single request to your write.php.
Your write.php script must return the $DOCUMENT_ID in some way, e.g. echo it directly, then the success handler in the jQuery AJAX call can access it via the handler's parameter (see jQuery documentation).
You can't access variables on the server when the page is already loaded in the users browsers, other than with ajax.
You need to send something back, and in PHP all you have to do is echo something, and capture it in the success function of your Ajax call.
at the end of /database/write.php, do
echo $_SESSION['DOCUMENT_ID'];
and in JS
$.ajax({
url: "/database/write.php",
type: "POST",
data: {
docName: name,
docData: document_Data,
docMode: "new"
},
success: function(data) {
alert("Successfully Saved NEW document");
set_Mode();
if (data == 'something') {
//do something with the returned DOCUMENT_ID stored in the data variable
}
},
});

Categories