Show JSON result via Ajax

Asked

Viewed 416 times

0

I don’t have much knowledge in javascript, but I need to integrate a payment API.

I’ve never performed integrations with an API before.

Following the documentation I saw you need to first generate a transaction token.

So I have this code:

function GeraToken() {
    var base64 = $.encodeBASE64(AppKey:CHAVE, Signature:ASSINATURA);

$.ajax({
    url: "http://desenvolvimento.intermeio.com/api/v2_1/Token/Gerar",
    headers: { "Authorization": "Intermeio " + base64, Content-Type: application/json },
    type: "POST",
    crossDomain: true,
    dataType: "json",

    success: function () {
        alert('FOI');
    },
    error: function (xhr, status) {
        alert('NAO FOI');
    }
});
}

Where the Geratoken() function is a button that calls.

But I wanted to make sure the call was correct. When I click the button it does not return me either of the two Alerts. The most ideal would be to return me on the screen even the token, just to see even if it worked, because I need to store this token in the database. In the API it says that the return will be in JSON.

Could someone help me?

Grateful from now on!

  • If it does not return either of the two Alerts, it is probably not running this ajax. Confirm the execution by observing the "Network" tab in the "Developer Tool" of your browser, or place an Alert/console.log before running ajax to make sure it has passed there

  • In the console appears the message: Uncaught Referenceerror: Geratoken is not defined at Htmlanchorelement.onclick The strange thing is that if I delete everything from the Geratoken() function and leave only one Alert() inside it, only to see if it enters the function. Then Alert() runs. But if I put the ajax code it gives this error on the console

1 answer

2


Hello,

From what I’ve analyzed and what you put in the comment, your function is probably syntax-deficient. It seems that in the property "headers", the sub-property "content-type" and its value are without quotes, try so:

function GeraToken() {
    var base64 = $.encodeBASE64(AppKey:CHAVE, Signature:ASSINATURA);

$.ajax({
    url: "http://desenvolvimento.intermeio.com/api/v2_1/Token/Gerar",
    headers: { "Authorization": "Intermeio " + base64, "Content-Type": "application/json" },
    type: "POST",
    crossDomain: true,
    dataType: "json",

    success: function () {
        alert('FOI');
    },
    error: function (xhr, status) {
        alert('NAO FOI');
    }
});
}
  • I did it this way, but it falls into the error function. The strange thing is that when I test the REST client using these same credentials it returns status 200. :/

  • Before I tested it this way he was showing error in the hyphen of Content-Type, because it was without the quotation marks... anyway his answer helped. Thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.