Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Ajax POST not working with MailChimp

I have the following code I am using to send data to a MailChimp Newsletter List (API v3). Everytime I remove the type: POST from the function it attempts to post the data via GET and it sends the data properly (ok response in MailChimp API dashboard). When testing this in the browser (FF) I get a .part file with "true" response.

   $(function(){
     $("a#test").click(function(e){
       e.preventDefault()  
       data = {
         "apikey" : "667378947", 
         "id" : "90298590285", 
         "email_address" : "[email protected]", 
         "output" : "json"
       }

  $.ajax({ 
    type: "POST",
    url: 'http://us2.api.mailchimp.com/1.3/?method=listSubscribe',
    data: data,
    success: function(data){
      alert(data);
    },
    error: function(){
      alert("err");
    }
  })       
 });
});   

Im pulling my hair out on this one, any insight is greatly appreciated.

Thanks in advance,

JN

like image 409
jeffreynolte Avatar asked Mar 04 '11 00:03

jeffreynolte


2 Answers

There is an undocumented endpoint that uses JSONP to do cross-domain ajax requests.

Just change 'post?' to 'post-json?' and add '&c=?' to the end of the standard url to get the JSONP endpoint. This doesn't requires the API key to be exposed on the client-side, or the creation of a server-side view.

I wrote a jQuery plugin that uses this method, if that's useful at all

https://github.com/scdoshi/jquery-ajaxchimp

like image 73
sid Avatar answered Sep 28 '22 04:09

sid


The main issue is what jc commented on your original post - this simply won't work due to Same Origin Policy issues. Firebug is not as vocal about why the GET call fails, but that's why it returns no data. If you watch that with the POST, you'll see Firefox doesn't even make the call. Chrome's js console on the other hand straight explains the Same Origin policy to you.

All in all, this is a very good thing if for no other reason than it prevents you from publicly publishing your account's API Key, which is a very bad thing to do. If the reason why doesn't immediately sink in, go read through the large number of methods available in the API and then realize that all you need to access them is that API Key.

The correct way to do this is to POST data back to your server, then make the request from there. There are several fully built PHP examples (one using jquery, even), here.

like image 25
jesse Avatar answered Sep 28 '22 03:09

jesse