troubleshooting Question

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

Avatar of Tim Brocklehurst
Tim BrocklehurstFlag for United Kingdom of Great Britain and Northern Ireland asked on
* Cross-origin resource sharing (CORS)JavaScriptjQueryAJAXJSON
10 Comments1 Solution618 ViewsLast Modified:
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.

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());
        }
    });
}

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",
with
dataType: 'jsonp',

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

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
ASKER CERTIFIED SOLUTION
leakim971
Multitechnician
Join our community to see this answer!
Unlock 1 Answer and 10 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 10 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros