Kern Elliott
Kern Elliott

Reputation: 1659

Using Ajax to access an external php file

so I am trying to access some content in an external php file (not on my domain) however I can browser to the content but I cannot access it via jquery ajax here is my code:

function newarticle()
{
var ajax_load = "<img src='images/spiral.gif' align='center' alt='loading...' />";  

//load() functions  
var loadUrl = "http://www.webapp-testing.com/includes/newarticles.php";  
$("#articles").click(function(){  
    $("#pagetitle").html(ajax_load).load("New Articles");
    $("#listarticles").html(ajax_load).load(loadUrl);  
}); 
}

what am i doing incorrect to access this content?

Upvotes: 1

Views: 1263

Answers (3)

njmu83
njmu83

Reputation: 314

Create your own php file that get the content of the desired url with a curl. -> http://ch.php.net/manual/de/book.curl.php

=> your_php_file.php

<?php

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://www.webapp-testing.com/includes/newarticles.php");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($curl);
curl_close($curl);

print $page;

?>

In your javascript code, call your_php_file.php

function newarticle()
{
var ajax_load = "<img src='images/spiral.gif' align='center' alt='loading...' />";  

//load() functions  
var loadUrl = "your_php_file.php";  
$("#articles").click(function(){  
    $("#pagetitle").html(ajax_load).load("New Articles");
    $("#listarticles").html(ajax_load).load(loadUrl);  
}); 
}

Upvotes: 0

matino
matino

Reputation: 17715

As Xeon06 mentioned - you can't make cross site requests with AJAX. You can have a look at JSONP though that basically allows you to do it.
Link to jQuery docs
Link to JSONP Wikipedia

Upvotes: 1

Alex Turpin
Alex Turpin

Reputation: 47776

You can only make AJAX requests on the same domain due to the Same Origin Policy. Your best bet is to make a server-side (in something like PHP) proxy. You would then make the request on the proxy (which would be on the same server), which would make a request to the page and return the information.

Upvotes: 2

Related Questions