javascriptgoogle-analyticsgoogle-tag-managergoogle-datalayerdata-layers

Parsing xhr.responseText | GTM DataLayer Push


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>


Solution

  • 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;