PHP variable resets/not available after jquery load - javascript

I'm using jquery .load() to show a php file that basically fetch data from a table. Inside the while loop, I have a variable which checks my user's ranks, however, on every .load() this variable seem to become unavailable and everything in the if statement containing that variable, disappears.
Now I am aware of this:
PHP runs before any browser response is issued to the client, and all
code runs on the server. The variables declared in your PHP file are
destroyed after all the PHP code has been run; they "vanish."
JavaScript runs after the browser response has begun, and all code
runs on the client. By "loading" the output result of the PHP file,
you won't get any access to PHP's variables, only the output.
However, how am I supposed to access my variable this way?
This is the line that disappears after .load()
<div id="deleteSB">
<?php if($u_rank >= 2) {
?>
<div style="float: left;margin-top:3px;margin-right:5px;" id="deletesb">
<a href="<?php echo $siteurl;?>/forum?getDelSb=<?php echo $fetchshoutquer['id']; ?>">
<img src="<?php echo $siteurl; ?>/img/delete.png" /></a></div>
<?php } ?>
</div>
Where $u_rank is the variable that I need. If I remove that if statement, everything works fine.
This is the jQuery:
function loadlink(){
$('#loadshoutbox').load('http://localhost/shoutboxcontent.php');
}
function loadlink2(){
$('#shoutboxinput').load('http://localhost/shoutboxinput.php');
}
loadlink(); // This will run on page load
loadlink2();
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
setInterval(function(){
loadlink2() // this will run after every 60 seconds
}, 60000);
I thought of storing the contents of $u_rank in a jQuery variable, but then I don't know how to do with the if statement...

So, I guess you're looking for sessions then.
http://www.w3schools.com/php/php_sessions.asp

I believe you're looking for a $.post, or AJAX call
$.post('script.php', {variableIn:variableIn}, function(data){
var u_rank = data;
});
You need to call the PHP again to grab that variable from the PHP script. This is extremely simplified of course and you'll need to figure out what data you're bringing back. You can return anything echoed from the PHP script using that data.
For example. when I return a few results from my PHP script:
echo $var1 . ":" . $var2;
data will return "variable1:variable2". Then I use split in my AJAX call like so:
$.post('script.php', {variableIn:variableIn}, function(data){
var var1 = data.split(":")[0];
var var2 = data.split(":")[1];
});

Related

PHP method calls from Javascript not showing up in Wordpress source

I am running a Wordpress website, and trying to call PHP methods from my Javascript code.
When a button is tapped, the saverFoo() Javascript method is called, and attempts to call the PHP method save_image_data().
function saverFoo() {
var dataURL = canvas.toDataURL();
<?php echo save_image_data(dataURL); ?>;
}
function loaderFoo() {
var loadedImage = <?php echo loadimagedata(); ?>;
console.log(loadedImage);
}
The PHP method's implementation is in the function.php file, and is simply attempting to save some image data (dataURL) in the user's meta
function save_image_data($imageData) {
global $current_user;
update_user_meta( $current_user->ID, 'user_design', $_POST['$imageData']);
}
function loadimagedata() {
global $current_user;
$old_notes = get_user_meta($current_user->ID, 'user_design', true);
return $old_notes;
}
Inspecting my web-page in Chrome, shows me an empty space where loaderFoo () (javascript) is supposed to be calling loadimagedata() (php) , and loadedImage is an undefined variable, when I try to log it, such as:
function loaderFoo() {
var loadedImage = ;
console.log(loadedImage);
}
Not sure what fundamental mistake I'm making here.
Always remember that PHP runs on the server side, and javascript on the client side. So we have an order here, the server receives the request PHP processes what it should process and render the page, only here Javascript will be executed.
In this example, when the 'saverFoo()' function is executed, this function <? Php echo save_image_data (dataURL); ?>; has already been written on the page. PHP will not be able to get the information contained in the dataURL variable, not on this way. To do this, we must make a request to the server with this desired information, but with an "image" is not trivial to do this, as there is a limit on the size of the post when using a normal String field.
function saverFoo () {
    var dataURL = canvas.toDataURL ();
    <? php echo save_image_data (dataURL); ?>;
}
PHP doesn't work that way. It is a pre-processor. It is all run and done server side and the resulting text/html/binary data/whatever is sent out to the client. In the case of a content type of text/html the browser will load it, parse it, render it, and run whatever javascript is called.
How you can mix PHP and JavaScript in-line like that would be to use PHP to fill in variables. For example
alert("<?php print($_SERVER['SCRIPT_FILENAME']); ?>");
would work because the client would see
alert("/path/to/foo.php");
and render that for the user.
To really interact with PHP using JavaScript, you'll want to look into using a http based REST type service and perhaps one of the various popular tool sets like Angular, Vue, etc.

Php script is automatically being invoked multipletimes

I am facing a strange issue here.
I am using javascript ajax(I used jquery). Now the scenario is;
One ajax call is invoking a php script which is basically a long running process and it sets some session variables.
Later in some intervals(lets say in each 2 sec) I am running another ajax calls to check the session variables to know when the process(first php script execution) is completed.
First php script is fetching data from database and wring it into a file. In each fetching I am counting the loop number and storing it into a session variable to keep some kind of tracking record. Like;
$i=0;
$_SESSION['time']=date('m-d-Y H:i:s');
while(...)
{
ini_set('session.use_only_cookies', false);
ini_set('session.use_cookies', false);
ini_set('session.use_trans_sid', false);
ini_set('session.cache_limiter', null);
session_start();
$_SESSION['tracksatus']="loop number : ".$i." time is :"$_SESSION['time'];
session_write_close();
$i++;
......
......
}
Another php script which I am invoking via setInterval ajax is just doing like;
echo $_SESSION['trackstatus']
The set interval ajax is returning me like;
loop number 1 time is m-d-Y H:i:s
loop number 5 time is m-d-Y H:i:s
loop number 8 time is m-d-Y H:i:s
......
Then after few call again;
loop number 1 time is m-d-Y H1:i1:s1
.....
Notice the change of H:i:s to H1:i1:s1
So as per my understanding the php script is invoking twice. And for your information same code was working just before 12 hrs may be. And I faced this issue before and somehow solved it(trial and error so I don't know how or may be automatically....ok actually I have no clue).
Can you please give me an insight what I am doing wrong?
Please mention if you need more information.
And the funny thing is that it is working as expected just after asking this question without even changing a single line of code. But I want to know the reason.
I think that I know what the reason, PHP writes session variables to file, but it do it only on end of script execution, so you can`t see the changes of session in another script before end of long one.
You can fix it by adding session_write_close(); session_start(); after each change of session data.
session_write_close will write changes to HD, so another script can read it.
session_start will load session from HD, but make sure that your another script make no changes for a session, these changes will be overwritten by your long script.
And one more thing if you are using separate domains:
Before actual AJAX call happen your browser sends OPTIONS request to the same URL for checking CORS headers. So on start of your script check the HTTP METHOD and if it HEAD or OPTIONS make die();
Instead of using sessions, try using a temp file to keep count with a dynamic ID
Javascript
var time = Date.now();
$.get('/firstURL?time='+time);
setInterval(function(){
$.get('/secondURL?time='+time, function(response){
console.log(response);
}
}, 1000);
PHP 1st URL
<?php
$id = $_GET['time'];
$count = 0;
while(...) {
// Do your stuff
$count++;
file_put_contents("/tmp/{$id}", $count);
}
?>
PHP 2nd URL
<?php
$id = $_GET['time'];
$count = 0;
try {
$count = file_get_contents("/tmp/{$id}");
} catch(Exception $e) {}
echo $count;
?>
As other have said PHP does not write the session until execution has finished. you better off creating a php function that you call that writes a file with the progress and then your second ajax call just reads the file.
function updateCreateProgress($jobStartTime, $progress){
file_put_contents('/tmp/'.$jobStartTime.'.txt', $progress);
}
function completeProgress($jobStartTime){
unlink('/tmp/'.$jobStartTime.'.txt')
}
now your second script can check for '/tmp/'.$jobStartTime.'.txt' if it's there read it using file_get_contents if its not there report back it has finished.
Try adjusting to something like this:
$i=0;
ini_set('session.use_only_cookies', false);
ini_set('session.use_cookies', false);
ini_set('session.use_trans_sid', false);
ini_set('session.cache_limiter', null);
session_start();
$_SESSION['time']=date('m-d-Y H:i:s');
while(...)
{
$_SESSION['tracksatus']="loop number : ".$i." time is :"$_SESSION['time'];
session_write_close();
session_start();
$i++;
......
......
}
You started talking about $_SESSION before calling session_start();
If you call ajax with GET method - you must set "cache:false" option.
Yes, you must protect your php script from other requests. With unique key (GET parameter) or session.
php lock session data for single call and release it only when this call end. Using session_write_close() when script still working - bad practice. Maybe you want save into session something more after loop but before using this data from other requests.
Flexible and clear solution:
1) script1.php - invoke from ajax for start long job.
2) script2.php (long job here) - run directly from script1.php as background without wait, or add new cron job (insert into table) and run script2.php from cron (check jobs every second or other time).
3) script3.php - check job status (ajax).
For "communication" between script2.php and script3.php can be use database or special file with flock(), clearstatcache() and flush().

Reloading url page with ajax

i'm trying to refresh page every 3 second, the url page change with $_GET variable.
i'm trying to save $_GET var into session and cookie, but get error header has already sent.
how to change url after page reload ?
here my script :
Index.php
<?php
session_start();
$skill =$_SESSION['skill'];
?>
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#src2').load('monitor.php?skill=<?php echo $skill;?>').fadeIn("slow");
}, 3000);
</script>
monitor.php
<?php
include "conn.php";
session_start();
$_SESSION['skill'] = $_GET['skill'];
if ($_SESSION['skill']=='')
{
$a ="bro";
$_SESSION['skill']=4;}
elseif ($_SESSION['skill']==4){
$a = "yo";
$_SESSION['skill']='5';
}
elseif ($_SESSION['skill']==5){
$a = "soo";
}
?>
First off, "headers already sent" means that whichever file is triggering that error (read the rest of the error message) has some output. The most common culprit is a space at the start of the file, before the <?php tag, but check for echo and other output keywords. Headers (including setting cookies) must be sent before any output.
From here on, this answer covers how you can implement the "refresh the page" part of the question. The code you provided doesn't really show how you do it right now, so this is all just how I'd recommend going about it.
Secondly, for refreshing the page, you will need to echo something at the end of monitor.php which your JS checks for. The easy way is to just echo a JS refresh:
echo '<script>window.location.reload();</script>';
but it's better to output some JSON which your index.php then checks for:
// monitor.php
echo json_encode(array('reload' => true));
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
if (response.reload) window.location.reload();
}).fadeIn('slow');
One last note: you may find that response is just plain text inside the JS callback function - you may need to do this:
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
response = $.parseJSON( response ); // convert response to a JS object
if (response.reload) window.location.reload();
}).fadeIn('slow');
try putting
ob_start()
before
session_start()
on each page. This will solve your problem.
Without looking at the code where you are setting the session, I do think your problem is there. You need to start the session before sending any data out to the browser.
Take a look at: http://php.net/session_start
EDIT:
Sorry, a bit quick, could it be that you send some data to the browser in the 'conn.php' file? Like a new line at the end of the file?

Javascript echos PHP command, not PHP variable

The jquery code:
$('.up_IMG').click(function() {
if (notLoggedIn()) return false;
alert('Got to here');
});
The function (attempt #1): in quotes:
function notLoggedIn() {
alert('here');
logged_in = "<?php echo json_encode($logged_in); ?>";
alert('Logged in: ' + logged_in);
}
OR json_encoded (attempt #2):
function notLoggedIn() {
alert('here');
logged_in = <?php echo json_encode($logged_in); ?>;
alert('Logged in: ' + logged_in);
}
When attempt #1 fn is called, the first code block's alert displays:
The second code block does nothing.
The PHP variable does exist and has the value zero.
Any thoughts as to what's happening?
If you're calling this code with a 'click', at that point it's too late for PHP to help you asynchronously.
PHP runs when the page is loaded, not after. It's a matter of timing. PHP can never output something that doesn't exist yet, so it will always be blank.
Explanation of Solution:
The question was caused by a misunderstanding of the relationship between PHP and javascript.
Once the page has rendered (that is, inside jQuery's $(document).ready()), all PHP regular variables no longer exist. The PHP super-variables exist (such as $_SESSION, but not $logged_in.
To possible solutions:
Store logged-in value in a super-global: e.g. $_SESSION['logged-in'], or
Use AJAX inside the javascript $(document).ready() to query PHP if the user is logged in, and receive the answer in the AJAX function's success: function.
Simple explanation of AJAX and how it works

JS variable to PHP variable without buttons or refresh

I've searched for over an hour and tried many examples but none do what I need. From JavaScript I can display the necessary variable in PHP or HTML with <b id="citynm"></b> but I need to make citynm $citynm. I've tried looking in AJAX for the first time but could only get it to work with a button click or page refresh.
I need to run the JavaScript to get citynm and then make it into $citynm for PHP use on any page without running the JS again. The JS is only run once upon entering the site. But the $citynm will be run on several pages in different needs (such as echo "You live in ".$citynm).
The best way is to store the value you want for citynm into a session variable as below:
$_SESSION['citynm'] = $citynm
You have to do this either at page load, or by ajax. Then, you can use $_SESSION['citynm'] in any pages you want since its global.
USECASE 1: via user input
in your html document:
<input type="text" name="citynm" id="citynm" value="Brussels">
inside your javascript file (using jquery here for readability):
(function(){
$('#citynm').on('blur',function(){
// when the input value has changed, post its value to server.
var citynm = $(this).val();
$.post('http://domain.com/path/to/your/php/file.php',{citynm: citynm},function(data){
// if the request is successful, the following script will be executed.
alert("server said: "+data);
});
});
})(jQuery);
And inside the file.php file:
<?php
session_start();
if(isset($_POST['citynm']) && strlen($_POST['citynm'])>0){
$_SESSION['citynm'] = $_POST['citynm'];
}
echo "citynm is ". $_SESSION['citynm'];
?>
USECASE 2: no userinput
var cityname = city.short_name;
if (status == google.maps.GeocoderStatus.OK) { document.getElementById("citynm").innerHTML = cityname; }
(function(){
$.post('http://domain.com/path/to/your/php/file.php',{citynm: cityname},function(data){
// if the request is successful, the following script will be executed.
alert("server said: "+data);
});
})(jQuery);

Categories