I'm trying to do something that goes far over my current skills yet I believe I can do it, I would be imensely thankfull if you point me to an already developed script for this matter.
My question comes from what runs first? Javascript or php? because I need to asynchronosly include a php file into the page.
My idea is this, if user has a screen width wider then 1024, draw an extra fixed position div, if not, don't draw it. That div is supposed to take in a flash object with a clickable link.
My idea would be to:
Get resolution with javascript.
Use jQuery to send ajax json var into .php file that stores res vars into a session cookie.
Read the cookie with php, decide to include the extra .php file or not. That file should then eco the extra div with flash object.
Is this possible? Is there an easier way? Since this is to include in a Zencart personal store of mine, does it conflicts with the zencart cookie session or can a user have more then 1 type of session cookie per website? it can right?
Best Regards, any help appreciated,
Joricam
Yes, it's possible - but now in the way you're describing. PHP runs server side and Javascript runs client side, i.e. PHP is executed before any Javascripts. However, nothing says you cannot do this only with Javascript - and it would actually be trivial to solve with jQuery (as you tagged the question with it). Just let your Ajax called PHP-page return the inline HTML, and print it with jQuery instead. No need for cookies, either.
PHP runs first because the page hasn't loaded yet and javascript is run user-side, but once the page is loaded, ajax allows you to make calls to a php script and recieve a result that you can then add to the page via javascript.... so yes it's doable:)
Sessions can contain as many keys as you need them to, just name them something specific
<script language="javascript">
if (window.location.search == "") {
window.location.href = window.location + "?width=" + screen.width + "&height=" + screen.height;
}
</script>
This will redirect the page you try to access to the same page but sending parameters to the page.
Then you would be able to:
<?php
$width = $_get['width'];
$height = $_get['height'];
?>
Related
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.
I am using php and an apache server. My application gathers data from the user, put's it in a database, then uses PDFLib to display the formatted data back to the user as a pdf. My problem is, I would like the pdf to display as a new page, this works. But, I also have a blank page left up with the URL containing the variables used to display the pdf. I would like this page to show a different summary page, in HTML, without the variables in the URL, but I don't know how to do that. In the code that follows, I am going to the summary page if the medical flag is false. What I would like is to go to BOTH pages if the medical flag is true. Is this possible?
if($medical_flag) {
header("Location: {$_SERVER['PHP_SELF']}/./index.php?step=wc_pdf&id={$event_id}");
} else {
header("Location: {$_SERVER['PHP_SELF']}?step=success&id={$event_id}");
}
exit;
OK, I understand how this is impossible, but I still haven't figured out how to solve the problem. I thought I could toss the opening of the PDF back at jQuery with something like this:
jQuery(document).ready(function ()
{
function display_pdf_page(data, textStatus) {
var current_record = data || {};
//somehow display the pdf now
}
function show_pdf(eventid){
jQuery.getJSON(
'./inc/get_current_record_data_json.php',
{'id': eventid},
display_pdf_page
);
}
...
});
Then after I process the data in php "call" the above using:
echo '<script type="text/javascript">'
, 'show_pdf($event_id);'
, '</script>';
But that doesn't work either, php doesn't know where to find show_pdf. My lack of understanding of client/server side events is killing me here. Call be obtuse... I don't get it.
This solution will not work as designed.
First, if you want to hide the data, you should switch to POST rather than GET. This way, the data is included in the HTTP payload instead of the URI.
Secondly, you should either include a hidden iframe for javascript to access the page for which generate the PDF. On successful execution of the AJAX call (or whatever method you use), you can then redirect the page to your desired destination.
As suggested by sixeightzero, POST should be used instead of GET in such cases.
However, maybe you could accomplish the desired effect with a big iframe spaning the window (100% width and height)?
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.
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;
}
?>
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});
});