Link to home
Create AccountLog in
Avatar of Tim Brocklehurst
Tim BrocklehurstFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How to get past the CORS No 'Access-Control-Allow-Origin header' error with jQuery.ajax ?

How to get around the jQuery.ajax CORS and Jsonp callback problem?
I'm writing a solution in a WordPress plugin which requires an api GET call, and will later require POST too, from JavaScript.
My initial attempt resulted in a CORS policy block:
Access to XMLHttpRequest at 'https://app.xxxxx.com/api/pub/v1/contacts/528a34f9-dbc1-4c50-ad6b-a9f300e19ea9' from origin 'https://www.xxxx.co.uk' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Open in new window


This is what the jQuery looked like:

function generateCandidate(cuid){
    console.log('Generating New Candidate');
    var api = my_api()
    var candUrl = "https://app.xxxx.com/api/pub/v1/contacts/" + cuid;
    var da = {
        api_key: api,
    }
    jQuery.ajax({
        url: candUrl,
        data: da,
        type: "application/json",
        method: 'GET',
        success: function(resp){
            console.log(resp);
        },
        error: function(err){
            console.log('Ajax ERROR:');
            console.log(err.toString());
        }
    });
}

Open in new window


So I did some research and discovered plenty of people were getting around the CORS issue by specifying the 'jsonp' type instead of json. So I tried replacing
        type: "application/json",

Open in new window

with
dataType: 'jsonp',

Open in new window


But then I discovered I need to specify a callback somehow, because the error I get is this:

jquery.js?ver=1.12.4:4 GET https://app.xxxx.com/api/pub/v1/contacts/528a34f9-dbc1-4c50-ad6b-a9f300e19ea9?callback=jQuery1124036525732914578746_1550866428904&_=1550866428905 net::ERR_ABORTED 404

Open in new window


I've read about how the callback can be sent to a function, and handled that way to make it work. But I can't find out what the function should do, or how to write it.
And I'm not sure if that's what I should be doing anyway, or if there's any way I can solve the CORS problem in a way it can be used publicly, and not just in my own browser.

Can anyone assist, or point me in the right direction to get this solved.

Many thanks
Tim
Avatar of David Favor
David Favor
Flag of United States of America image

The only way to "get past" this type of problem is for the owner of the asset being accessed to ACL the asset to the consumer of the asset has privilege to access the asset.

Only the asset owner can accomplish this action.
Avatar of Tim Brocklehurst

ASKER

Thanks for your response David...
Yes I'm sure 'get past ' is the wrong term for solving this issue.

I'm struggling to understand the rest of your answer though I'm afraid. I do have an api key for the resource (or do I mean asset?) And I'm adding that in the data passed through Ajax.

Are you able to see whats wrong with my code or should I provide more info?

I have written numerous successful Ajax calls to api resources in the past but I'm still trialling this particular one, and need to get it working before I can proceed.

Thanks again
Best wishes
Tim
Hi Tim,

I need some more information before I attempt to answer. The jquery call you are trying to make is it going to be hosted on the same domain or on some other domain?

Regards,
Chinmay.
Thanks Chinmay
The call uses an api key to access data on another domain than the one hosting the request.
Tim
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
OK - wow... thanks for that.
I've only ever called foreign data via ajax by javascript.  But will try this method using PHP now.
Will revert on how it works for me...

Many thanks
You said, "I do have an api key for the resource (or do I mean asset?) And I'm adding that in the data passed through Ajax."

Tip: Always get API code working using curl, or something similar, before you attempt with AJAX.

If you use curl, many times some minor problem will pop up to solve first... which will be difficult to impossible to even determine if you start with AJAX.
YES! - thank you...
That is the answer to EVERYTHING!  (or at least, for the time being).
It works.

Thank You @leakim971  you're a star!

User generated image
Thank you leakim971 -
Your explanation of how to use php from javascript, instead of going via javascript directly (which I had been) is a HUGE help.
Thanks also to David and Chinmay for taking the time to help with this.

Very glad to get the solution so quickly.
you're welcome, have a nice week-end!