Featured Post

Cross Domain AJAX POST Call

Friends, 
      would like to discuss today about cross site AJAX post which is powerful feature n client side with out waiting for server response . I have used Jquery to make AJX POST call to my website 
teknosys.in . the same code which I deployed in my blogs that is working great . would like to share the code with you . 

server side code looks as follows ajax.php
----------------------------------------------------
   switch ($_SERVER['HTTP_ORIGIN']) {
    case 'http://vedicastrology-prognosis.blogspot.in': case 'http://sitarampv.blogspot.in':
    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    break;
}
header('Content-Type:application/json');

mentioned above code snippet allows  cross AJX POST on server side .  Access-Control-Allow-Origin talks out origin makes XSS calls to server . Access-Control-Allow-Methods talks about methods those are allowed . 

Client Code ajax.js
-----------------------



var sc=document.createElement("script");
sc.src="http://code.jquery.com/jquery-2.1.1.min.js";
document.head.appendChild(sc);
      function doMe(){


$.ajax({
    type: 'POST',
    url: 'http://www.teknosys.in/sample/ajax.php',
    crossDomain: true,
    data: 'url='+window.location.href,
    dataType: 'json',
    success: function(responseData, textStatus, jqXHR) {
        var value = responseData.foo;console.log(responseData);
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
}); 
}

window.onbeforeunload = confirmExit;
function confirmExit(){
doMe();
    alert("confirm exit is being called");
    return false;
}


window.onbeforeunload makes a call to server and POST some data like context path .



Happy Learning ...!


Comments

Popular posts from this blog

[Inside AdSense] Understanding your eCPM (effective cost per thousand impress...