Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery getJSON to external PHP page

I've been trying to make an AJAX request to an external server. I've learned so far that I need to use getJSON to do this because of security reasons ?

Now, I can't seem to make a simple call to an external page. I've tried to simplify it down as much as I can but it's still not working. I have 2 files, test.html & test.php

my test.html makes a call like this, to localhost for testing :

    $.getJSON("http://localhost/OutVoice/services/test.php", function(json){
    alert("JSON Data: " + json);
});

and I want my test.php to return a simple 'test' :

$results = "test";
echo json_encode($results);

I'm probably making some incredible rookie mistake but I can't seem to figure it out. Also, if this works, how can I send data to my test.php page, like you would do like test.php?id=15 ?


The test.html page is calling the test.php page on localhost, same directory I don't get any errors, just no alert ..

like image 737
Pmarcoen Avatar asked Apr 26 '09 14:04

Pmarcoen


2 Answers

It could be that you haven't got a callback in test.php. Also, json_encode only accepts an array:

$results = array("key" => "value");
echo $_GET['callback'] . '(' . json_encode($results) . ')';
// the callback stuff is only needed if you're requesting from different domains

jQuery automatically switches to JSONP (i.e. using script tags instead of XMLHttpRequest) when you use http://. If you have test.html and test.php on the same domain, try using relative paths (and no callbacks).

like image 172
moff Avatar answered Oct 12 '22 23:10

moff


Be careful with moff's answer. It's got a common XSS vulnerability: http://www.metaltoad.com/blog/using-jsonp-safely

like image 32
drewish Avatar answered Oct 12 '22 22:10

drewish