Struggling to get my head around AJAX success scope.
I am trying to load some data from an AJAX call, then attach it using jQuery to an already existing ul
This example helped me out , but I can't work out how to reference specific elements from 'this'.
So I've passed this into the success function as that , but this line:
$('li.loading').before(nextLoad); Fails with:
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8 Im assuming , I need to use that followed my my element, but cannot work out the syntax.
var that = this; $.ajax({ type: 'GET', url: url, async: true, jsonpCallback: 'callback', contentType: "application/json", dataType: 'jsonp', success: function(data) { $.each(data.products, function(key, val) { items.push('<li class="product"><a href="product.html"><span class="store-badge"></span><img src="'+val.image+'" width="124" height="166" /><h3>'+val.title+'</h3></a></li>'); }); var nextLoad = items; if (loadNumber <= 4) { $('li.loading').before(nextLoad); }; if (loadNumber >= 4) { $('li.loading').hide(); }; $('.scroll-horizontal').mCustomScrollbar("update"); }, error: function() { console.log('failed'); } }); EDIT:
Console logging that results in :
Window Infinity: Infinity $: function (a,b){return new e.fn.init(a,b,h)} Array: function Array() { [native code] } ArrayBuffer: function ArrayBuffer() { [native code] } Attr: function Attr() { [native code] } Audio: [object Function] AudioProcessingEvent: function AudioProcessingEvent() { [native code] } BeforeLoadEvent: function BeforeLoadEvent() { [native code] } Blob: function Blob() { [native code] } Boolean: function Boolean() { [native code] } //CONTIUNES Console logging nextload also results in
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
console.log(nextLoad); console.log($('li.loading'))and update your question with results?itemsis not defined in your code above, but I assume it's an array since you'repushing to it? If so,nextLoadis also an array, and you can't usebefore()to insert an array, only jQuery objects or strings with HTML will work with DOM insertion methods.