Javascript echos PHP command, not PHP variable - javascript

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

Related

PHP variable resets/not available after jquery load

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

AJAX Request For Like Link Not Working

I'm working on a like system with PDO, PHP and AJAX.
But, its not working.
Here's the PHP Code.
$get_likes_sql = "SELECT * FROM `likes` WHERE post_id=:post_id AND liker_id=:my_id";
$get_likes = $db->prepare($get_likes_sql);
$get_likes->execute(array(
":post_id" => $post_id,
":my_id" => $my_id
));
$likes_numrows = $get_likes->rowCount();
if ($likes_numrows == 0) {
echo "<a class='like-link' id='$post_id' title='Like'>Like</a>";
} else {
echo "<a class='like-link' id='$post_id' title='Unlike'>Unlike</a>";
}
Here's the AJAX script.
$(document).ready(function(){
$(document).on('click', '.like-link', function(){
if($(this).attr('title')=='Like'){
$.post('ajax.like.php',{pid:$(this).attr('id'),action:'like'},function(){
$(this).text('Unlike');
$(this).attr('title','Unlike');
});
}else{
if($(this).attr('title')=='Unlike'){
$.post('ajax.like.php',{pid:$(this).attr('id'),action:'unlike'},function(){
$(this).text('Like');
$(this).attr('title','Like');
});
}
}
});
});
The Problem is that nothing happens after clicking on like link neither on unlike link.
This is where debugging comes into place. First off, let's see if the AJAX call succeeds. Put in console.log('foo'); statements, with different strings to trace what the JavaScript code does. If the AJAX call is being made, you should be able to see it in the debugger as well.
After that, you should be able to see the results going into the PHP script. You can dump the variables at the top var_dump($_POST);exit;.
There should also be some code where the $_POST variable is linked to $post_id and $my_id.
Since this isn't the complete code example, I can only help you this much. Please let us know if you managed to debug it. Else the complete code example would be nice for us to help you out some more.
use Console.log function to see which part of your code is executed and which is not

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?

I can't get a value from a PHP array...?

I'm writing a script to retrieve the scores from an osu! beatmap. The script uses the osu! API, which can be found here. I've obtained a valid API key, and got the info from the website. My project can be found here: failosu!.
This script is called by AJAX, and the variable s is passed via POST.
My problem is with the returned array.
In the following snippet (not really, it's pretty much my entire script), I make a request for the beatmap information first. In doing this, I am passing a variable, s (beatmap set ID), to the server, and trying to get the variable b (beatmap ID).
However, whenever I call $d1['beatmap_id'], it doesn't return anything to the main page. Instead, my AJAX script runs the error function rather than the success function. Does anyone know what my problem is?
if($_POST['id']) {
$s = $_POST['id'];
$k = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$u0 = "https://osu.ppy.sh/api/get_beatmaps?k=".$k."&s=".$s;
$d0 = json_decode(file_get_contents($u0));
$d1 = get_object_vars($d0[0]);
$b = $d1["beatmap_id"];
// THE CODE STOPS WORKING HERE FOR SOME REASON ????
$u = "https://osu.ppy.sh/api/get_scores?k=".$k."&b=".$b."&m=0";
echo $u;
$d = json_decode(file_get_contents($u));
for($i=0;$i<count($d);$i++) {
echo "<li>".$i." ".$d[$i]['username']."</li>";
}
}
Does anyone know what's wrong? Do you need me to tell you more information about my code?

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