I'm creating an advertisement like service, and using AJAX to fetch some picture links from another web server. The question is, can anyone show some examples of how to create a response for the second web server when an AJAX call has been made to it? I have been searching the web for answers, but haven't found anything that could help me with this case. Thank you.
2
-
is JSONP useful , it can besshet– sshet2014-04-26 10:39:11 +00:00Commented Apr 26, 2014 at 10:39
-
I'm trying to use jsonp, but the question is, once a request was made by the client, how to handle it on the other web server and return the results?user3443640– user34436402014-04-26 10:40:12 +00:00Commented Apr 26, 2014 at 10:40
Add a comment
|
1 Answer
A JSONP response is basically just a piece of JavaScript which is a function call, with an argument being the JavaScript object or array for the data. You should look for a callback querystring variable to use as the function name.
A PHP example:
// the data to return
$data = array('image' => 'http://placehold.it/100x100');
// default callback name if none set
$function = 'callback';
// if callback set, override the default
if(isset($_GET['callback'])){
// filter the callback so it can only contain a-zA-Z0-9
$function = preg_replace("/[^a-zA-Z0-9]+/", "", $_GET['callback']);
}
// output
echo $function . '(' . json_encode($data) . ');';
Example when called via http://yoursite/data.php?callback=abc
abc({ "image" : "http://placehold.it/100x100" });
Consuming this service via jQuery would be:
$.ajax({
url : 'http://yoursite/data.php?callback=?',
dataType : 'jsonp',
success : function(response){
console.log(response.image);
}
});
5 Comments
user3443640
Let's say if there is additional things written on that webpage that I am trying to request information from. Will all that additional stuff be sent to me?
MrCode
Not sure what you mean. You can only access what the page responds with. If it's JSONP, you can only access the data portion (argument to the function).
user3443640
And the page responds all of the information that would have been displayed if just entered the url manually, correct? Is there somekind of issue that the .ajax call could neither be success or error? Because I have tried making a request and added success or error, however none of them are executing.
MrCode
Can you show what the output is, that the page responds with?
user3443640
Thanks for your help! I managed to get everything working now and it seems like I started to understand this a little clearer.