Make an ajax request to another server using JSONP

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

However there is a way to do that through our server using JSONP

we will use the EHttpClient extension to make requests from our server to another one, so add this extension

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');


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') {
            $response = $client->request('GET');
        } else {
            $response = $client->request('POST');

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

In your view

<div id='div-1'>waiting for ajax response...</div>
  url: 'http://www/',
  type: 'POST',
  data: {"data_to_another_server1":'value1',"data_to_another_server2":'value2'},
  success: function(data) {
  error: function(e) {

Thats it!