Enable Cross Domain Ajax Request with Zend Framework 2

Cross Domain Ajax Request  are forbidden by default because of their ability to perform advanced requests (POST, PUT, DELETE and other types of HTTP request, along with specifying custom HTTP Headers) that introduce many security issues as described in cross-site scripting.

I discover some hack(i dont know whether it is an appropriate term for this but i think its not 😉 ) on how to deal with this.

Using jquery on front end and zf2 for back-end this is what i did.

This line customizes the ajax option that i will be sending , as you could see i enable crossDomain , and the credentials

jQuery.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    options.crossDomain = {
        crossDomain: true
    };
    options.xhrFields = {
        withCredentials: true
    };
});

Then from the back-end using ZF2, i set value for Access-Control-Allow-Origin which will be the specific domain note if you set allow credential to true Access-Control-Allow-Origin can only be set to a specific domain therefore using wildcard like ‘*’ is not allowed.

$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Access-Control-Allow-Origin', 'http://test.com');
$response->getHeaders()->addHeaderLine('Access-Control-Allow-Credentials', 'true');
$response->getHeaders()->addHeaderLine('Access-Control-Allow-Methods', 'POST PUT DELETE GET');

$response->setStatusCode(200);
$response->setContent('content here');
return $response;

Then back to the file where you put the ajaxfilter.
The final step is adding the actual ajax request.

jQuery.ajax({
    url: //yourdestinationFile,
    type: 'POST',
    data: {somedata:value},
    success: function (data) {

    }
});

Then FINISH!!! Your ajax request to other domain should work.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s