Skip to content

Instantly share code, notes, and snippets.

@tiwariayush
Created February 15, 2021 16:56
Show Gist options
  • Save tiwariayush/f57ada7c2977a0a6ec857f807f021142 to your computer and use it in GitHub Desktop.
Save tiwariayush/f57ada7c2977a0a6ec857f807f021142 to your computer and use it in GitHub Desktop.

Revisions

  1. tiwariayush created this gist Feb 15, 2021.
    41 changes: 41 additions & 0 deletions basicMethods.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@

    //Send a request
    //Must send methid as a string, url as a string, data as an object, headers as an array of objects
    window.sendRequest = (method,url,data,headers) =>{
    let xhr = new XMLHttpRequest();

    let json = JSON.stringify(data);

    xhr.open(method,url);

    if (method == 'POST'){
    xhr.setRequestHeader('Content-type', 'application/json');
    }

    for (h in headers){
    header = headers[h];
    xhr.setRequestHeader(header.key, header.value);
    }

    xhr.send(json);

    xhr.onload = () => {
    if (xhr.status != 200) { // analyze HTTP status of the response
    console.log(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
    }
    return;
    };

    }

    //Base64 Encode data
    window.base64Encode = (data) => {
    let encodedData = window.btoa(data);
    return(encodedData);
    }

    //JSON Encode data
    window.jsonEncode = (data) => {
    let encodedData = JSON.stringify(data);
    return(encodedData);
    }