-2

I've been trying to do an ajax post request to an external URL and when I try the same request in the website hurl.it, it gives a proper response but when I try on the browser, I don't get the browser.

In hurl.it, I'm entering the https url, content-length in the header and the request body is a json field. But when I send the same parameters using the following code, I get either 200 OK without a response or 400 denied without any response.

    var parameter = some json data;
    $.ajax({
                    url:"external-url",
                    type: 'POST',
                    data : parameters,
                    headers:{
                        "Content-Length" : 10070
                    },
                    success: function(data){
                        alert('success');
                    }
            });

Later I tried a POST request using PHP but did not get any response either.

$url = "external-url"
$data = json_encode($data1);
// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
        'Content-Length' => 10070
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);

And the php code gives me a result bool(false). I don't know what the result means and any help would be appreciated.

1 Answers1

0

If the external url is some other domain then it's not possible to make calls to different domain as by default, Ajax calls are allowed within the same domain origin.

If it's cross domain service call, then you may need jsonp service.

here is an example:

$.ajax({
            crossDomain: true,
            url: "yourexternalURL?callback=?",
            data: parameters, // pass the data
            dataType: "jsonp",                
           //this is very important since it's the callback we will and that allow cross domain
            jsonp: 'jsonp_callback',
            success : function(data){
                 // process the data
            }
        });

In the server:

    <?php

$data = '{}'; // json string

if(array_key_exists('callback', $_GET)){

    header('Content-Type: text/javascript; charset=utf8');
    header('Access-Control-Allow-Origin: http://www.example.com/');
    header('Access-Control-Max-Age: 3628800');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

    $callback = $_GET['callback'];
    echo $callback.'('.$data.');';

}else{
    // normal JSON string
    header('Content-Type: application/json; charset=utf8');

    echo $data;
}
?>
mohamedrias
  • 18,326
  • 2
  • 38
  • 47