Setting PHP Session variables with jQuery Ajax - javascript

I have a pretty simple issue which I just can't seem to resolve. I have the following ajax request which sets a PHP Session variable
$.post("http://mytestdomain.com/test.php", {"data": 'success'});
And this code in the PHP file to generate and echo the Session variables
session_start();
$_SESSION['test_text']= $_POST['data'];
echo "Pageviews=". $_SESSION['test_text'];
However this keeps returning the following error message
Notice: Undefined index: data in /var/www/test.php on line 2
If I post a demo URL into my browser like this
http://mytestdomain.com/test.php?data=11111
Then the results are echoed correctly.
So my question is, how do I pass via jQuery Ajax data to a PHP session variable and have it saved?
Thanks

In your test.php file, try the following:
session_start();
$_SESSION['test_text']= $_REQUEST['data'];
echo "Pageviews=". $_SESSION['test_text'];

Related

Passing php session variables to html page containing jquery

I am trying to pass a session variable to an html page as following :
$_SESSION['login_user'] = $myusername;
header("location: main.html");
in main.html I have codes like this :
<?php
session_start();
$user_id = $_SESSION['login_user'];
?>
and
$(document).ready(function(){
alert('<?php echo $user_id; ?>');
})
I expect to see an alert showing the user name - which is not happening. Any help about where it goes wrong?
Thanks
I think you are messing up PHP and HTML.
You can only run PHP from *.php files. *.html files won't parse PHP (unless defined in your web server config). To make this work, rename main.html to main.php.
Also make sure that session_start() is on above every file that is using sessions.

Cannot use echo after connection to database

I'm using ajax to send a request to php with some text.
$.get("process.php", { finalQuery : finalQuery }, function(data) {
alert("Data Loaded: " + data);
});
I know this works because in php I can put
$val = $_GET['finalQuery']; echo $val;
And it outputs the correct data.
However, if I put
$db = pg_Connect("host=localhost port=5432 dbname=Blah user=postgres password=1888");
pg_close($db);
It stops echoing the results back to javascript. If I use a different port or name, and it doesn't connect, it then goes back to sending the data to javascript and outputting the correct data.
So basically, when I connect to the database, I cannot communicate my results back with echo. What am I doing wrong?
EDIT(update):
Here's the complete php code
<?php
$val = $_GET['finalQuery'];
echo $val;
$db = pg_Connect("host=localhost port=5432 dbname=Blah user=postgres password=1888");
$result = pg_query($db, 'SELECT gid FROM "Perfect"');
while ($row = pg_fetch_row($result)) {
echo "gid: $row[0]";
echo "<br />\n";
}
pg_close($db);
?>
However, the problem still occurs as long as I use pg_connect. All the other lines can be removed and the problem persists. As long as I remove the pg_connect, the problem disappears and I can send the information back through echo
NEW EDIT(debugging) :
The connection to the database and the php code seems ok. After loading the php page with
error_reporting(-1);
ini_set('display_errors', 'On');
no errors are logged on the page, and the connection to the database is returning all the data properly on every page load.
The problem arises when I'm trying to connect to the php through javascript.
The page loads the data properly sometimes, but it's random, and most of the time nothing happens (not even php logged errors). If you there's no way the javascript-php connection isn't the problem then I'll keep debugging the code.
Here's the steps I'd take for debug:
Begin by ensuring the DB is running and that you can send it a query
successfully via console window DB GUI Tool (Navicat is my gui of
choice for DB's)
Load the PHP page directly. Check for output of
expected code or fatal PHP Errors
Check the browser console for errors. Since it appears to be a PHP
only page, this should be entirely clear of problems.
Check PHP logs
Check Postgres logs
More than likely, something between Postgres and PHP is the problem. Post any errors back on your question if you're still stuck after finding a clue.

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?

php post not working using header and ajax

i am sending a post request using jquery $.post to another domain. every thing works fine but i am not getting the posted data in the requested page please check my code
jquery code
var data = {mydata: 'testing'};
$.post("http://anyurl/file.php",data,function(info){
alert(info);
});
and here is php code
<?php
header('Access-Control-Allow-Origin: *'); // this is to allow another domain
$data = $_POST[“mydata”]; // assigning data to variable
echo $data; // sending back to jquery
?>
it does not return the data please check anyone.
Thanks in advance
Use proper quotes and use isset() to check the data set or not like,
<?php
header('Access-Control-Allow-Origin: *'); // this is to allow another domain
print_r($_POST);// to check the post data
$data = isset($_POST['mydata']) ? $_POST['mydata'] : "No Data";
echo $data; // sending back to jquery
?>
Try to get the POST variable with single quotes and better to put exit after echoing it like
$data = $_POST['mydata'];
echo $data;
exit;
And make sure that it is posting to the given URL or not through console.
OK,It walk well when I test it.In order to reappear the error you've got,I'm trying to set the file.php into a BOM-UTF8 file and it got error in the end.So,please check your file.php if it got a BOM before header().
Another suggess,you can use firebug to test your ajax post process.The link in the console will show you the ajax process,such as what you've post and what is feedback.Just use console.log() instead of alert().

$jquery.post() PHP and Mysql

So I half got jQuery's ajax ($.post) to work. But, for some reason, I haven't been successful with finding the right online article to explain to me how PHP retrieves the ajax data that is sent. I've found some stuff on json_decode, but upon me doing that to basically decode it, it wont work (and yes, I am using json for the $.post command).
Here is my javascript code
$.post("notificationNum.php", {"user":"1"},
function(data){
$(".example-number").html(data.amount);
}, "json");
Here is my PHP code
<?php
session_start();
//link to db info here
$user_id_got = json_decode($_REQUEST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>
Mind you all, I've also tried using the $_POST command instead of the $_REQUEST. Any ideas how to send data to the PHP file so I can use it?
"json" in your jQuery call is how your php should write its output, not how jQuery sends it. Use normal $_REQUEST in your php:
$user_id_got = $_REQUEST['user'];
try this
notificationNum.php
<?php
//link to db info here
$user_id_got = intval($_POST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>

Categories