Mailchimp how to call mailchimp 3.0 API in javascript - javascript

I am trying to subscribe an email to a list on mailchimp, I followed the documentation first, made a request using "Postman" added what was needed and everything works just fine, so I tried to do it on my website and it didn't work
I tried to made a simple request with the same values I set on postman, but everytime I try to send the request the response says
XMLHttpRequest cannot load
https://us12.api.mailchimp.com/3.0/lists/xxxxxx/members. Response
to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://mywebsite.com' is therefore not allowed
access. The response had HTTP status code 501.
I tried to find a way to overcome this but it has been impossible
I searched on stackoverflow everybody says to use jsonp or add something to the ajax call or use a mailchimp ajax plugin nothing has worked
I tried diferent stackoverflow posts like this one
Mailchimp subscribe using jQuery AJAX?
but almost all of them say the same
I tried cache: false dataType:jsonp crossDomain: true xhrFields: {withCredentials: true}
Here it is my code, I am using Jquery
$.ajax({
type: "POST",
url: "https://usxx.api.mailchimp.com/3.0/lists/xxxxxxxx/members",
data: { "email_address":email#adress.com, "status":"subscribed"},
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==",
"Content-Type": "application/json"
},
success: function(data){
alert('Thanks for subscribing');
},
error: function(data){
alert('there was an error, try again later');
}
});
I also Thought on creating my own api and then make the call to mailchimp api but I might ran into the same problem
Do you have any suggestions?
Thanks in advance

As charliefl noted, this is a CORS issue. MailChimp doesn't support CORS, mostly because it would require you passing your API credentials to the user of the webpage, allowing them to takeover your entire account.
Your two options for MailChimp are to proxy your requests through a server or, for signing people up to your list, you can build a custom signup form that uses a much more restricted API. The caveat of this second method is that it forces all of your subscribes through MailChimp's double opt-in process.

Related

Javascript/JQuery Send custom header in OPTIONS Preflight API

Code dump:
$.ajax({
type: 'GET',
dataType: 'json',
url: api,
xhrFields: {
withCredentials: true
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic [my auth token]");
},
success: function(jd) {
console.log(jd.stringify());
}
});
The problem is that Chrome and Firefox send an OPTIONS preflight when I include a beforeSend, however that OPTIONS request is refused by the API because it doesn't know how to handle an OPTIONS request and treats it like a GET, sees no Authorization header and refuses the request.
The only way I can get this to work is to coerce the browser either to not send an OPTIONS request or include my header with it. I am unable to modify the API that I am using.
I would appreciate it if anyone could advise me.
The reason why browser sends preflight request is that you are using custom headers. Please. read about how to avoid preflight request (content type should be text or html and no custom headers)
If you could not chagne server side the last chance to make it work is to create your custom proxy (for example you can create node server and that node app would take your requests and forward them to those Api Then you will have you own server even in the some domain and this proxy server will send CORS requests to another server domain.

How do I enable CORS?

I am unable to enable CORS on any resources from AWS Api Gateway.
I used the "Enable Cors" button present on the web UI:
But attempting to use in development or production yields:
I'm using jQuery 2.2.4 and the method $.post.
What's going wrong?
UPDATE: test staging:
SUCCESS UPDATE:
AWS documentation can be quite large. What I failed to realize is that you must EXPORT a client generated SDK which has a global variable that generates methods based on the resources you provided. As such, I can FINALLY return a succesfull result when I use THIS code:
const apigClient = apigClientFactory.newClient();
apigClient.purchaseTokenPost({}, card, {})
.then(function(result){
console.log(result);
}).catch(function(result){
console.log(result);
});
I found that even for an 'unsecured' api call, i.e. one that your didn't secure with an API key (like I did to test something out), once I enabled cors it would only work if I created an API key and sent it in with the request - easy to do, may want to give it a try.
ADDL INFO:
Here is a sample jquery that worked for me after I enabled CORS on the endpoint:
function loadData() {
$.ajax({
type: "GET",
cache: false,
url: "https://k4t999edod.execute-api.us-east-1.amazonaws.com/prod/myapicall",
crossDomain: true,
dataType: "json",
headers: { 'x-api-key': 'xoeNNQ9475PCAgLtNP18cTv6YTWWB2JFfOe', 'X-Amz-Date': '1/1/2000', 'X-Amz-Security-Token': 'xoeNNQ9475PCAgLtNP18cTv6YTWWB2JFfOe' },
success: function (response) {
//do something here.
}
});
}
Note I included the API key in two places (I scrambled the real ones)
CORS seems to be setup correctly for your method. I tested with this tool:
http://client.cors-api.appspot.com/client (Enter your invoke URL, the POST dropdown, and you can confirm the success "onload" callback is triggered)
Can you try making your request with plain JavaScript to narrow down if it's an issue with jQuery? See: A CORS POST request works from plain javascript, but why not with jQuery?
Edit:
Found this on http://enable-cors.org/server_awsapigateway.html. Looks like the One-Click CORS button in API Gateway isn't compatible with jQuery:
Amazon API Gateway adds support for CORS enabling through a simple button in the API Gateway console. Unfortunately that button has a partial behavior, thus setting CORS correctly only for 200 answer (so not other HTTP status codes) and ignoring JQuery header support. The best solution considered so far is about avoding to use the CORS button and set configurations manually. This can be achieved in a couple of steps:...
(Final) Edit: This is a bug with API Gateway not applying header mappings when the integration returns an error response. This has been a known issue for quite a while: https://forums.aws.amazon.com/thread.jspa?threadID=220324&tstart=0

Howto get and post data via jQuery from JIRA REST API?

We are using JIRA 6.4.5 in our company but I am struggeling fetching data from its API REST interface. I have been trying now for the last couple of days, getting stuck on a cross-domain problem or that I don't know the user credentials so I cannot do any server-side either.
Ideally I am having a jQuery page where the user will use his own credentials/session for querying the JIRA data. The JIRA REST API is located at srv1.mydomain.xyz and I am using srv2.mydomain.xyz as my webserver with my code.
I have read the JIRA REST API Reference.
I have tried various Javascript/jQuery stuff - in the below example I am trying to submit 1h 30minutes to a specific issue:
$.ajax({
url: "https://srv1.mydomain.xyz/rest/api/latest/issue/proj-3/worklog",
dataType: "json",
method: "post",
data: { time: "1h 30m",
comment: "Test" }
}).done(function(data) {
alert("Success");
}).fail(function(jqXHR, textStatus) {
alert("Failed");
});
I get this error:
XMLHttpRequest cannot load
https://srv1.mydomain.xyz/rest/api/latest/issue/proj-3/worklog?time=1h+30m&comment=Test.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://srv2.mydomain.xyz' is therefore not
allowed access. The response had HTTP status code 401.
I then looked more in to this and saw that Atlassian has something called Atlassian Connect so I tried with this:
AJS.$.ajax({
url: "https://srv1.mydomain.xyz/rest/api/latest/issue/proj-3/worklog",
type: "post",
dataType: "json",
contentType: "application/json",
xhrFields: { withCredentials: true },
async: false,
method: "post",
data: { time: "1h 30m",
comment: "Test" }
}).done(function(data) {
alert("Success");
}).fail(function() {
alert("Failed");
});
But I get a similar error:
XMLHttpRequest cannot load
https://srv1.mydomain.xyz/rest/api/latest/issue/proj-3/worklog.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://srv2.mydomain.xyz' is therefore not
allowed access.
I have also looked in to if I could do this server-side from my PHP enabled server in the same domain as the JIRA server but as I don't get the base64 encoded credentials when doing a phpinfo() then I don't think I can use this approach either (and I don't want to prompt the user for credentials).
I am painfully aware that my problem is related to cross-domain protection but I cannot find any examples on how to fix it? It would be great if the JIRA server could set a Access-Control-Allow-Origin for certain hosts but I assume this is not a configuration option (I am not in control of the JIRA server).
This is definitely a cross-domain case. And believe me, it exists for your own protection ; )
The method I use is to send the jQuery request to a server-based processing page, which then authenticates and interracts with the Jira server. In your case, since srv1 and srv2 are under the same domain, srv2 (webserver) can talk to srv1 (Jira) using internal IPs (https://10.50.25.87:8080/rest/api/latest/issue/proj-3/worklog, for example) so the cross-domain issue doesn't apply.

Creating wallet on Blockchain with Ajax gives CORS error

I am trying to create wallet on Blockchain using Ajax but I am getting "Cross-Origin Request Blocked" error. My Ajax call is:
$.ajax({
type: 'POST',
url: 'https://blockchain.info/api/v2/create_wallet',
data: "cors=true&email="+email+"&password="+password+"&api_code="+code,
dataType:'json',
crossDomain: true,
beforeSend:function(){
},
success: function (data) {
}
});
When I post this I get error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://blockchain.info/api/v2/create_wallet. This can be fixed by moving the resource to the same domain or enabling CORS.
On Blockchain they say that Some API calls are available with CORS headers if you add a cors=true parameter to the request
I have tried everything, I have tried to send this parameter as a GET as well as POST parameter, I have tried jsonp. I have also tried with the header Access-Control-Allow-Origin * but nothing seems to be working. Can anyone confirm if he managed to create blockchain wallet using Ajax call or they don't support CORS for this. Any help will be much appreciated.
Thanks
Hamza
I think it is safe to say that blockchain does not support CORS for their wallet API.
Your AJAX call above looks correct and you are getting a CORS blocked error.
And unlike some of their other APIs, the blockchain wallet API docs at https://blockchain.info/api/blockchain_wallet_api do not specify that calls are available via CORS with the cors=true query parameter.
There are some significant security implications when dealing with private keys and passwords in the browser using javascript. I suspect that is why they do not allow it.
The solution for this is insanely simple. Just do that request on the server side and then call your server script which does that request from your $.ajax() method.

Sharing a base64 image on Twitter using javascript

I spent hours and hours to resolve this problem... but couldn't get any tutorials or examples for this. Tried to implement something but confronted terrible errors.
I'm working on client slide and it seems "POST statuses/update_with_media" in REST Api of Twitter is especially designed to share image data url, but originally, Twitter documentation is very poor and has no example codes for this. I am even not sure how to give user_secret, user_token, consumer_key and consumer_secret in ajax request. This is what I've done.
var fd = new FormData();
fd.append("oauth_consumer_key", "knC68njKLjXrRljSxhE3uywsi");
fd.append("status", "");
fd.append("media[]", base64_string);
$.ajax({
url:"https://api.twitter.com/1.1/statuses/update_with_media.json",
type:"POST",
data:fd,
processData:false,
contentType: "multipart/form-data",
cache:false,
success:function(data){
alert('Post was published.');
},
error:function(shr,status,data){
alert('Post was not published.');
},
complete:function(){
}
});
I know this is a bad try but that was all I could do. And this gives below error.
XMLHttpRequest cannot load https://api.twitter.com/1.1/statuses/update_with_media.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.101' is therefore not allowed access.
I'm running this on local php server. Any examples or tutorials for this will be appreciated.
Thanks.
I do not know about the specifics of this API call but, from a first look, you can't make an ajax call to a server different than the one your page originated from. Thus, you cannot make an ajax call to the twitter api, unless twitter supports CORS. The error message you get indicates exactly this. The only way to solve this is by making the twitter api call from your server, and then have your page make the ajax call to your server.

Categories