My WordPress application is hosted on url http://127.0.0.1/wordpress/ and i added following script in WordPress header to get some token but it does not give any token
I copied that url ( http://127.0.0.1:8090/sample/sample/getToken ) and open in new tab it successfully return token but when i called it using $.ajax it does not return me token
<script>
$().ready(function(){
$("#signIn").click(function(){
alert("Display Alert Properly");
$.ajax({
type: "POST",
url: "http://127.0.0.1:8090/sample/sample/getToken",
contentType: "text/html",
success: function(token) {
window.open("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token, "_self", ""); });
});
});
You cannot directly access external resources via Javascript due to the Same Origin Policy implemented in modern browsers. However, there are a couple of solutions.
If the remote site offers JSONP you can utilize it to load external resources, but if they don't, you will not be able to access those resources directly.
If the remote endpoint does not offer JSONP, you will need a proxy script on your own server which accepts an AJAX request, makes the request to the external endpoint, and relays the response to your Javascript app. Be sure to secure such a script well to only accept requests to blessed endpoints, or you will have a nasty security hole to contend with.
Ajax is subject to the same origin security policy.
You can read about it here: http://en.wikipedia.org/wiki/Same_origin_policy
There are workarounds for this, including JSONP
Try this and see what error you get , it will help you see the actual problem
$().ready(function(){
$("#signIn").click(function(){
alert("Display Alert Properly");
$.ajax({
type: "POST",
url: "http://127.0.0.1:8090/sample/sample/getToken",
contentType: "text/html",
success: function(token) {
window.open("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token, "_self", "");
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
});
});
May be this will help.
You need to trigger JSONP behavior with $.getJSON() by adding &callback=? on the querystring, like this:
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?",
function(data) {
doSomethingWith(data);
});
Reference Ben Everard's answer