2

I found this great script that does the job of collecting JSON to a specific triggered area of my site.

I would like to parse xhr.responseText to collect only ID_number.

Here is the script:

<script>
(function() {
 var xhrSend = window.XMLHttpRequest.prototype.send;
 window.XMLHttpRequest.prototype.send = function() {
  var xhr = this;
  var intervalId = window.setInterval(function() {
   if(xhr.readyState != 4) {
    return;
   }
   dataLayer.push({
    'event': 'ajaxSuccess',
    'eventCategory': 'AJAX',
    'eventAction': xhr.responseURL,
    'eventLabel': xhr.responseText
   });
   clearInterval(intervalId);
  }, 1);
  return xhrSend.apply(this, [].slice.call(arguments));
 };
})();
</script>
Rafael
  • 7,605
  • 13
  • 31
  • 46
Truststy
  • 23
  • 2

1 Answers1

1

Ok, this is actually really simple, believe it or not :)

You have a JSON response in some sort of text form:

{"status":"ok","ID_number":"YE513215"}

What we need to do is to turn that into a Javascript object, so we can pull attributes from it. Javascript has built-in JSON parsing:

var response_object = JSON.parse(xhr.responseText);

We can then get the id number:

var id_number = response_object.ID_number;
Dave
  • 11,499
  • 5
  • 34
  • 46
  • @RandyCasburn there really should be a way to assign this to you since you beat me ;) but sure I'll try. – Dave Oct 17 '18 at 04:55
  • @Dave - it looks like what I am looking for. Thanks you so much! The only problem is that I am a total newbie and I am not sure how to code this the correct way. I have tried but I get errors. – Truststy Oct 17 '18 at 05:01
  • @Truststy where you would add this depends on what you want to do with the information. The code you included above looks like it modifies the usual AJAX request to send updates to some sort of data layer, but it doesn't actually make the AJAX request itself. Honestly, if you're new at this, I would very much not try and handle an AJAX request in straight javascript, it's a massive pain. Instead you could use jQuery which has a lot of helper methods. – Dave Oct 17 '18 at 05:02
  • I'd like to add the information parsed on > 'eventLabel': {ID_Number}. I'll see what I can do with this info - thanks a lot! – Truststy Oct 17 '18 at 05:05
  • Oh ok! So it should be as simple as adding to your dataLayer object `'eventLabel': JSON.parse(xhr.responseText)["ID_number"]` – Dave Oct 17 '18 at 05:07
  • @Truststy no worries man! Do me a favor and mark this as the correct answer, I need my 15 points :) (also future users will be able to know it works without reading through our comments) – Dave Oct 17 '18 at 05:13