Get a PHP $_SESSION variable from Jquery? - php

I'm not yet a JSON/AJAX master so I don't know how to do this.
I need a $_SESSION['name'] PHP variable to work with in my jQuery stuff and I don't know how to access it... consider:
// the 'who is typing' shindig
$.ajax(
{
url: "whos_typing.html",
cache: false,
success: function(whos)
{
// here I need to access $_SESSION['name'] and do stuff with it
$("#soandso").html(whos); //Insert who's typing into the #soandso
}
});

You'll need to inject it, something like this:
var sessName = '<?php echo $_SESSION['name']?>';
The file containing this script must be executed by the php interpreter (i.e. a .php file)
EDIT: Conceding to Radu's point, it would be safer execute for unsanitized data:
var sessName = <?php echo json_encode($_SESSION['name']) ?>;

You need to use $.post to retrieve the variable from the server. You would have something like this:
$.post('echoMyVar.php', {post: 1}, function(data){
myVar = data['myVar'];
});
This is very basic, you first need to check if data is not null. In echoMyVar.php, you need just need basically the following:
header('Content: application/json', 1);
$returnVal = array('myVar', $_SESSION['myVar']);
echo json_encode($returnVal);
Again this is a shell, not secure, and would not handle any errors.

var name= "<?php echo $_SESSION['user_name'];?>"
will do it . . .
Remember php is a server side script, . . .so it takes precedence and get executed first and spits html to the client (Jquery , javacript) which will be executed in your browser . . . .
So, you can use server side variables to share with client . . . but not the other way around . . .

The easiest way is probably to include your javascript code in a .php file. Then you can simply do:
var phpVar = <?php echo $_SESSION['name']; ?>
SIMILAR POST

Server side in whos_typing.php:
<?php
//...
header('Content-Type: application/json');
echo json_encode(array(
'who'=>'Bob',
'session'=>$_SESSION,
// Be sure that you're not storing any sensitive data in $_SESSION.
// Better is to create an array with the data you need on client side:
// 'session'=>array('user_id'=>$_SESSION['user_id'], /*etc.*/),
));
exit(0);
Client side:
// the 'who is typing' shindig
$.ajax({
url: "whos_typing.php",
dataType: 'json',
cache: false,
success: function(data) {
var session = data.session,
who = data.who;
console.log(session.user_id); // deal with session
$("#soandso").html(who); //Insert who's typing into the #soandso
}
});

You need to echo the session variable from PHP when you send it to the browser. I'm assuming whos_typing.html is just the URL to a PHP script.

Related

ajax send data to "test.php", and then open "test.php" directly to show the result

I want to send an array from javascript to php via ajax function.
And I don't want show the result as callback, but immediately open the target php file and show the images.
I mean, I want open the php file directly on the server side.
I think this is quite simple, but I just have no idea.
My javascript looks like:
var stringArray = new Array("/images/1.jpg", "/images/2.jpg", "/images/3.jpg");
$.ajax({
url: 'test.php',
data: {stringArray:stringArray},
success: function() {
window.open('test.php'); // It opens test.php in a window but shows nothing!
},
});
the test.php file:
$stringArray = $_GET['stringArray'];
foreach($stringArray as $value) {
echo "<img src=" . $value . "></img>";
}
Thanks for any help!
Likely the window.open command is being called without the POST data needed.
Now, I don't know what you want to do here but, why send an Ajax request when you don't really want to make use of it?.
Edit: just to make it a bit clearer, you seem to be calling the php file with no data trough POST. There is no clean way of opening a window in JS with POST data, just try GET for no critical information. Let is know how it goes.
As I can see, You are sending data by post method and accessing in test.php
but when u open file via window.location it doesn't get POST data hence no data get populated
You can achieve it via $_SESSION.
in test.php
session_start();
if(!empty($_POST['stringArray'])) {
$_SESSION['stringArray'] = $_POST['stringArray'];
}
$stringArray = (isset($_SESSION['stringArray']) && $_SESSION['stringArray'] != '') ? $_SESSION['stringArray'] : $_POST['stringArray'];
foreach($stringArray as $value) {
echo "<h3>" . $value . "</h3>";
}
Hope this will work for you...
you should write
var stringArray = new Array("apple", "banana", "orange");
$.ajax({
type: 'post',
url: 'test.php',
data: {stringArray:stringArray},
success: function(message) {
window.open(message); // It will open a window with contents.
},
});
I doesn't show the output because when you open the page on the callback you are not sending anything through to the test page through the post variable. Why you would want to do this I don't know. Send the information through the url, get.

How to send data between ajax and php in secure way?

I have index.php, ajax.js and process.php (where I get my AJAX data).
I am using AJAX this way:
var = $('user_id').val();
$.ajax({
url : "somefile.php",
method : "GET",
data : {'user_id' : user_id},
cache : false,
success : function(data) {
// do something with "data"
}
);
User_id I receive from PHP file:
<input value="<?php echo $user_id; ?>" id="user_id" />
What do I need to do for increasing security?
Following can be added, just for increasing security measures,
In PHP code
<input value="<?php echo base64_encode($user_id); ?>" id="user_id" />
In JS Code:
var = $('user_id').val();
$.ajax({
url : "somefile.php",
method : "POST",
data : {'user_id' : user_id},
cache : false,
success : function(data) {
// do something with "data"
}
);
In "somefile.php"
for getting the file use the $_POST method, if will only accept the variable posted by using POST method. This can be used:
if(isset($_POST['user_id']))
{
$user_id=$_POST['user_id']
$user_id=base64_decode($user_id);
//all functionality here
}
else
{
//shoot error message
}
I'd recommend you don't provide the userid to the client. Can you store it in a session variable instead?
If this user_id is being used to retrieve some confidential information related to the logged in user then that sounds like a security flaw.
You should be getting the user_id from a session variable
I think is not an good idea to put 'user_id' in client HTML and send back to server. You need to do more validation with data that sent from client (do some checking and filtering).
I recommend to use session instead of sending it to client, But you will have problem if editing two or more data at same time (multi tab), So you need to use session and some trick.
With this example your real user_id will never sent to the client.
index.php:
session_start();
$edit_session_id = md5(uniqid() . microtime(true));
$_SESSION['edit_' . $edit_session_id] = $user_id;
ajax.js:
var edit_session_id = $('#edit_session_id').val();
$.ajax({
url : "process.php",
method : "POST",
data : {'edit_session_id' : edit_session_id},
cache : false,
success : function(data) {
// do code
}
);
process.php:
session_start();
$edit_session_id = $_POST['edit_session_id'];
if(!isset($_SESSION['edit_' . $edit_session_id]))
{
die('Invalid edit session, please go back & refresh');
}
$user_id = $_SESSION['edit_' . $edit_session_id];
// Do something with user_id
//Clear the editing session
unset($_SESSION['edit_' . $edit_session_id]);
You should use POST instead of GET and you should also use ssl so that yuor urls sart with https instead of http.Now you are secured enough but you can increase security by adding extra encryption layer.

JQUERY - .html() can also view php

The following script sends data with ajax for login
I want to format the data returned by using, in essence, a session variable ($ _SESSION)
I can do it
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "inc/login.inc.php",
data: "username="+username+"&password="+password,
success: function(msg){
if(msg!='false')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<\?php print(\"$_SESSION['name'].\" <a href='inc\/logout.inc.php' id='logout'>Logout k2<\/a>\");\?>");
//valori menĂ¹
if(tipo=='1')
{$("#admin").css('display','none')}
}
else
{
$("#add_err").html("Username o password errata");
}
},
beforeSend:function()
{
$("#add_err").html("<img hspace='84' src='img/loading.gif' alt='Loading...' width='32' height='32'>" )
}
});
return false;
});
especially this is possible, in this way would print the name of the user just logged. otherwise I would not know how to do
$("#profile").html("<\?php print(\"$_SESSION['name'].\" <a href='inc\/logout.inc.php' id='logout'>Logout k2<\/a>\");\?>");
You can't insert PHP code after the script has already been processed.
Either pull it in via ajax, or include the actual PHP output into your javascript.
ie, in page.php
<script>
var sessionName = '<?php echo $_SESSION['name']; ?>';
</script>
then when you need it later
$("#profile").html(sessionName + " Logout k2");
JavaScript is client-side, it simply can't execute your php code.
You have to return something (eg. the username) in the php file you use in your ajax request and use that in your JS.
See the jQuery ajax docs for examples.
You'll need to serve the php code:
$("#profile").load("inc/login-header.inc.php");
login-header.inc.php
<?php
print($_SESSION['name'] . " <a href='inc/logout.inc.php' id='logout'>Logout k2</a>");
?>
The easiest way to send information back from the php script to the javascript, is by using the msg variable in
success: function(msg){
If you just want to send back one string, you just echo that one string in your php file and you will have its value in msg. If there are multiple variables you want to send back, you can package the result in a json object.
So assuming that everything you want to send back is contained in the php array named $output, you do a echo json_encode($output); at the end of your php script to get the whole thing in msg.
that won't work, as the PHP code is never processed.
In login.inc.php try something like this
<?php
if (!loginOK()){
echo "{login:false}";
} else {
echo "{login:true, name:'".$_SESSION['name']."'}";
}
and then on the client
success: function(msg){
if (msg.login){
// stuff
} else {
$("#profile").html(msg.name + $('<a>').attr('href', 'logout.php').html('logout'));
}
}

update .text() using ajax auto refresh

When I set the session in a file called signin.php:
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'array.php',
type: 'post',
data: {'user': $user}
});
";
In another file (index.php), I want to get:
<?php
session_start();
echo "log in as <span id=\"user\"></span><br/>";
$user = $_POST['user']
echo "
<script>
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
</script>
";
?>
I know I completely messed up with the code. What I want is that when the session is set in the signin.php file, I want $user in the content in "log in as $user" automatically updated without refresh the page, any help will be greatly appreciated!
First, work on diligently formatting your code more effectively. That code you posted was all over the place. This is a bad practice to get in and leads to errors, bugs, and other effects which can be difficult find due to the formatting.
If I follow what you're doing, when someone logs in and then hits the index.php page, you want to be able to load a user's information from another file that will give back the user data asynchronously?
signin.php
Your code is confusing in what it appears to be doing; you simply have not told us enough both in code and explanation to understand what the workflow entails.
For instance, in signin.php, you're echoing a <script> tag that does an $.ajax() request, but who/what get's this code? Is this part of the signin.php content, if the user successfully logs in? Does this mean the signin.php will load the page to use the $.ajax() here, or is that meant to run from the $.ajax() on success?
If it's the latter, you need to return regular Javascript with no markup (like a <script> tag wrapped around it) and use dataType: 'script' in the options.
Also, I would at least use a more descriptive word than array.php; if you're getting user data from it, name that file something like userdata.php.
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
dataType: 'script',
data: 'json=' + jQuery.serialize({user: '$user'})
});
";
Then in userdata.php, you can access it with $_POST['json'].
index.php
This honestly makes no sense:
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
);
Why is the setInterval() in an anonymous function that's run while setting $.text()? This is one of those What? moments, where I'm not even sure what you're trying to accomplish.
Before that though, you have:
$user = $_POST['user'] <<< Note here, you need a ; at the end
Why is this a $_POST? Does the signin.php use $_POST to log a user in? Here, I believe you want $_SESSION (I think, hope, ??), since that's where you stored the username when the user logged in using signin.php.
This is my best guess as to what you're trying to do (assuming you're returning JSON-formatted data):
<?php
session_start();
$user = $_SESSION['user'];
echo "log in as <span id=\"user\"></span><br/>";
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
data: 'json=' + jQuery.serialize({user:'$user'}),
dataType: 'json',
success: function(data){
$('#user').text(data.fullname);
}
});
</script>
";
?>
Try the following:
<?php
$user = 'john';
$_SESSION['user'] = $user;
?>
<script type="text/javascript">
$.ajax({
url: 'array.php',
type: 'post',
data: { 'user': <? echo json_encode($user) ?> }
});
</script>

arrays in $.ajax jquery and then sends it to a php page

jQuery(document).ready(function(){
// Set the data text
var dataText = "
{
name: 'John',
time: '2pm'
}";
alert(dataText);
// Create the AJAX request
$.ajax({
type: "POST", // Using the POST method
url: "/ajax/analytics/push", // The file to call
data: dataText, // Our data to pass
success: function() { // What to do on success
alert("Data Loaded: " + dataText);
}
});
});
</script>
hello im still learning ajax. how can we push a array of $_POST?
1.im trying to do something like
var dataText['name'] = 'Jhon';
var dataText['time] = '2pm';
then somehow turns it into
$_POST['name'] = 'Jhon';
$_POST['time'] = '2pm';
then send it to the url..
2.is there a way to debug this ? what im doing now is im writing
# somehow doesnt work becouse its not auto refresh when the ajax sends a post
var_dump($_POST);
# ok heres how i debug it right now.
ob_start();
// write content
$content = $_POST;
ob_end_clean();
file_put_contents('CACHE',$content);
in to a file, i hope there is a better solution for this..
Thankyou for looking in.
Adam Ramadhan
I'm not entirely sure what you're doing. You seem to be building JSON manually (and not doing it correctly) and then passing that (in the JSON-serialised string form) to your file. You then seem to expect it to be parsed by PHP automatically.
It would be better to send it as key-value pairs. You can let jQuery do this for you if you pass in an object. This won't look much different to your existing code:
var dataText =
{
name: 'John',
time: '2pm'
};
Note that I have removed the double quotes. This is primarily because it is illegal to have a JS string covering more than one line without escaping the line breaks. It is also because you want the object to pass into your $.ajax call.
These should be available as $_POST['name'] and $_POST['time'] now.
file_put_contents('CACHE',serialize($content));
or
foreach($_POST as $k => $v) $content .= $k .'='.$v;
jQuery(document).ready(function(){
// Set the data text
var dataText =
{
name: 'John',
time: '2pm'
};
alert(dataText);
// Create the AJAX request
$.ajax({
type: "POST", // Using the POST method
url: "/ajax/analytics/push", // The file to call
data: dataText, // Our data to pass
success: function() { // What to do on success
alert("Data Loaded: " + dataText);
}
});
});
# ok heres how i debug it right now.
ob_start();
# somehow doesnt work becouse its not auto refresh when the ajax sends a post
var_dump($_POST);
$content = ob_get_contents();
ob_end_clean();
file_put_contents('CACHE',$content);

Categories