0

I have built a Wordpress site and am trying to make an ajax post to an API on a page template.

I have spend the better part of a day researching this and have tried editing server mod_header, htaccess,

header("Access-Control-Allow-Origin: $http_origin");

On the top of the template page, etc..

I have even tried the cors-anywhere proxy but am unable to pass the api-key and app-id through it and am getting a 422 code.

This is a very simple ajax post, but no matter what i try I can't get past the Access-Control-Allow-Origin error.

$.ajax({
        url: queryURL,
        type: 'POST',
        headers: {
            'x-requested-with': 'xhr',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-Api-Key':'zyx',
            'X-App-Id':'5'
        },
        data: JSON.stringify({sendThis}),
        dataType: 'json',
        contentType:"application/json",
        crossDomain: true,
        crossOrigin: true,
        success : function(data){
                console.log(data);
                alert('ajax success');
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
                alert('There was an error.');
        }
});

This is what my post data would look like:

var sendThis = {
        "customerNumber": "000013",
        "attention": "Test Testing",
        "email": " test@testing.com ",
        "comment": "This is a testing comment",
        "sidemarks": "Do not ship this order",
        "enteredBy": "Testy Tester",
        "items": [
            {
            "itemNumber": "AH115",
            "quantity": 1
            },
            {
            "itemNumber": "AH116",
            "quantity": 1
            }
        ],
        "shipTo": {
            "name": "Testy Testing",
            "address": "This is address 1",
            "address2": "This is address 2",
            "city": "Anywhere",
            "state": "NY",
            "zip": "06850",
            "country": "USA",
            "attention": "Test"
        },
        "rushOrder": true,
        "shipperNumber": "0123456"
 };

But still no luck, so looking for help to get a successful post to the api endpoint and pass through the api-key and api-id.

  • Quik thought: what if you set `access-control-allow-origin` to "*" as a test? If it works, issue would be in how you got the allowed domain listed. Also [this thread](https://stackoverflow.com/questions/6114436/access-control-allow-origin-error-sending-a-jquery-post-to-google-apis) may prove helpful. [Or this one](https://stackoverflow.com/questions/10692866/jquery-ajax-post-says-xxx-not-allowed-by-access-control-allow-origin). – uncleoptimus Apr 13 '18 at 01:37
  • I've set the header to header('Access-Control-Allow-Origin: *'); with no luck. I've also tried in Apache # Always set these headers. Header set Access-Control-Allow-Origin "*" – Matthew Duplinsky Apr 13 '18 at 12:51

0 Answers0