Leon van der Veen
Leon van der Veen

Reputation: 1672

Json request to another domain

Im trying to make a request from one server to another with json and php.

my html page:

$.ajax({
            type: "POST",
            url: "https://api.domain.com/gateway/partners/create_account.ajax.php",
            dataType: 'jsonp',
            crossDomain: true,
            data: { "name" : "Test name"},
            success: function(data)
            {
                console.log(data.responseText);
            }
          });

My php looks like this:

$name = $_GET['name'];
$data = array("Hello", $name);

echo json_encode($data);

I want to receive on my console: Hello Test name

What did I do wrong?

Upvotes: 0

Views: 98

Answers (2)

Quentin
Quentin

Reputation: 943939

You are:

  1. Telling jQuery to process the response as JSONP
  2. Writing PHP that will output JSON (not JSONP) … presumably with a text/html content-type.
  3. Trying to make a POST request instead of a GET request. JSONP only supports GET.
  4. Trying to treat the data returned by the request as if it were an XHR object.

The minimal example of a JSONP response would be:

<?php
header("Content-Type: application/javascript");
$name = $_GET['name'];
$data = array("Hello", $name);

echo $_GET['callback'];
echo "(";
echo json_encode($data);
echo ");";

Then you need to alter the JS so that type: "POST" becomes type: "GET" and console.log(data.responseText); becomes console.log(data);

Alternatively, you could use another technique to bypass the same origin policy and still use POST.

Upvotes: 3

mcuadros
mcuadros

Reputation: 4144

The jsonp is a old practice and a insecure one because any one can call to your script. To is very default tor retrieving errors when a jsonp call fails.

You can implement CORS headers in your request, and then you can use just a simple XHR call.

Addeding the header:

Access-Control-Allow-Origin: *

Will fix your issue, but is better use the exact domain instead of the wildcard.

Upvotes: 0

Related Questions