user3736648 user3736648 - 7 months ago 181
Javascript Question

Convert curl code to ajax

I am writing some code to update Credit Card details for Credit Cards that are stored on Stripe in a MVC 5 view.

Here is an api reference:

https://stripe.com/docs/api/curl#update_card

The reference is using curl. Am I correct in saying that I can make an ajax call to the curl url and it will achieve the same result as using curl?

May I have some help to convert the curl code into an ajax call?

Here is the curl code:

POST https://api.stripe.com/v1/customers/{CUSTOMER_ID}/cards/{CARD_ID}

curl https://api.stripe.com/v1/customers/cus_5iRk16Lkf8knHW/cards/card_15X158B0kSXRxQJDzHdigbYq \
-u sk_test_Z8pMCKSd34P8XLzrcbumkGZo: \
-d name="Jane Austen"


Here is what I have so far:

function testAjaxFunction()
{
$.ajax({
type: "POST",
async: true,
url: 'https://api.stripe.com/v1/customers/cus_5iSot8lwZQS8ra/cards/card_15X1t6B0kSXRxQJDKmdGdLTC',
data: {
'name': "Jane Austen"
},
dataType: "json",
error: function (data) {
alert("error");
alert(data);
},
success: function (data) {
alert("success");
}
});
}


This code above returns an error.

What does the
-u sk_test_Z8pMCKSd34P8XLzrcbumkGZo: \
need to be coded to for the ajax request?

Thanks in advance.

Answer

It won't work with an AJAX call alone. Replace alert("error"); with alert(data.statusText); and you'll see it was blocked by cross-domain policy. If you have this working from your server via curl, you can create an API for yourself to make AJAX calls to. The API would be a web interface to your curl call, and you could POST your AJAX calls to it. Your AJAX call would look more like:

$.ajax({
    type: "POST",
    async: true,
    url: '/api/stripe/',
    data: {
        'name': "Jane Austen",
        'customer_id': "cus_5iSot8lwZQS8ra",
        'card_id': "card_15X1t6B0kSXRxQJDKmdGdLTC"
    },
    dataType: "json",
    error: function (data) {
        console.log(data);
    },
    success: function (data) {
        console.log(data);
    }
});