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

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.

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.
});

display browser window width using 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}
});

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.

noob question about autosuggest jquery plugin

I want to do some autosuggest for my text field, using this plugin AutoSuggest jQuery Plugin
I have an array, already json_encoded, and the files on the server, js, css, but Im not getting yet how the example works, here my code,
<html>
<head>
<title>test-data</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="inc/css/admin_style.css" rel="stylesheet" type="text/css">
<link href="inc/css/autoSuggest.css" rel="stylesheet" type="text/css">
<script language="javascript" src="inc/js/functions.js"></script>
<script language="javascript" src="inc/js/jquery-1.5.1.js"></script>
<script language="javascript" src="inc/js/jquery.autoSuggest.js"></script>
<script language="javascript" type="text/javascript">
</script>
</head>
<body>
<center><br><font class="title">test</font></center>
<form action="dataAll.php" method="post">
Name: <input type="text" name="fname" />
<input type="submit" />
</form>
<p> </p>
<p>JSON</p>
<p> </p>
<?php
$encoded = json_encode ($familyNames);
echo $encoded;
?>
</body>
</html>
so Im supposed to put this code,
$(function(){
$("input[type=text]").autoSuggest(data);
});
but the question is where??( as if I put it inside the php tags, it gives me an error
where should I put the name of my json formatted array? "$encoded" for the function to recognize that is the source of data?
thanks a lot!
You've got all the pieces, but your order/methodology is a bit off. Try creating a second file, named something like ajax.php, and place all of your php code in there. To ensure you are outputting good JSON, add the line header('Content-Type: text/json; charset=ISO-8859-1'); at the very beginning of the ajax.php file (you must set the header before any output is sent or you'll get an error). Now you've got to request your suggestion data:
$(document).ready(function() { // Runs when your page is loaded in the user's browser
$.getJSON('ajax.php', function(data) { // Runs ajax.php, then executes an anonymous function to handle the response
$('input[name="fname"]').autoSuggest(data); // Set your input field to use automatic suggestions with the returned data
}); // end getJSON
}); // end ready
This code simply executes an asynchronous HTTP request for ajax.php, and hands off the returned JSON data to the auto-suggest jQuery plugin. Place it inside a <script type="text/javascript"></script> tag. It will run once when the page loads due to the use of $(document).ready(...). I added the small optimization (input[name="fname"]) so jQuery doesn't attempt to attach the auto suggestion functionality to every text input you have on your page. If thats what you wanted to do (unlikely), just change it back to input[type=text].
You really do not need a separate php file to get this to work. There is nothing stopping you from doing it all in one file, but you'll soon realize how cluttered and unmanageable that can get. For me, its easiest to think of my "ajaxy" php code as a single, modular piece of my web application.
Be sure to reference these pages for detailed information:
http://api.jquery.com/
http://api.jquery.com/ready/
http://api.jquery.com/jQuery.getJSON/
You put it inside a tag in the html.
<script type="text/javascript">
$(function(){
$("input[type=text]").autoSuggest(data);
});
</script>

Categories