My php file located at port 80 (default port) while my ajax call are on port 8080.
My index.html on port 8080
$(document).ready(function(){ $.get("userCheck.php", {"username" : "lazy", "favcolor" : "FFFFFF" }, function(data){ alert("Data Loaded: " + data); });
My PHP
$user = $_GET["username"]; if($user == "lazy") echo "SUCESS"; else echo "FAIL";
I have googled abit, JSONP came out mostly. Any idea how to convert it to JSONP?
Any way to make it work?
Advertisement
Answer
Implementing a JSONP service is really simple, you need only a callback GET parameter and at the end, print a string containing the equivalent to a function call with the JSON data as the argument:
$callback = $_GET["callback"]; $user = $_GET["username"]; if($user == "lazy") { $response = array("message" => "SUCESS"); } else { $response = array("message" => "FAIL"); } echo $callback . "(". json_encode($response) . ");";
Then you can use it with jQuery $.getJSON
:
$.getJSON("jsonpTest.php?callback=?", { username: "lazy"}, function(json){ alert("JSON Data: " + json.message); // SUCCESS });