0

I have recently started working with js outside the DOM and now I face the ajax calls, which I don't seem to quite build/use. I need to send and retrieve info to and from an API, at first, coding the GET call was easy: I started with cURL and php but ended using ajax calls, this was not so complicated since all the examples I found were more or less the same. Even so, I could not figure out how to send my user/pass along the call so the API would let me access the info I was looking for.

I decided to let that rest and to start coding the rest of the calls, to return to the credentials issue once I had finished, but when it came to the POST calls, every example I saw was very different from the previous one and I could not find any solution to my problems, so my POST call is more of a mix of everything I have read and in the end, none have solved my issues nor make me grasp exactly how they work.

I will be omitting variables storing username, password and url, but they are properly declared and filled with the correct data.

My issues are as follow: -I am not sure about the structure the ajax POST call must follow. As I said, GET calls are much more uniform, but every POST example I see, varies a lot from the others.

-Is the 'data:{' field filled correctly?

-Once again, I have seen a lot of ways to send access credentials, I tried many but I still get 401. I am also getting CORS policy error since I am in localhost. Is that the reason I am getting the 401? Is it because the 'headers:{' field is wrong written?

-Lastly, at first I started using success for the response, but after searching a while I learned the method was deprecated and replaced since with .done and .fail. I could not find any better example than the one i am attaching (which I copied), but I don't understand where do some parts come from since It was not explained:

  1. Where does successFunction(data) come from? Is there anything I have to add to this?

  2. Do all the parameters from .fail(function( come as the response? Is there anything I have to do with them? Do both functions work as they are?

And finally, If you see any other thing I have done wrong or I could improve, I will be glad to hear!

--QUICK NOTES--

Since I didn't know how they work, I left the success function for the GET call.

--CODE--

[GET] - The call works, but I am getting the 401 all the time.

<!DOCTYPE html>
<html>
<head>
    <title>FETCH CUSTOMERS</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<body>


<script type="text/javascript">
    function callAPI(){
        $.ajax({
            url: url, 
            type: "GET",
            headers: {
                "Autorization": "Basic" + btoa(username+":"password)
            },
            success: function(response){
                $("#respuesta").html(response);  
            }
        });
    }
callAPI();
</script>

<h1 id="resultado" style="text-align: center;"></h1>
<div id="respuesta">

</div>
</body>
</html>

[POST]

    $("#submit1").onclick( function postAPI() {
      var contactEmail = $("#formContactEmail").getValue();
      var contactResellerId = $("formContactResellerId").getValue();

      $.ajax({
        url: url, 
        type: "POST",
        data: {
            email: contactEmail,
            reseller_id: contactResellerId
        },
        dataType: "json"
        headers: {
            "Autorization": "Basic" + btoa(username+":"+password)
        } 
      })
      .done(function (response) { successFunction(data); })
      .fail(function (jqXHR, textStatus, errorThrown) { errorFunction();

    });

Thank you all for your help. I know there are many questions about ajax calls and ajax structures, but none have answered my questions. Please, if you are able, don't just post the answer as many do, I would like to understand why that is the solution!

----EDIT----

After reading and searching more, I was able to verify my calls as correct (after correcting some errors). Using postman while the ssl certificate check was deactivated showed that the calls are working.

I don't know if I should open another question, since the original purpose for this one was to verify that my code was right, which now I know it is, but the main issue now lays in the CORS Policy blocking all my requests.

Whenever I try to send a request outside postman, 401 Error (Unauthorized) appears, along another message explaining that because of cross-origin, my requests are being dismissed:

Error Response in console

I read that you can't comunicate with APIs if you are located in localhost, but the software I am working on is intended for that purpose, meaning I need some way to make it work from localhost.

I don't want to set the Access-Cross... to '*', is there any other, more secure, way of achieving this?

Thank you all again!

Berny
  • 121
  • 14
  • 1
    `username` and `password` are attributes of the ajax settings, you should use those for authentification or didn't those work? – user3154108 Jan 09 '20 at 10:36
  • Yeah, I omitted the variables for security purposes, but they are properly filled, as url is. When you say they are attributes, do you mean I should put them outside of headers:? dataType: "json", username: username, password: password }) I have seen some people doing it like this too, but that doesn't worked for me either. – Berny Jan 09 '20 at 10:42
  • Yes. if you check out the definition of the settings object here https://api.jquery.com/jQuery.ajax/ you can see username and password appear as attributes the same way dataType or headers do. jQuery puts the request together with the authetification then. The headers can add nonce or crossorigin settings. – user3154108 Jan 09 '20 at 10:45
  • I see! Thank you, I tried before but still got 401. I now assume this is due to CORS policy error. I have been searching and I found headers: { 'Access-Control-Allow-Origin': 'http://site allowed to access' } Will adding this header prevent the CORS error I am getting? – Berny Jan 09 '20 at 10:58

0 Answers0