Sending JSON data to the remote server

JSON: JavaScript Object Notation.
JSON is syntax for storing and exchanging text information. Much like XML.
JSON is smaller than XML, and faster and easier to parse.

You may need to post JSON data to the server for different purposes. If you are wondering about ‘How to send JSON data to the remote server?’ then this article is for you. Keep on reading.

In this article, we will share different techniques to send JSON data to the server.
For one of the payment module development in Magento, we had to send the encrypted password(using plain password) to the gateway page. And we will use this scenario as an example.

Suppose we have the following data:


<?php
#web service to encrypt the password (which accepts the JSON data and returns the result in JSON format)
$url	= 'http://some-payment-gateway.com/WebService/EncryptPassword';
#password to be encrypted
$plainPass = 'some-plain-password';
$data = array(
	'password' => urlencode($plainPass)
);

1. Using Ajax


var data = <?php echo json_encode($data) ?>;
var url  = '<?php echo $url ?>';
jQuery.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
		var jsonObj = jQuery.parseJSON(data);
		alert(jsonObj.encPassword);
	},
    failure: function(errorMsg) {
        alert(errorMsg);
    }
});

Note: This approach can’t be used in Payment Module as we have to pass the encrypted password in hidden form fields

2. Using Curl


<?php
$content = json_encode($data);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
		array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //curl error SSL certificate problem, verify that the CA cert is OK

$result		= curl_exec($curl);
$response	= json_decode($result);
var_dump($response);
curl_close($curl);
?>

3. Using Streams


<?php
$options = array(
	'http' => array(
		'method'  => 'POST',
		'content' => json_encode( $data ),
		'header'=>  "Content-Type: application/json\r\n" .
					"Accept: application/json\r\n"
	  )
);

$context	 = stream_context_create($options);
$result		 = file_get_contents($url, false, $context);
$response	 = json_decode($result);
var_dump($response);

4. Raw HTTP Post

Using Zend Framework’s HTTP client: http://framework.zend.com/manual/en/zend.http.client.advanced.html#zend.http.client.raw_post_data


$json = json_encode($data);
$client = new Zend_Http_Client($url);
$client->setRawData($json, 'application/json')->request('POST');
var_dump($client->request()->getBody());

These were some basic examples. If you have any other idea regarding sending JSON data to the remote server, please share.