I need to get th" /> I need to get th" /> I need to get th"/>

How to get .data() using jQuery $.get (or $.ajax)

1.2k views Asked by At

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.

2

There are 2 answers

0
Derek Foulk On BEST ANSWER

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 use var 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:

  • Move the data attributes to a hidden input (or any other tag inside the )

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

// Needed for use inside AJAX request
var $el = $(this);
var url = $el.data('url');

// List Stock
getProductData('stock', url, function(val) {

  var stock = val;
  var str;
  var cls;

  if ( stock > 0 ) {
    str = stock + ' ' + 'In Stock';
    cls = 'in-stock';
  } else {
    str = 'Out of Stock';
    cls = 'out-of-stock';
  }

  $el.find('label.stock').addClass(cls).text(str);

});

The AJAX Request

// Get data from the product page
function getProductData(type, url, callBack) {

  $.ajax({
    url: url,
    method: 'GET',
    dataType: 'html',
    success: function(data){

      var $data = $(data).find('#product-data');

      var val = $data.data(type);

      return callBack( val );

    },
    error: function(data) {
      console.error( 'getProductData: ' + type + ' = FAIL / URL: ' + url );
    }
  });

}
2
dmeglio On

Let me suggest perhaps a crazy idea... You provided a sample url of: var stock = getProductData('stock', '/some/product/url'); So is the file on the same domain? If so, what about loading it into a hidden iframe and then accessing the iframe's document property? That won't work though if the content is on another domain for security reasons. If it's the same domain, then window.frames["framename"].document would give you the contents of the IFrame if I'm not mistaken.