aemie aemie - 6 months ago 103
jQuery Question

XMLHttpRequest cannot load for instagram like

I want to call this link for the like on instagram, I am using following code but it is not working. Following error comes, please help me how I call this url from local host and server also.

var likeurl = "https://api.instagram.com/v1/media/" + idslist[1] + "/likes?ACCESS_TOKEN=" + accesstoken;
Nextin_downloadData(likeurl);
$.ajax({
url: likeurl,
type: 'POST',
data: {

},
success: function (result) {
alert("out" + result);


},

error: function () {
alert("error");
}
});

Error : XMLHttpRequest cannot load https://api.instagram.com/v1/media/714346267865083830_540073674/likes? ACCESS_TOKEN=1281148571.506af84.fc2e95e7257fdhgu5thca. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:2356' is therefore not allowed access.

Answer

Unfortunately, this is instagram-side restriction. You should use therefore server-side queries. Browser blocks cross-domain request because in the return there is no Allow-origin header. I recommend to read more on CORS to fully understand this problem.

For example if you're using PHP backend, this is the solution:

Backend:

<?php
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL,"https://api.instagram.com/v1/media/" . $_REQUEST['id'] ."/likes?ACCESS_TOKEN=" .$_REQUEST['token']);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'out'.$_REQUEST['data']);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);

Frontend:

$.ajax({
    url: "path.to.backend.php",
    type: 'POST',
    data: {
        id:idslist[1],
        token:accesstoken,
        data:{}
    },
    success: function (result) {
        alert("out" + result);
    },

    error: function () {
        alert("error");
    }
});