On our site, the <body> tag holds various data-*="*" attributes:
<body data-someData="someValue" data-someOtherData="someOtherValue">
I need to get the values of these attributes while on other pages. So, I am using jQuery AJAX $.get to get the page's HTML, and thus these data attributes.
My current script:
// The call (used on different pages)
var stock = getProductData('stock', '/some/product/url');
// The "GET" function
function getProductData(type, url) {
var jqxhr = $.get(url, function( data ) {
console.log('Data found!');
var $body = $(data).find('body');
var val = $body.data('stock');
console.log('Returning Value: "' + val + '"');
return val;
}).done(function(){
// Request is complete
console.log('getProductData Finished...');
}).fail(function(){
console.error( 'getProductData: ' + type + ' = FAIL / URL: ' + url);
});
}
So, what's the problem? Well, the $(data).find('body').data('stock'); is coming back as undefined. I also tried $(data).find('body').attr('data-stock');, but it returned the same thing.
So, how can I return the body tag's data-someData="someValue" attribute values using $.get?
The data-stock attribute used in the example above looks like this on my product page:
<body data-stock="3">
EDIT: Not a duplicate: this question refers specifically to the parsing of specific attributes of elements. I am not asking how to just return the data using AJAX.
Okay, so the short answer is that you are not able to reference data attributes inside the
<body>tag in this way. Thus, you are not able to usevar productData = $(body).data('someData');. jQuery evidently does not pay attention to the body tag when using$.ajax- even if the returned data is referenced as an object.What you can do is:
After doing this, you can then reference data attributes in your ajax requests.
There was one other thing I was doing wrong in my OP... My ajax request function kept returning 'undefined'. This was because the variable was being used externally before the ajax request was complete. So the
return val;did not return anything until after the scripts that used the stock variable were done using it.So, I had to use a callback and rework my script a little bit, but now everything works fine...
So- bottom line: you cannot return .data() from the body tag, but you can from other tags inside of the .
For anyone needs some help with this, here is my script (that works)...
The Call
The AJAX Request