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

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
}
},
});

Related

Create a waiting page with PHP and twig

I post data to a page and make some checks that take 5-6 seconds. I would like to insert a waiting page to improve the user experience.
My code is like this:
....functions that take time
echo $twig->render('template.html.twig',[ variables ....]);
Because PHP calls the twig template at the end after processing the data I cannot use a javascript solution.
I tried rendering a waiting template first, then process the data and store the output in a session variable then after that send a location header to the results page but I found PHP does not echo the waiting template untill it finishes the whole script even if i call it in the beginning.
echo $twig->render('waiting.html.twig',[ variables ....]);
....functions that take time
store output as session variable.
send location header to another page that renders the template from the session variable
How can I achieve a waiting page?
You could always store the data temporarily and load a dummy "loading page" for the user. And right when the dummy page loads you send an ajax request that recovers your data and processes it. When the ajax call returns you could do your redirection or whatever it is you want to do when the process is done.
When I say "store the data temporarily" I mean in a database or a file, etc.
The solution I ended up doing was the following:
Call the page by Ajax and display a waiting page.
function submit_form(file_method) {
var spinner = $('#loader');
spinner.show(); //show waiting div
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
success: function (res, status) {
if (status == 'success') {
window.location.href = 'results.php';
} },
error: function (jqXHR, textStatus,res) {
spinner.hide();
alert('Error encountered: '+textStatus+'-'+jqXHR.responseText);
} })
};
In the php page, store the output as an array in a session variable.
....functions that take time
$_SESSION['result'] = [RESULTS .......]
After the ajax call is completed successfully the user is redirected to a new page. The new page uses the session variable to call the template.
echo $twig->render('waiting.html.twig',$_SESSION['result'] );
unset($_SESSION['result']);
Simplest solution is to add 'waiting page' inside first page but hide it. When user presses button browser will send request, but will still wait for response showing old page. Here you can show it using JS.
In short - user presses button, you show template (which was already there but hidden) and then browser just waits for response with your template in front.
But best way would be to use AJAX like Patriot suggested.

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

Check database after inserting data and update listview

What I know is how to download and upload data from the database.
But how do I control, whether a data has been uploaded on the database? And if a data has been uploaded, I want to know how to get this data to put this to the listview without reloading the whole database again?
In other words I want to have the new written text in the listview in real time, like a messenger.
Piggybacking off of #CptMisery's answer here, I agree that ajax would be useful for this.
I use this quite often when I'm writing to a database - as a form of callback to ensure data was actually written. First, here's the code you'd execute in JavaScript:
$.ajax({
type: 'POST',
url: 'some_php_page.php',
data: { data:data },
success:function(data){
if ( data == 0 ) {
console.log("item has been updated");
} else {
console.log("item has NOT been updated");
}
}
}); //close ajax
What this does is the ajax call sends the variable data as a POST to your some_php_page.php. You can send multiple items like this: data: { data:data, variable1:variable1, age:age, date:date }. The PHP page does something, (e.g. - writes to the database), and if it's successful, you have PHP echo "0", otherwise you have it echo "1". The ajax success call happens once the some_php_page.php returns a value. The success call reads that value and then does something. This is a relatively simple way to accomplish (I think) what you're looking to do.

How can I use Ajax to delay a PHP for loop and echo out PHP on screen?

i'm not sure whether Ajax is what I need as i'm rather stumped on where to start, but I'll describe what I would like to happen.
I have a PHP file (lets call it scan.php) that contains a For loop that iterates along an array, which holds details of local files stored in a directory on a PHP. For each item in the array (a path to a file), I would like it (presumably an ajax script?) to call another php file (lets call it info.php) and display whatever that PHP file outputs on screen, with info.php taking the filepath in that index of the array as an argument.
Within that info.php file are various (dynamically generated) divs which inserts a different value into the database depending on which div the user clicks on. When that user clicks on a div, it inserts a value into the database (via an ajax call that i've already got working) and then displays a message (i'm using a javascript window.alert). If that message is a success then the info.php function ends, an we return back to scan.php. Whatever echoed out by info.php is cleared and then the loop iterates round again.
Sorry it's a bit complex but I have no idea where to start. Could anybody give me any hints on how to get started? I've had a look at ajax but frankly I have no idea where to start and whether it's even possible to use ajax to delay the PHP for loop.
This was my script that I thought would display info.php, but it's not echoing anything into the "show" div - or anything at all:
function Search_file(path) {
$( "#show" ).empty();
var request = $.ajax({
url: "info.php?path="+path,
type: "GET",
dataType: "html"
});
$("#show").html(result);
request.done(function(data) {
alert("Next file");
});
}
AJAX is asynchronous, so you haven't received your result when you are setting your html. You need to move your 'show' code inside the done handler like so:
function Search_file(path) {
$("#show").empty();
var request = $.ajax({
url: "info.php?path="+path,
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("#show").append(result);
alert("Next file");
});
}

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.

Categories