Manny
Manny

Reputation: 61

Calling JSONP Ajax Callback from Javascript

I'm trying to send an JSONP Ajax request (from client.htm to proxy.htm), which is received by a proxy page which creates another different Ajax JSONP request to a service (proxy.htm ---> service.php). At the moment the proxy page receives the JSON format object from the service, but I'm stuck on returning the object to the first initial Ajax request. The following if the sample code I'm trying to run. Is this possible with Javascript? If so, how could I return the object to the clientCallback function.

Client.htm

// CLIENT ---> PROXY
$(document).ready(function () {
     $.ajax({
            type: 'GET',
            url: 'http://localhost/jsonp_proxy/listener.htm',
            dataType: 'jsonp',
            jsonpCallback: "clientCallback",
            success: function (theData) {
              alert("Success");
            },
            error: function (xhr, ajaxOptions, thrownError) {
              alert("Error");
            }
        });
      });
      window.clientCallback = function(results) {
        alert(results.uid);
      }

Proxy.htm

      // PROXY ---> SERVER
      $(document).ready(function () {
        $.ajax({
          type: 'GET',
          url: 'http://localhost/jsonp_server/service.php',
          dataType: 'jsonp',
          jsonpCallback: "proxyCallback",      
          success: function (theData) {
//          alert("Success");
          },
          error: function (xhr, ajaxOptions, thrownError) {
//          alert("Error");
          }
        });
      });
      window.proxyCallback = function(resultData) {
        // HOW TO CALL CLIENT CALLBACK FUNCTION
      }

Service.php

<?php
echo "proxyCallback("."{'uid': 123, 'username': 'jdirt', 'name': 'Joe Dirt'}".");";
?>

Upvotes: 4

Views: 1785

Answers (2)

saml
saml

Reputation: 6802

Simply call window.clientCallback from window.proxyCallback.

Upvotes: 0

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

One of the few semi-valid uses for eval:

success: function (theData) {
  eval("(" + theData + ")");
  //alert("Success");

Just as a reminder, JSONP is something of a hack and security risk. You are giving a lot of trust and control to a 3rd party.

Upvotes: 1

Related Questions