jQuery to get another sites page content / div content - javascript

I'm trying to grab some tracking information from a website and tried to use load and ajax but I'm getting the following errors:
XMLHttpRequest cannot load http://www.tuffnells.co.uk/PODLookupResults.aspx?__EVENTTARGET=&__EVENTARGU…%24tbDestPostcode=AL15BY&ctl00%24maincontent%24btnDoPODLookup=Search+Again. No 'Access-Control-Allow-Origin' header is present on the requested resource.
What I have tried:
<div id="tracking"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#tracking").load( "http://www.tuffnells.co.uk/PODLookupResults.aspx?__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATEGUID=7ca82b1d-b722-4cdc-b74a-b338d8577ffa&__VIEWSTATE=&__EVENTVALIDATION=%2FwEdAAevVXD1oYELeveMr0vHCmYPaomE%2FDwQD43eOdzEj3p%2Fm4U4pgxq6tlupSJfQZQBazFFj%2F1LmlGLyHFagz1yHZm8bjowVgAJ8C3e%2B2bVMPt91KjXCHjnAsonQDi2zFSuasUVzpitHiLDCDtiLHCjNCQG4CxrbV5VPFqBeOgs2X52AD%2FEb%2BYR%2BEJ68PaN2CiyKzE%3D&ctl00%24ctl16%24tbHeaderSearch=Search..&ctl00%24maincontent%24tbAccountRef=01484267&ctl00%24maincontent%24tbConsignmentRef=2837&ctl00%24maincontent%24tbDestPostcode=AL15BY&ctl00%24maincontent%24btnDoPODLookup=Search+Again #ctl00_maincontent_pnlPODRecords" );
});
</script>
and
<div id="tracking"></div>
<script type="text/javascript">
$(document).ready(function(){
var url = "http://www.tuffnells.co.uk/PODLookupResults.aspx?__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATEGUID=7ca82b1d-b722-4cdc-b74a-b338d8577ffa&__VIEWSTATE=&__EVENTVALIDATION=%2FwEdAAevVXD1oYELeveMr0vHCmYPaomE%2FDwQD43eOdzEj3p%2Fm4U4pgxq6tlupSJfQZQBazFFj%2F1LmlGLyHFagz1yHZm8bjowVgAJ8C3e%2B2bVMPt91KjXCHjnAsonQDi2zFSuasUVzpitHiLDCDtiLHCjNCQG4CxrbV5VPFqBeOgs2X52AD%2FEb%2BYR%2BEJ68PaN2CiyKzE%3D&ctl00%24ctl16%24tbHeaderSearch=Search..&ctl00%24maincontent%24tbAccountRef=01484267&ctl00%24maincontent%24tbConsignmentRef=2837&ctl00%24maincontent%24tbDestPostcode=AL15BY&ctl00%24maincontent%24btnDoPODLookup=Search+Again";
$.ajax({
url:url,
type:'GET',
success: function(data){
$('#tracking').html($(data).find('#ctl00_maincontent_pnlPODRecords').html());
}
});
});
</script>
Anyone have any ideas? I need to get the tracking details into our tracking page as they don't provide a API.

Answers staring right at you!
No 'Access-Control-Allow-Origin' header is present on the requested resource.

It's not possible with Javascript, use PHP instead :
$.ajax({url: 'loadRemoteFile.php', type: 'POST', data: {loadPage: url}, success: function(data){
doStuff();
}});
and your PHP file :
if (isset($_POST['loadPage'])){
echo file_get_contents($_POST['loadPage']);

I found the link which may be helpful for you i think.
Thanks

Related

Can't get php POST sent by AJAX

I know there's a lot of similar questions here, but I looked up over 20 of them, and no solutions worked for me.
Here's the problem: I'm sendind an ajax post value to my index.php. When I look at Firebug, the value is there, but when I try to echo it on the page, the POST is empty. I'm really stucked on this.
Here's my full code:
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<!-- JQUERY LIBRARY AND SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
Test
<script type="text/javascript">
$(document).ready(function()
{
$('a').on('click', function()
{
$.ajax({
url: 'index.php',
type: 'POST',
data: {action: 'clicked'},
success: function(data)
{
console.log(data);
alert('Done!');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
return false;
});
});
</script>
</body>
</html>
This code does not try to print that to the page, but simply prepends the whole HTML document with a "clicked" string, in the ajax response. If you want to show this in the browser, you need print that data to the page. If you inspect the console in FireBug, you will see that the response for the Ajax call is exactly what I described above.
Now if you want to print that value back to your page, here is my suggestion, you create a separate file, ajax.php:
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
And fix your index.php to include some element where you are going to print that value to. I.e. add <div id="response-results"></div> just after your element. Then change your Ajax call to go to ajax.php, not index.php.
Now you need to populate that Ajax response to the rendered page, and this can be done simply with jQuery like:
$("#response-results").html(data);
Ofcourse, this goes into the success handler of the ajax call.
As Jay Blanchard said
You're using AJAX to send a a variable to a page which is already rendered on your browser. This will never work because the PHP your're getting the variable from has been run server-side and returned via AJAX, not in the page you're currently viewing.
Try this it will work :
index.php :
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
main.html :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<!-- JQUERY LIBRARY AND SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
Test
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function()
{
$('a').on('click', function()
{
$.ajax({
url: 'index.php',
type: 'POST',
data: {action: 'clicked'},
success: function(data)
{
// console.log(data);
$("#result").html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
return false;
});
});
</script>
</body>
</html>
As R J commented, it's impossible to do what I was trying to.
That happens because once my page is loaded, the top PHP script is proccessed, but there's nothing on my POST.
After my call to Ajax, the page is rendered again but the top PHP script will get nothing cause it's SERVER SIDE. Turns out that I even could print out my Ajax data on the page, but the PHP $_POST would never get its value.
Thank you guys.

Bing Image Archive Ajax Error

I have made an Ajax call to Bing to get its daily image, however i get an error in the console:
this is the full code its on a localhost using wamp
index.php
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
$.ajax({
url : "http://bing.com/HPImageArchive.aspx?format=js&idx=0&n=1",
dataType:"jsonp",
});
function mycallback(data)
{
$('#output').html(data.images[0].url);
}
</script>
I think you should study the documention for jquery ajax call.
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
(function() {
var bingImagesUrl = "http://bing.com/HPImageArchive.aspx";
$.getJSON( bingImagesUrl, {
idx:0,
n:1,
format: "js"
}).done(function( data ) {
$('#output').html(data.images[0].url);
});
})();
</script>
#Below_the_Radar: your answer does not really help as OP is likely getting the same error even if he makes the Ajax call correctly.
According to Is there a way to get Bing's photo of the day?, it seems that Bing.com only supports XML, JSON, and RSS. I guess OP want to make the call with dataType: "jsonp" probably because he would like to bypass the browsers same-origin policy.
This can be solved client-side in browser by using a Chrome extension, but I guess that is not OP's use case. I bet OP is trying to get a picture from Bing's archive and thus use it in his own website. If that is the case, it has no solution as we need to have "Access-Control-Allow-Origin": "*" in the response's headers returned by Bing, which we do not have control.
I suggest considering an alternative. Try this: https://source.unsplash.com/

Load Javascript after AJAX-fetched HTML is fully loaded

I have a situation where the HTML part is loaded with AJAX into a DIV with ID="dynamic content" using main.js script. This script is situated inside the HEAD part of main.php and it goes like this:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
}
});
The Javascript file responsible for controlling that content is situated in another JS file named secondary.js. This file is placed just before the closing of BODY again inside main.php.
main.php Document Structure:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
....
<div id="dynamic-content"></div>
....
....
<script type="text/javascript" src="js/secondary.js"></script>
</body>
</html>
Sometimes the content of content.php is too large, and secondary.js file loads before the content is fully loaded. Hence some elements are not targeted and i have problems.
Is there a way for me to delay for 1-2 seconds the execution of secondary.js, just to make sure that the content is fully loaded?
ps: all above files are hosted on the same server
Thanks in advance.
What you're trying to achieve is async behaviour. Whatever secondary.js does, put it inside a function and call it inside the ajax callback. If you do so, you won't even need two JavaScript files.
Don't try to manage this by timeouts or loading order. This will not be failsafe. You cannot know the exact time the browser needs to load your content. For example, what if you are on very slow internet connection? Don't try to predict those things, that's what the callback is for :-)
Your code could look sth like this:
function doSthWithLoadedContent() {
// whatever secondary.js tries to do
}
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
doSthWithLoadedContent();
}
});
You could possibly load the script using $.getScript once the output has been applied to the html tag:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
$.getScript('js/secondary.js');
}
});
https://api.jquery.com/jquery.getscript/
The best way to do this would actually be to hand a callback to the function that does your ajax call. I probably wouldn't put this in html but it demonstrates the method:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
<script lang="javascript>
function doWhenLoaded(someCallback)
{
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
someCallback();
}
});
}
$(document).ready(function(){
doWhenLoaded(function(){
$.getScript('js/secondary.js');
});
})
</script>
</head>
...
</html>
Instead of using $.getScript you could also load in secondary.js with main.js and wrap it in a function call (i.e. doStuff = function() { /* your code here */ }). Then you could call doWhenLoaded(doStuff) in $(document).ready.
You have to add script after ajax call.
$.ajax({
url: 'url of ajax',
type: "POST",
data: data,
dataType: "html",
success: function (data) {
$('#instructions').html('<div>' + data + '</div>');
$.getScript("js/html5lightbox/html5lightbox.js", function() {
$('body').find('.html5lightbox').html5lightbox();
});
}
});

Getting Data from php through Ajax [duplicate]

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 8 years ago.
I am a novice to PHP, trying to learn.
I have my php file present in www folder in the WAMP server.
<?php
echo 'Hi';
?>
This can be run if I go http://127.0.0.1/testRequestParameter.php from my Browser, it prints Hi
So now I created an HTML page(not present in the same directory)
<html>
<head>
<script src="jsLibrary/jquery-1.11.1.min.js" ></script>
</head>
<body>
<script type="text/javascript">
function getTestDataFromAjax()
{
var url = 'http://127.0.0.1/testRequestParameter.php';
$.ajax({
url: url,
success: function(data) {
alert(data);
},
async:false
});
}
</script>
<input type="submit" name="Button" onclick="javascript:getTestDataFromAjax(); return false;" />
</body>
</html>
And when I try to call that php through AJAX, the response is blank.
May be it I am missing something, any help will be appreciated.
Finding1: In my firebug it is showing, Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/testRequestParameter.php. This can be fixed by moving the resource to the same domain or enabling CORS.
Any setting which I need to change?
Scenario
I tested your script using EasyPHP: I created into http://localhost/script/test/ the file content.php
<?php
echo 'Hi!';
?>
Then, I added to my desktop index.php:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function getTestDataFromAjax()
{
var url = 'http://localhost/script/test/content.php';
$.ajax({
url: url,
success: function(data) {
alert(data);
},
async:false
});
}
</script>
<input type="submit" name="Button" onclick="javascript:getTestDataFromAjax(); return false;" />
</body>
</html>
Then, I launched index.php and clicked on the button, which returned an error when clicked:
XMLHttpRequest cannot load http://localhost/script/test/content.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Solution
So, I edited my content.php like this:
<?php
header("access-control-allow-origin: *");
echo 'Hi!';
?>
And it's now working

Retrieve the content of the JavaScript file

Using JavaScript, I want to retrieve the content of the script files. These script files remain in local(in web page).
For example.
In web page, there is a script,
<script src="tool.js"></script>
Latter, I want to get the content of tool.js and process the retrieved result (like dump its content).
I have tried to use jQuery.getScript. However, it tells me that Origin null is not allowed by Access-Control-Allow-Origin.
try an ajax like the following
$.ajax('/tool.js', {
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function(data) {
console.log(data);
},
error: function() {
console.log("call failed");
}
});
You need to configure your Access-Control-Allow-Origin:
Access-Control-Allow-Origin: *
This lets you use any resource to obtain assets from an external domain. Do this first and either Mahan's or Lars's solution will work.
More info:
Access-Control-Allow-Origin Multiple Origin Domains?
try using jquery.load() and put its contents on an element and use .html()
<html>
</head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
//setup ajax to work locally
$.ajaxSetup({
crossDomain: false,
isLocal :true
});
$("#a").load('jquery.js', function() {
alert($("#a").html());
});
});
</script>
</head>
<body>
<span id="a" style="display:none;"></span>
</body>
</html>
Browser Check:
the code above works and tested in FF, Safari, Opera and IE
but if you keep on having problem with Origin null is not allowed by Access-Control-Allow-Origin then having a web server installed is needed as said here; Origin null is not allowed by Access-Control-Allow-Origin
Reference:
http://api.jquery.com/load/
code for your disposal : http://jsfiddle.net/PeaH3/1/

Categories

Resources