How to implement a get request and set a parameter through a function?

  • 0
    Hello everybody.
    The task was as follows: get data through a get request using js.
    Works only through shim because it swears at CORS. I could not decide otherwise. I did it through hosting as well. Does not help. But oh well.

    Wrote a function that should receive parameters (which key to pull out, is there a separator, if there is a separator, then get the position)
    function parseDateFromGererator(param,separator=false,position) {
            var xhr = new XMLHttpRequest(),
                method = "GET",
                url = "";
  , url, true);
            xhr.onreadystatechange = function () {
                if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                    response = JSON.parse(xhr.responseText);
                    if (separator) {
                    else {
                    console.log('name -' +param + ' surname -' + surname)

    But I do not know how to get from response my param, which I pass through the function
    generateButton.addEventListener("click", function () {
            name.innerHTML = parseDateFromGererator(param="name",separator=false,0);

    Writes undefined. Hope I explained correctly and someone can help or fix the function.
    Here is a live example
    JavaScript Anonymous, Feb 13, 2019

  • 2 Answers
  • 0

    1. Don't use XMLHttpRequest. Simply. no need.

    2. The parseDateFromGererator function should return something. In your case, some data.

    3. response.param - you are looking for the "param" field in the response. To use a variable you need the following syntax: response [param].

    If you want to figure it out, here's an example:


  • 0
    1) responce has no param property

    2) Your function returns nothing

    3) ajax requests are asynchronous, so name.innerHTML must be added to the callback

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!