display browser window width using PHP - php

I would like my PHP script to be able to access the width of the browser window. I've been reading up on this, and PHP can't access this information itself, but Javascript/jQuery can, and can then pass it to the server using AJAX, so PHP can get at it.
Following a few solutions online I've written the following test file, and called it "test.php"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<?php
if (!isset($_POST["window_width"])) {
?>
<script type="text/javascript">
var window_width = $(window).width();
$.ajax({
type: "POST",
data: "window_width="+window_width,
});
</script>
<?php
}
if(!isset($_POST["window_width"])) {
echo "not set";
}
?>
</html>
Loading test.php displays "not set" which shows that the window_width variable is not being picked up by PHP. This seems weird to me, because Firebug shows that the variable is there (set at 1366 on my computer, as this is the width of my browser).
How can I ensure that $_POST["window_width"] is set so that I can access it using PHP?

Description
I dont understand whats you goal ist but it looks like you forgot to wait till the DOM is ready.
Sample
$(function() {
var window_width = $(window).width();
$.ajax({
type: "POST",
data: "window_width="+window_width,
});
});

Your server side code doesn't pause processing to wait for the JavaScript to run. You are dealing with two separate HTTP requests here.
The browser requests the HTML document
Since $_POST['window_width'] is not set for that request. PHP returns an HTML document that includes the script. Since $_POST['window_width'] is still not set for that request, it also echos not set.
The browser receives the HTTP response and parses it. As part of this process, it runs the JavaScript.
The JavaScript makes a POST request to … wherever jQuery sends requests to by default since you didn't include a URI (which a very quick test suggests is the current URI).
For this request $_POST["window_width"] is set and included in the document returned to JavaScript.
Since the JavaScript doesn't have a success handler (or any other code that runs when the HTTP request comes back) the browser doesn't do anything with that document.
Ajax is a shorthand way of saying "Talk to the webserver with JavaScript". It doesn't stop HTTP being a stateless Request-Response protocol.
You haven't stated your usecase for getting the window width (which can change after the page has loaded), so it is hard to suggest a good solution to whatever problem you have. (You appear to have asked an XY Problem).
The two common reasons for wanting to know the window width are:
Statistics — in which case you can just process the data in PHP and not worry about rendering it to the client
Changing the layout — which is usually better achieved with CSS media queries

I don't think you need to use ajax in this case, the 'outer' (?) page needs to receive the data, not the 'inner' ajax request.
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<?php
if (!isset($_POST["window_width"]) && !isset($_SESSION['window_width'])) {
?>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="window_width_form" style="display:none;">
<input name="window_width" id="window_width" value="" />
</form>
<script type="text/javascript">
$(function(){
$('#window_width').val($(window).width());
$('#window_width_form').submit();
});
</script>
</body>
<?php
}
elseif (isset($_POST['window_width']) && !isset($_SESSION['window_width']))
{
$_SESSION['window_width'] = $_POST['window_width'];
exit(header("Location: {$_SERVER['PHP_SELF']}\r\n"));
}
if(!isset($_POST["window_width"]) && !isset($_SESSION['window_width'])) {
echo "not set";
}
?>
</html>

Try
$.ajax({
url : "your url goes here"
type: "POST",
data: {"window_width":window_width}
});

Related

How do I use Ajax to auto refresh a div across domains?

Can someone help me out? I have an html file that calls a php script via ajax and displays a random number that the php script generates. It works just fine when both files are on the same domain, but if the 2 files are located at different domains, which is what I need, nothing happens. Can someone help me fix this.
The code for the HTML file is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#divToRefresh').load('http://www.OTHERDOMAIN.com/random.php');
}, 5000); // the "5000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]></script>
</head>
<body>
<div id="divToRefresh">Loading users...</div>
</body>
</html>
If the line
$('#divToRefresh').load('http://www.OTHERDOMAIN.com/random.php');
is changed to:
$('#divToRefresh').load('random.php');
and placed in the same folder as the html file all is well.
The code for the php file is:
<?php
$random1 = sprintf("%02f", rand(0,9212));
echo $random1;
?>
What would the revised code that would allow cross domain ajax calls look like? I was reading documentation that talked about a json request wrapper, but I did not get where it was going. Any help would be hugely appreciated.
you are not able to use ajax cross domain its not possible, you have the following options though:
1.do the ajax to your own page and make a curl call to that page..
2.do $.getJSON('ur', variables, function(data){}).
there are few other solution, but those 2 are basically your best options
here is how getJson works:
On your server you should have a page that is ready to receive the $_GET sort of like an API or normal ajax call would do with $_POST.
should look something like :
<?php
if(!empty($_GET['jsoncallback']) && !empty($_GET['variable'])){
/* do whatever you like with the variable you get as get
*
*
*
**/
// echo the name of the callback function + the variables you want to receive back in JS
echo $_GET['jsoncallback'].'('.json_encode($jason_echo).')';
}
?>
Your JS or page you are going to do the call from should look something like:
$.getJSON("SomePage/PagethatTakesTheGet.php?jsoncallback=?", {variable:15}, function(response){
// do whatever you want with response.
});

Javascript is not loading when I load the content of external website

I have a page where I am loading external site content through Jquery Post method to my PHP file (due to cross site issue) which looks like this.(back.php)
$url = $_POST['url'];
echo file_get_contents($url);
And My HTML code looks like this
$.post ("back.php",
{
url : "http://www.ralphlauren.com/product/index.jsp?productId=2130294&cp=1760781.1760809&ab=ln_men_cs1_polos&parentPage=family"
}
,
function (data)
{
document.getElementById ("output").innerHTML = data;
}
);
The site content is loading fine, but the script is not loading, because of that I am getting error while changing any options which should execute the script.
I tried different methods but no use.
How Can I achieve to load the script also.
EDIT
It looks like my question was not clear.
The issue is, the content along with script of the given URL is loading in my page. The external URL contains some embedded scripts which is not executing.
Here is an example of the external site
<html>
<body>
Hello
<script>
alert("This is some message");
</script>
</body>
</html>
Now if we run this page directly in browser, it shows the text "Hello" as well as alert message, however when I load this file though the above method (POST/Jquery), it is showing "Hello" but not displaying the alert message (means, not executing the javascript).
Please help me to execute that script.
You should use $(function() { }) to load the js when execute it !
Loading HTML with elements into the page is not very stable. This will not work cross-browser cause some browsers don't run the onload in the external page (fetched with ajax).
So don't do this, run the javascript you need in the callback op you $.post.
edit
see also this
Not sure why yours is not working but, try this, seems to work perfectly:
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['url']){
header('Content-Type: text/html');
echo file_get_contents($_POST['url']);
die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" charset="utf-8"></script>
<script charset="utf-8" type="text/javascript">
$(function() {
$.post ("back.php",{
url : "http://www.ralphlauren.com/product/index.jsp?productId=2130294&cp=1760781.1760809&ab=ln_men_cs1_polos&parentPage=family"
},function (data){
document.getElementById ("output").innerHTML = data;
});
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
Error may be caused for following reasons:
May be you forget to load jQuery library.
You forget wrap you code within DOM ready ie. $(function() { })
If you are trying to retrieve data from different domain, then you should try with jsonp type request.

JQuery / PHP call with AJAX not working

I've been trying to get this really simple example of using AJAX with JQuery and PHP to work with no luck (here's the page for the sample). I've had a look at quite a few posts with similar discriptions and none have helped...
I've copied the code exactly but my function that should be run on success is never called. As an experiment, in the call to $.post I commented out the data part ({sendValue:str}) and the JSON part and added an alert into the body of the success function to see if it was called and it was. So I'm guessing there's something wrong with how I've created my data? I also tried to display the data returned from the AJAX call in the alert and it came out as 'undeclared' (data.returnValue).
This is a copy of my code, you can see the full example via the link above and also a working example from the author of the tutorial here: http://www.devirtuoso.com/Examples/jQuery-Ajax/
JQuery:
$(document).ready(function(){
$('#txtValue').keyup(function(){
sendValue($(this).val());
});
});
function sendValue(str){
$.post("ajax.php",
{ sendValue: str },
function(data){
$('#display').html(data.returnValue);
},
"json"
);
}
PHP:
<?php
//Get Post Variables. The name is the same as
//what was in the object that was sent in the jQuery
if (isset($_POST['sendValue'])){
$value = $_POST['sendValue'];
}else{
$value = "";
}
//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode(array("returnValue"=>"This is returned from PHP : ".$value));
?>
HTML:
<body>
<p>On keyup this text box sends a request to PHP and a value is returned.</p>
<label for="txtValue">Enter a value : </label><input type="text" name="txtValue" value="" id="txtValue">
<div id="display"></div>
</body>
Thanks!
EDIT:
I rewrote my $.post into a $.ajax with an error function in it. I'm definitely hitting the error function and the error is a parse error - I'm guessing it's coming from my PHP script when I call json_encode... here's a screenshot from firebug - anyone got any more ideas?:
Screenshot 1 - firebug console
Screenshot 2 - firebug watch window
Thanks for all the help so far by the way, really appreciate it.
I noticed that var str = $('#txt').val(); would give you an error because $('#txt') does not exist, it should be $('#txtValue').
After looking at your code, everything looks as it should, my next step would be trying to debug your code by using some console.debug() in JavaScript and some echo in PHP. I recommend you get Firebug for Chrome/Firefox and if using IE upgrade to IE9 and use their developer tools. Using the mentioned tools will give you a better idea of how your code is executing.
My first step would be to make sure that the keyup is firing:
$(document).ready(function(){
$('#txtValue').keyup(function(){
alert('keyUp');
sendValue($(this).val());
});
});
Second step would be to make sure sendValue is firing:
function sendValue() {
alert('sendValue');
var str = $('#txt').val();
tmr = null;
$.post(
'test.php',
{ sendValue: str },
function(data) {
alert('inside post');
$('#output').html(data.returnValue);
},
'json'
);
}
Without seeing more of what your various elements are outputting, I don't think I can tell you what to fix, but this example is similar to yours (although it's an all-in-one PHP file rather than two, as in your example). I also added a 350ms timeout to allow the user to type without having the page do an AJAX request every keystroke. As soon as they pause, it'll fetch the data.
Source to test.php
<?php
if(isset($_POST['sendValue']))
{
echo json_encode(
array('returnValue' =>
'Returned: ' . $_POST['sendValue']));
exit();
}
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX Sample</title>
</head>
<body>
<input type="text" id="txt" />
<div id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var tmr = null;
$(function () {
$('#txt').keyup(function() {
if(tmr != null)
clearTimeout(tmr);
tmr = setTimeout("sendValue()", 350);
});
});
function sendValue() {
var str = $('#txt').val();
tmr = null;
$.post(
'test.php',
{ sendValue: str },
function(data) {
$('#output').html(data.returnValue);
},
'json'
);
}
</script>
</body>
</html>
To anyone who gets here looking for an answer to a similar question:
I tried a few things to figure out what was going on, debugging the messages etc and everything looked fine. I then deployed my code to a virtual box running apache and to my web server to see if it was an environmental thing. My code worked on my web server and on the virtual box. I then realised that I had two conflicting installs of PHP on my dev system. I'm not sure why but this was causing the problem but rolling them both back and reinstalling WAMP on the dev system did the trick.
try this
$(document).ready(function(){
$('#txtValue').keyup(function(){
$.post("ajax.php",{ sendValue: str }, function(data){
$('#display').html(data.returnValue);
},
"json"
);
});
});

Why a Javascript code returned with AJAX doesn't write in a specified <div>, but it replaces the whole page?

I am requesting with AJAX (using jQuery) a tag which contains a Javascript function call to an Apache+PHP server. Here is the HTML and AJAX code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://localhost/LivingLab/javascript/jquery.min.js"></script>
</head>
<body>
<a href="javascript: void(0)" onclick="
$.post(
'http://localhost/test.php', // server target page
{some_var: 'abc'}, // data to be sent via POST method
function(data) { // JS callback function
$('#container').html(data); // innerHTML of <div id="container"> will be replaced
}
)
">Click me!</a>
<div id="container"></div>
</body>
</html>
AJAX requests the page 'http://localhost/test.php' which has the following PHP code:
<?php
echo '<script type="text/javascript"> document.write("Javascript output"); </script>';
?>
When I click on the link, after the AJAX request, the whole page is replaced by "Javascript output", instead of writing this only inside the div tag with id "container".
If the PHP server script writes something else, instead of a script tag like this:
<?php echo 'text' ?>
the AJAX call behaves normal, by replacing div with id "container" and not the whole page.
I tried to investigate HTTP data transfered by this pages with Wireshark and it doesn't seem to be an HTTP problem because server response is exactly how it should be:
<script type="text/javascript"> document.write("Javascript output"); </script>
Running the Javascript code without AJAX does not replace the whole page, this happens only when the script tag is returned using AJAX. A noticed the same behavior in Firefox 3 and 5 and also in Google Chrome.
Why does this happen?
document.write is normally used during the main load of the page, during which it outputs to the parsing stream that the browser reads to render the main page. If you use it after the initial load of the page is complete, it implicitly does an open on the document, which completely tears down the document and starts fresh with the newly-written content.
The short version is: Only use document.write during main page load (if then). After the page has loaded, use DOM manipulation instead.
Example (live copy):
<body>
<input type='button' id='theButton' value='Click Me'>
<script>
document.write(
"<p><code>document.write</code> is fine here, during " +
"the main load of the page.</p>");
document.getElementById("theButton").onclick = function() {
document.write(
"<p>But not here, because the initial " +
"page load is complete and using " +
"<code>document.write</code> at this point tears " +
"down the document and starts new one.</p>");
};
</script>
</body>
More about from the DOM2 HTML spec, the HTML5 spec, and MDC:
document.write: DOM2 | HTML5 | MDC
document.open: DOM2 | HTML5 | MDC(called implicitly by document.write if you call it once the page is loaded)
Because jQuery will recognise the javascript block and run it against the page, not the target container.
https://groups.google.com/forum/#!topic/jquery-en/tzu5n5k8Jp4
<script type="text/javascript"> document.write("Javascript output"); </script>
Why not just return "JavaScript Output" since you're altering the value of $('#container') anyway, there's no need to try to use an inline JavaScript document.write to write it out.

Achieving Google Visualization chart reloads using ajax

Been looking around the web, but not found anything so far... can anyone help?
I have created a simple html page that contains a list-box of values that when selected calls a seperate php script to run database query and print out a structure html page. This has been implemented using ajax calls and it results in the page being reloaded when the user changes the value in the list-box.
Now, I would like to move away from the generating of the table using html tags and print statemetns to something more slick and have discovered google visualisation api. I have look ready through many pages of the site and used the code playground, but was unable to find information to help me understand how I might use the visualization api to generate the table and pass this back to the main page in the div tag, using the same php script.
Does anyone have any pointers, or experience of doing this in the past?
Thanks.
You could achieve this using jQuery AJAX and some arrays generated by your php. This is a pretty basic but straightforward approach - you may want to look around for php client libraries that generate gviz code for you in your php if this proves to be insufficient.
Here's a working example:
HTML file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.6.1");
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
function drawVisualization(dataFromAjax) {
var data = google.visualization.arrayToDataTable(dataFromAjax);
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data);
}
function makeAjaxCall() {
$.ajax({url:'test.php',
data: {},
success: function(responseData) {
// eval just for testing - make safer
var arrayForGviz = eval("(" + responseData + ")");
drawVisualization(arrayForGviz);
}
});
}
</script>
</head>
<body>
<input type="button" onclick="makeAjaxCall();return false;" value="Click to get data"></input>
<div id="table"></div>
</body>
</html>
​
​PHP File
<?php
echo "[['Country','City','Value'],
['Ireland','Dublin','10'],
['France','Paris','15']]"
?>
Obviously my php file is static, but each time the user interacts with the page and triggers makeAjaxCall() you could send different parameters, and return different array responses.

Categories