Pass vars from php to js without ajax - php

Lets say I have a php page... I want the javascript in that page to access some user information variables (after logged in), such as userid, email, etc. If I use ajax, then it will take an extra half second, because the page has to load, then wait for ajax to go get those variables, so I'd rather embed it in the page, but that seems questionable as far as security to embed an email in the source.
Here are my options can you think of a better way?
1 - Embed the data into the php on the first request
<html>
<script>
user_email='<?php echo $user_email; ?>';
</script>
2 - Have data load separately from a js/php file so its not in original page source
<html>
<script src="userdata.js.php"></script>
--- userdata.js.php ---
user_email='<?php echo $user_email; ?>';
3 - Request data via ajax after page loads (would be slower)
<html>
<script>
$(function(){
$.post('getuserdata.php',[],function(result){
userdata=result;
});
});
</script>

Another option that you might consider is using JSONP to asynchronously call a function once the AJAX loads.
HTML
<script type="text/javascript">
function handle_response(response)
{
// do whatever you want with the response
// you get a json object here that looks like
// { id: 1, username: 'jimmy' }
}
</script>
<script type="text/javascript src="/path/to/ajax/script.php"></script>
script.php
<?php
$arr = array('id' => 1, 'username' => 'jimmy');
$param = json_encode($arr);
header("Content-type: text/javascript");
echo "handle_response({$param})";
exit;
So now, once that valid javascript from script.php finishes loading it immediately calls your function that you defined client-side. This keeps your information out of the initial HTML source and you could even put that script behind an https without doing that for the rest of the site.

I always use the first step
var myvar = <?php echo $myvar; ?>;

People are rather accustomed with ajax nowadays and a circle saying loading, is not that uncommon. On the other hand if you can embed the data that's just as good. Making a separate file is even better. You should be careful what kind of info you give out though, you could use SSL to make it more secure.
All three are viable... depends on who you're trying to protect the data from. The user that called the page will have access to the information one way or another... so go for the more reliable implementation.

I don't like embedding information in the page for security reasons. At some point in time it is just going to be too easy to store something that shouldn't be there. You have two decent options that occur off the top of my head:
Perform the ajax call during the page load (body onload=ajax call) (more secure)
Store them in the cookie for the site (less secure)
I typically use option #1.

seems questionable as far as security to embed an email in the source.
Retrieving the email via ajax vs embedding it directly in the source suffer from the same security problem: someone sniffing traffic could get the email. To avoid this you would need to either
Figure out a way to not send the email to the client in the first place.
Only send the email address to the client over https
I imagine lots of websites just punt on this issue and send the email to the client unencrypted.

Related

javascript to php and viceversa communicate

I am trying to write a plug-in for firefox which would fetch all the domains from the links of the current site and display their IP addresses.
for that I have written js code containing "domians". And simple php script:
<?php
$ip = gethostbyname('www.example.com');
echo $ip;
?>
now i have to pass this "domains" array to php and return the ip values to js code in order to display the domains with ip(s).how can i do this?
I heard that ajax, json can do this. Is there is any other possible solution?
From what I understand, PHP is executed server side. This means that when the user load the plug-in/page/content, the PHP is executed and done with. This being said, JavaScript is executed Client side, meaning it can be executed during the page load, before the page load and after the page load. Unfortunately this means that you cannot pass JavaScript variables to PHP without using AJAX or going to another page.
The way you would pass information from JS to PHP would be by receiving the data you need, then making an Ajax request to a PHP script that would perform some action and then return some value. If that's what you want to do, then there are tutorials/many questions that will help you in doing that.
To pass from PHP to JS, you can do something like:
<script>
var JavascriptVariable = <?php echo $PHPVariable ?>;
</script>
But this might be bad practice, I am unsure.

PHP GET variable in same document

how can i pass a variable from javascript to php using same file
in this example page keeps refreshing and i don't get to see the result
it works only if i separate the scripts... but i need it somehow like on ajax..
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
and this is the seccond part of the script ( they are both in same file )
<?php
Id = $_GET[Result];
echo $dbId;
?>
As Brian said you should put it in a conditional statement.. also your PHP is bad. Try the following
<?php if(isset($_GET["Result"])) : ?>
// do work with set variable
<?php $dbID = $_GET["Result"];
echo($dbID); ?>
<?php else : ?>
// "Result" not set
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
<? endif; ?>
I think this is a good exercise if you're trying to learn the Ajax method, in the real world I recommend using a framework like jQuery. Of course understanding how this works will help you build better applications in the end.
So you could do something like this in the PHP script:
if (!isset($_GET['Result']))
{
// include the javascript portion with the redirect
}
I'm with the others, though--I'm not seeing the value in a page load followed by an immediate redirect to the same page.
What you are trying to do cannot be done. Your script runs on the client in real time but the php will run on the server during the request. You will need to make an AJAX request.
First you will want to use Firefox with firebug and the web developer toolbar. Firebug gives a great view of ajax traffic and the web developer toolbar helps you see what's going on in the page.
Use jQuery make an ajax request to "send" the value to another php file. Don't be afraid to separate out files, in fact it's encouraged and considered good programming. If you find your sending a lot if information to a php script you will want to use JSON instead of as part of the url.
Man, you should follow a client-server pattern.. So the Client page can use some ajax to make a request to a Server page. This will response to the Client and you can make with the data what you want.
of course it will keep refreshing:)) Because as soon as the browser gets the js code, it will load that page you specify, which will send your browser the same page... you get the idea. It's like writing for(;;){}
Your question is difficult to understand (for me at least.) My guess is that you are wanting to use AJAX to send data to the server and receive a response without leaving the page.
Probably the easiest way to accomplish this is to use a library such as jQuery. (see jQuery.ajax())
PHP only runs on the server and the javascript only runs on the client. By the time your client is running the javascript, no more PHP can be executed on that request.

Set Session variable using javascript in PHP

Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

Using Ajax to Send Data Back to the Server

I understand there is a method send for xmlHttpRequest objects, but I've been working on this site all day and I'm unable to find any halfway decent tutorials on the subject and my brain feels like mush. Ajax is hard.
What I'm trying to do is send data from one Javascript file back to a PHP script on the server, where the data is simply a string and a small number. Is this possible? Why can't I find a good article on the subject?
tl;dr How do I use the send method to pass a string and a number from a javascript file to a php file?
Why don't you user jQuery or similar library?
Sending a variables with jQuery will be simple as that:
$.post("save.php", { name: "John", time: "2pm" } );
In your save.php file you can handle POST variables as you wish:
$name = $_POST["name"];
$time = $_POST["time"];
You can check it out: http://jquery.com/
I think you are wasting your time trying to make self made methods ...
It's definitely possible. This is a really nicely organized tutorial that walks you through the XmlHttpRequest object, how to set it up, and how to consume it on the server.
The server-side code is PHP, and I'm more of a C# guy, and it made total sense to me. (Maybe I should switch to PHP??).
I hope this helps! Good luck.
EDIT: In response to a previous SO question, I put this jsfiddle together to demo how to use XmlHttpRequest. Hope this also helps.
lots of good links here, so I'm not going to add to that. Just as a sidenote, you're dealing with a light case of ajaxness here :) - typically you'd want to send something back from the server that changes the state of the page in response to what was sent from the page in the first place (in fact one might argue why you need ajax in the first place and not simply post, if the page's not supposed to change - but I can see how there might be situations where you'd want ajax anyway). I'm just saying that because you're going to encounter a lot of content about how to deal with the stuff sent back from the server - just making sure you're aware that's not needed for what you're trying to do (I'm always glad when I know what I can leave out in the first pass ;)
step 1:
get jquery. all you have to do is download the latest file and include it on your page.
step 2:
make 2 files:
somepage.html:
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$.get("someScript.php",
// data to send if you want
{
'someVar' : 'someValue'
},
// receive and do something with response
function(response){
alert(response);
} // function (response)
); // .get()
</script>
someScript.php
<?php
echo $_GET['someVar'] . " response!";
?>
step 3:
upload all your files to your server and go to somepage.html
That's all there is to it. Though, you would generally put that code inside some kind of onclick or whatever, depending on what you want to use ajax for. But the comments in there are pretty self explanatory. jquery is used to make the ajax request, with an example of sending data to the server-side script receiving the request (using GET method). You would do whatever in someScript.php but in this example, it simply echoes back the value you sent. Then jquery takes what someScript.php echoes out and just throws it in a popup.
Using jQuery, you can use the post method:
$.post("test.php", { name: "John", number: 2 } );
Behind the scenes, this uses xmlHttpRequest, have a look at the source to see how they do it.

Setting a PHP $_SESSION['var'] using jQuery

I need to set a PHP $_SESSION variable using the jQuery. IF the user clicks on an image I want to save a piece of information associated with that image as a session variable in php.
I think I can do this by calling a php page or function and appending that piece of info to the query string.
Any ideas. I have found little help through google.
thanks
mike
You can't do it through jQuery alone; you'll need a combination of Ajax (which you can do with jQuery) and a PHP back-end. A very simple version might look like this:
HTML:
<img class="foo" src="img.jpg" />
<img class="foo" src="img2.jpg" />
<img class="foo" src="img3.jpg" />
Javascript:
$("img.foo").onclick(function()
{
// Get the src of the image
var src = $(this).attr("src");
// Send Ajax request to backend.php, with src set as "img" in the POST data
$.post("/backend.php", {"img": src});
});
PHP (backend.php):
<?php
// do any authentication first, then add POST variable to session
$_SESSION['imgsrc'] = $_POST['img'];
?>
Might want to try putting the PHP function on another PHP page, and use an AJAX call to set the variable.
Whats you are looking for is jQuery Ajax. And then just setup a php page to process the request.
A lot of responses on here are addressing the how but not the why.
PHP $_SESSION key/value pairs are stored on the server. This differs from a cookie, which is stored on the browser. This is why you are able to access values in a cookie from both PHP and JavaScript.
To make matters worse, AJAX requests from the browser do not include any of the cookies you have set for the website. So, you will have to make JavaScript pull the Session ID cookie and include it in every AJAX request for the server to be able to make heads or tails of it. On the bright side, PHP Sessions are designed to fail-over to a HTTP GET or POST variable if cookies are not sent along with the HTTP headers.
I would look into some of the principles of RESTful web applications and use of of the design patterns that are common with those kinds of applications instead of trying to mangle with the session handler.
I also designed a "php session value setter" solution by myself (similar to Luke Dennis' solution. No big deal here), but after setting my session value, my needs were "jumping onto another .php file". Ok, I did it, inside my jquery code... But something didn't quite work...
My problem was kind of easy:
-After you "$.post" your values onto the small .php file, you should wait for some "success/failure" return value, and ONLY AFTER READING THIS SUCCESS VALUE, perform the jump. If you just immediately jump onto the next big .php file, your session value might have not become set onto the php sessions runtime engine, and will you probably read "empty" when doing $_SESSION["my_var"]; from the destination .php file.
In my case, to correct that situation, I changed my jQuery $.post code this way:
$.post('set_session_value.php', { key: 'keyname', value: 'myvalue'}, function(ret){
if(ret==0){
window.alert("success!");
location.replace("next_page.php");
}
else{
window.alert("error!");
}
});
Of course, your "set_session_value.php" file, should return 'echo "0"; ' or 'echo "1"; ' (or whatever success values you might need).
Greetings.
in (backend.php) be sure to include include
session_start();
-Taylor
http://www.hawkessolutions.com
Similar to Luke's answer, but with GET.
Place this php-code in a php-page, ex. getpage.php:
<?php
$_SESSION['size'] = $_GET['size'];
?>
Then call it with a jQuery script like this:
$.get( "/getpage.php?size=1");
Agree with Federico. In some cases you may run into problems using POST, although not sure if it can be browser related.
It works on firefox, if you change onClick() to click() in javascript part.
$("img.foo").click(function()
{
// Get the src of the image
var src = $(this).attr("src");
// Send Ajax request to backend.php, with src set as "img" in the POST data
$.post("/backend.php", {"img": src});
});

Categories