Make an ajax request to another server using JSONP

You are viewing revision #1 of this wiki article.
This is the latest version of this article.

There are cases that you want to make an ajax request to another server and get the results.

but Browsers apply the same-origin policy and not allow you to do that http://en.wikipedia.org/wiki/Same-origin_policy

However there is a way to do that through our server using JSONP http://en.wikipedia.org/wiki/JSONP

we will use the EHttpClient extension to make requests from our server to another one, so add this extension http://www.yiiframework.com/extension/ehttpclient/

In your controller

public function actionJSONP($url=null) {
	if ($url === null)
		throw new CHttpException(403, 'Invalid request');

	if (Yii::app()->request->isPostRequest) {
		echo $this->callHttpClient($url, $_POST, 'POST');
	} else {
		echo $this->callHttpClient($url, array(), 'GET');
	}

	Yii::app()->end();
}

public function callHttpClient($exUri, $params = array(), $methodRequest = 'GET') {
        Yii::import('ext.EHttpClient.*'); //if you not add it in your config/main.php
       
        $client = new EHttpClient($exUri, array());

        if ($methodRequest === 'GET') {
            $client->setParameterGet($params);
            $response = $client->request('GET');
        } else {
            $client->setParameterPost($params);
            $response = $client->request('POST');
        }

        if ($response->isSuccessful())
            return $response->getBody();
        else
            return null;
    }

In your view

<div id='div-1'>waiting for ajax response...</div>
 
 <script> 
 $.ajax({
  url: 'http://www/yourdomain.com/index.php?r=site/JSONP&url=http://www.anotherserver.com',
  type: 'POST',
  data: {"data_to_another_server1":'value1',"data_to_another_server2":'value2'},
  success: function(data) {
    $('#div-1').html(data);
  },
  error: function(e) {
    console.log(e.message);
  }
}); 
</script> 

Thats it!