jQuery AJAX - Set PHP Session variable - php

I am looking to store a variable across an entire session so that when a user closes a promotional bar it stays closed and doesn't pop back up every time they navigate to a new page.
On page load I have the following:
$.ajax
({
url: 'promo.php',
type: 'post',
data : formData,
success: function(result)
{
alert(result);
}
});
The formData isn't too important right now as it isn't used.*
promo.php:
<?php
if (isset($_SESSION['promoBar'])) {
echo $_SESSION['promoBar'];
}
else {
$_SESSION['promoBar'] = "closed";
echo "does not exist";
}
?>
The idea is that on page load it will check if the $_SESSION['promoBar'] variable exists, and if it does, return it's value. Otherwise set a value.
Currently the alert always displays does not exist. I was expecting it to display does not exist the first time and then closed each time I navigate to a new page.
What have I done wrong?

Try this...
Use "session_start" before check
session_start();
if (isset($_SESSION['promoBar'])) {
echo $_SESSION['promoBar'];
}
else {
$_SESSION['promoBar'] = "closed";
echo "does not exist";
}
?>

Related

Stop $_GET being processed after reload

I'm creating a link which appends a $_GET variable to the end of it for use of deleting files / other PHP tasks.
Delete file
Part of my PHP code looks for the variable and if it exists, it runs the unset function to remove the file, but when I reload the webpage, it obviously tries to remove the file again. Is there any way to remove the $_GET after it has been run once to stop the processing after a refresh?
<?php
if (isset($_GET['delete_file'])) {
if (file_exists($full_path.$_GET['delete_file'])) {
unlink($_GET['delete_file']);
} else {
echo "File ".$full_path.$_GET['delete_file']." doesn't exist";
}
}
?>
Delete file
You can use ajax to remove files so it won't refresh.
Delete file
<script>
function deletefile(filename){
var data = {delete_file:filename };
$.ajax({
url: 'delete.php',
type: 'post',
data: data,
success: function(response) {
// .. do something with response ..
// you can use window.location to refresh page
// or if you have js method to refresh page. you can call it here
}
});
}
</script>
In php file you can retrive with post
<?php
if (isset($_POST['delete_file'])) {
if (file_exists($full_path.$_POST['delete_file'])) {
unlink($_POST['delete_file']);
} else {
echo "File ".$full_path.$_POST['delete_file']." doesn't exist";
}
}
?>
But as the commenters say this is open to potential security issues. You need to take care of security if you use this approach in production.

Check db and then redirect using Ajax

So it's my first time handling or rather using ajax and it still rattles my mind. I made this ajax function so when everytime I push a button it checks the value of something on db and if it's true then it should redirect. It works fine or rather redirect when I refresh the webpage but that isn't what I was expecting, I was expecting that if the value on the db being checked is "EQUAL TO" or True then it should redirect without me having to refresh the page just so it can do it's stuff. Hoping for some insights, thanks!
My home.php has this:
<script src="js/ajax.js"></script>
My Ajax JS:
$.ajax
({
url: "testjax.php",
type: "post",
data: $('#Button').serialize(),
dataType:'json',
success: function (data)
{
if (data.status=='SUCCESS')
{
window.location="/anotherdirectory/";
}
else
{}
},
error: function (e) {
console.log('error:'+e);
}
});
Testjax PHP
<?php
session_start();
require_once('path/sql.php');
require_once('path/who.php');
$userID = Who::LoggedUserID(); //Found in who.php
$userData = Who::GetUserData($userID);
$userPoints = $userData['points'];
if ($userPoints==0.00)
{
$tent='SUCCESS';
}
else
{
$tent='ERROR';
}
$ary=array("status"=>$tent);
echo json_encode($ary);
?>

Running a PHP Script without redirecting or refreshing the page

I am very new to PHP and Javascript.
Now I am running a PHP Script by using but it redirect to another page.
the code is
<a name='update_status' target='_top'
href='updateRCstatus.php?rxdtime=".$time."&txid=".$txid."&balance=".$balance."&ref=".$ref."'>Update</a>
How do I execute this code without redirecting to another page and get a popup of success and fail alert message.
My script code is -
<?PHP
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
-------- SQL Query --------
?>
Thanks in advance.
You will need to use AJAX to do this. Here is a simple example:
HTML
Just a simple link, like you have in the question. However I'm going to modify the structure a bit to keep it a bit cleaner:
<a id='update_status' href='updateRCstatus.php' data-rxdtime='$time' data-txid='$txid' data-balance='$balance' data-ref='$ref'>Update</a>
I'm assuming here that this code is a double-quoted string with interpolated variables.
JavaScript
Since you tagged jQuery... I'll use jQuery :)
The browser will listen for a click event on the link and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.
As you can see, I'm using .data() to get the GET parameters.
$(document).ready(function() {
$('#update_status').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
rxdtime: $(this).data('rxdtime'),
txid: $(this).data('txid'),
balance: $(this).data('balance'),
ref: $(this).data('ref')
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});
PHP
Looks like you know what you're doing here. The important thing is to output the appropriate data type.
<?php
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
header('Content-Type: text/plain; charset=utf-8');
// -------- SQL Query -------
// your logic here will vary
try {
// ...
echo 'success';
} catch(PDOException $e) {
echo $e->getMessage();
}
Instead of <a href>, use ajax to pass the values to your php and get the result back-
$.post('updateRCstatus/test.html', { 'rxdtime': <?php ecdho $time ?>, OTHER_PARAMS },
function(data) {
alert(data);
});

returning php session to ajax

I am having trouble getting jQuery ajax to recognise a session. I am creating a php session from a login script, but what is happening is that when ajax loads the authenticated page, the session is always unset. For example, in the secure page, if I refresh the page, the session id changes each time. I have session_start(); in each page. Can someone please show me the correct way to handle sessions with ajax and php? I have spent 2 days and have used google so much, I will probably get an invite to there xmas lunch :-) I have included the relevant code and would be grateful for any help. Thanks
PS. If it makes any difference, I am trying to develop mobile app using jquery mobile.
login html js
$(function() {
$("#kt_login1").click(function() {
var user = $('#user').val();
var pass = $('#pass').val();
if (user == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=user]').addClass("label")
return false;
}
else if (pass == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=pass]').addClass("label")
return false;
}
else $('label[for=user]').removeClass("label");
$('label[for=pass]').removeClass("label");
//alert(user + pass + ok);
data = 'user=' + user + '&pass=' + pass;
$.ajax({
type: "POST",
url: "testajax.php",
cache: false,
data: data,
success: function(data) {
if (data == 'authenticated') {
//alert(user);
document.location = 'secure.php';
}
else $('#login_message').html('You are not authorised');
//$(ok).val('Logged In');
//$("#login").get(0).reset();
//$("#form").dialog('close');
},
error: function(xhr, ajaxOptions, thrownError) {
jAlert('There was an exception thrown somewhere');
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
});
testajax.php
<?php
// test wether the user session is already set
$username = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string(md5($_POST['pass']));
mysql_connect('localhost', 'root', '');
mysql_select_db('sample');
//now validating the username and password
$sql="SELECT * FROM user_usr WHERE username_usr='$username' and password_usr='$pass'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0) {
session_start();
$_SESSION['u_name']=$row['name_usr'];
/*
echo '<pre>';
print_r( $_SESSION['u_name'] );
print_r( $_REQUEST );
echo '</pre>';
exit;
*/
echo 'authenticated';
}
else
{
echo 'Unknown User';
}
?>
+++++SOLUTION+++++
Changed form input from submit to button and voila. All ok
you have to call session_start() each time working with a session (not only when creating it)
see: http://php.net/manual/en/function.session-start.php
There are a whole load of reasons this might be the case - but you're code is upside down! This may well be the cause (or a contributory factor).
You should not treat the existence of a session as evidence of authentication (the contents of the session is another thing altogether). Call session_start() at the top of your script - not conditionally, half-way through.
As to why your session data is not available...that's an FAQ here - have a look at some of the previous answers for potential causes / how to investigate.

Is there a way to check if a user is logged in using JQuery?

I want to be able to display a message if a user is not logged in if they try rating a user by clicking a rating. Is there a way to add it to my JQuery code below or can I pass it to my PHP script?
I'm using PHP
Here is the JQuery code.
$('#rate li a').click(function(){
$.ajax({
type: "GET",
url: "http://localhost/update.php",
data: "rating="+$(this).text()+"&do=rate",
cache: false,
async: false,
success: function(result) {
// remove #ratelinks element to prevent another rate
$("#rate").remove();
// get rating after click
getRating();
getRatingAvg();
getRatingText2();
getRatingText();
},
error: function(result) {
alert("some error occured, please try again later");
}
});
just check it if one is login in your update.php script. If not login, echo something like "error".
then in your success handler,
success: function(result) {
if (!$.trim(result)==='error') {
// remove #ratelinks element to prevent another rate
$("#rate").remove();
// get rating after click
getRating();
getRatingAvg();
getRatingText2();
getRatingText();
} else {
// not login, do something...
alert('login first please...');
}
},
Send something back to jQuery as the result and check it, before you perform your other steps.
jQuery alone cannot test reliably if the user is logged in, but your request to PHP could send an answer if theuser was logged in or not. This answer can be checked and then display an error (or not).
Use your update.php script to send back a codified response that includes an acknowledgement of whether the user is logged in; I am assuming the script echoes some value which is then received as the result variable in your jquery snippet.
if(result.loggedin == "1"){ //Assuming your output is a JSON object
}else{
}
In Wordpress you can easily check with below code:
if(jQuery('body').hasClass('logged-in')) {
// add your jquery code
}

Categories