1

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 be Commented 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? Commented Apr 26, 2014 at 10:40

1 Answer 1

1

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);
   }
});
Sign up to request clarification or add additional context in comments.

5 Comments

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?
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).
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.
Can you show what the output is, that the page responds with?
Thanks for your help! I managed to get everything working now and it seems like I started to understand this a little clearer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.