0

Here is what I have come up with this far: I am getting nothing in the console.log that I am trying to print; although no errors either. My goal is to handle an ajax request (multiple later) with vanilla javascript (ES6).

  function loadJSON(callback) {   
    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'https://www.website.com/wp-json/acf/v3/options/options', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
 }
  function init() {
    loadJSON(function(response) {
    // Parse JSON string into object
      var actual_JSON = JSON.parse(response);
      console.log(response)
    });
  }
});

Here is what my website ../options... file looks like:

{"acf":{"1yr_short_copy":"<p>Our 1 Year Money Back Guarantee either leaves you 100% satisfied,....

So, for instance - I just want to grab field 1yr_short_copy text data and print into html div. I know this is incredibly easy with jQuery; but I am not able to use jQuery on current application - so am seeking a Vanilla ES6 technique.. Any thoughts?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Dr Upvote
  • 8,023
  • 24
  • 91
  • 204
  • You need to set the `responseType` on `xobj` to `text` if you want to use `responseText`. Or use `json` if you want to get a JavaScript object in `xobj.response` and not have to use `JSON.parse`. See [Using XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest). However, you may want to look into using the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) instead. – Heretic Monkey Sep 17 '19 at 18:55
  • 2
    Yeah, if you're not worried about IE compatibility, use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). – Tom Faltesek Sep 17 '19 at 18:56
  • did you try testing in postman? i can't get a response from your server. no 400, no 500, no auth error, just a complete no go. – sao Sep 17 '19 at 19:02
  • @HereticMonkey thank you; this makes sense. Where exactly do you mean? – Dr Upvote Sep 17 '19 at 19:21
  • You set the `responseType` some time before you read the response. I usually do it when I set the MIME type header as they're related in my head. – Heretic Monkey Sep 17 '19 at 19:23
  • May; just use the 'fetch' - looks like anything is way more code then I want to use. – Dr Upvote Sep 17 '19 at 19:23
  • As you want to work with ES6, also consider [How do I promisify native XHR?](https://stackoverflow.com/q/30008114/1048572) – Bergi Oct 06 '19 at 15:32

3 Answers3

1

you may want to use onsuccess method. Its an another prototype of XMLHttpRequest class that works after response has turned.

const text = document.querySelector("#paragraph")

xobj.onsuccess = () => {
    const response = JSON.parse(xobj.responseText);
    text.textContent = response.acf.1yr_short_copy;
}
Teoman Tıngır
  • 2,766
  • 2
  • 21
  • 41
0

also you can do this

async function ajaxRequest(id) {
  const response = await fetch(`url/${id}`, options); //here is where you do a ajax call
  const json = await response.json(); // here you manage the response

  return json;
}
Joaquin
  • 49
  • 5
  • Thanks; I have tried that with the below: async function ajaxRequest(id) { const response = await fetch(`https://www.website.com/wp-json/acf/v3/options/options/${id}`, options); //here is where you do a ajax call const json = await response.json(); // here you manage the response return json; console.log(json); } }); -- Nothing outputs in the console log. – Dr Upvote Sep 17 '19 at 19:19
  • @CaptainRon You don't have an id in your URL, so don't add it. Joaquin was not kind enough to alter his example to fit your use case. – Heretic Monkey Sep 17 '19 at 19:25
  • Was a example, i give another way to do a ajax call (with fetch), and im not so sure to understand what you say. Sorry – Joaquin Sep 17 '19 at 19:56
0

Half of the object innit is missing ;) Note this is as SYNCHRONE routine. Somehow you can not use post with this type of call so far i saw. Async would work but tend then to get complicated. This will fetch any kind of file from the server. I use it inside a small template engine to include html breadcrumbs or even more templates. By this a async function would be a nightmare.

function axget(url) {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState === 4 && this.status === 200) {
                        // Typical action to be performed when the document is ready:
                        return this.responseText;
                    }
                }
                ;
                // the false below means synchron and works only together with GET 
                xhttp.open("GET", url, false); 
                xhttp.send();

                // by a synchrone funtion we can get the result here
                var src = xhttp.responseText
                if (src === "") {
                    console.log("ERROR AXGET: INVALID OR EMPTY ! " + url);
                }
                return src;
            }

But i just can guess, thats exactly what you may need :) But note this will block until this function get the server answer.

Same thing in asynchrone

        //writes something inside the document 
        function simplewriter() {
            console.log("Hi i am here !!!!");
            doc = new DOMParser().parseFromString(this.responseText, "text/html");
            document.getElementById(this.id).innerHTML = doc.body.innerHTML;
            this.onload = "";
        }
    //inputdata means some kind for serialized input from a form for example  
    function axg(
                  url, //should be clear
                  inputdata, //serialized datat to be processed by php or whatever
                  execfunc, // the callback function
                  method, //get or post
                  async)  // should be set to true  - its just for testing here
            {
            if (typeof url === 'undefined') {
                return;
            }
            if (typeof async === 'undefined') {
                async = true;
            }
            if (typeof method === 'undefined') {
                method = "GET";
            }
            if (typeof data === 'undefined') {
                inputdata = "";
            }

            xhr = new XMLHttpRequest();
            if (typeof execfunc !== 'undefined') {
                 // here we have to provide a callback function
                 // e.g. the simple writer for example  
                xhr.onload = execfunc.bind(xhr);
            } else {
                return xhr.responseText;
            }
            if (method !== "POST") {
                xhr.open("GET", url, async);
            } else {
            xhr.open("POST", url);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send(inputdata, async);
            }
        }

the code will continue without any delay and it will look like this function would not be there . That is why the callback is needed. Sooner or later on the server answer this callback function will be called. But it means also that it will break your serial code flow. And you will see no result until the server answered. And imagine the fun if you want depending on that answer anoter asyncronous function... Callback nightmare. That is the reason why i do not use it on my simple template system.

Have some fun :)

Thomas Ludewig
  • 696
  • 9
  • 17