Jean Manzo
Jean Manzo

Reputation: 123

Translate curl to Javascript ajax code

How can I translate this curl script to an AJAX request in JavaScript?

curl -X POST
     -d "grant_type=password&username=admin&password=Demo1234"
     -u "<ClientID>:<ClientSecret> " http://<host>/url/to/auth

Upvotes: 2

Views: 440

Answers (3)

Ahmed Musallam
Ahmed Musallam

Reputation: 9753

Here is how you can do it for any curl not just this one:

  1. Get postman (https://www.getpostman.com/)
  2. follow this to import your curl to postman: https://www.getpostman.com/docs/postman/collections/data_formats#importing-postman-data
  3. follow this to generate a code snippet for the curl you just imported: https://www.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets

one of the code snippet exporters is jqueryAjax.

Upvotes: 1

Giulio Bambini
Giulio Bambini

Reputation: 4755

I will show an example in pure JavaScript

function sendData()
{
    var formData = new FormData(); //create formData object to send data
        formData.append("grant_type, "password"); //via append you add data 
        formData.append("username", "admin"); 
        formData.append("password", "Demo1234");
    var xmlHttp = new XMLHttpRequest(); //create "ajax/xhr" object
        xmlHttp.onreadystatechange = function() //monitor status of response
        {
            if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //if it's ok
            {
                console.log(xmlHttp.responseText); //then output data
            }
        }
        xmlHttp.open("POST", "http://<host>/url/to/auth"); 
        xmlHttp.setRequestHeader("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>");
        xmlHttp.send(formData);

}

Upvotes: 3

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Your curl call uses three things:

  1. Unprocessed data.
  2. HTTP Authentication.
  3. Templating? - Not sure.

This is what I best came up with:

$.ajax({
  "url": "http://<host>/url/to/auth",
  "data": "grant_type=password&username=admin&password=Demo1234",
  "processData": false,
  "beforeSend": function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>"));
  }
});

Replace your <ClientID> and <ClientSecret> with the right values.

Upvotes: 2

Related Questions