Vote Up 0 Vote Down

cross domain ajax request using jquery

How we can make possible cross domain ajax requests work ? Every time when I request from a remote domain url I got



an empty response. But I know that the other domain outputs some html which I can't retrieve in the client side.

      $.ajax({

type: 'POST',
url: 'http://mysite.com/mypage.php',
data: { var1: 'value1', var2: 'value2' },
beforeSend:function(){
// show something till we get the data
$('#output-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Please Wait..." /></div>');
},
success:function(data){
// after successfully getting data
$('#output-panel').empty();
$(data).find('item').each(function(i){
$('#output-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// if failure
$('#output-panel').html('<p class="error"><strong>Oops!</strong> An error occured.</p>');
}
});


Please give me a solution.
flag
edited on 2/5/12

Answers


Vote Up 0 Vote Down
Do you have access to that http://mysite.com/mypage.php. You should have because the remote url should allow the requesting domain to fetch the data by ajax.

So add the following in the header of the remote host page header (mypage.php in your case).

header('Access-Control-Allow-Origin: *');


It should then allow the requesting domain to get its data by ajax request.

For security purposes you may limit the requesting domains to some particular domain. All other domains are disallowed.

Example:

header('Access-Control-Allow-Origin: http://alloweddomain.com');
flag | link |

Your Answer

Login before answering

Login with facebook