Ajax does not post to div-Collection of common programming errors
I receive no errors from either jshint or console for this code. Yet, my ajax content does not post to the intended div(s). The alerts, however, fire:
var recentVar;
var highlightsVar;
var test3;
var test4;
function switcher(divToShow, thisVar, otherVar, url, div){
$("#site-nav li a").parents().removeClass("nav-active");
$(div).addClass("nav-active");
if (otherVar){ $(otherVar).detach();}
if(typeof thisVar === 'undefined') {
thisVar = $(divToShow + " ul.top-level").load("assets/includes/" + url, function () {
alert("I'm new");
});
} else {
$(thisVar).appendTo("#content-listing");
alert("I'm old");
}
}
//Recent
$("#site-nav .nav1").on("click", function (event) {
switcher("#recent", "recentVar", "highlightsVar", "recent.php", "#site-nav .nav1");
event.preventDefault();
});
//Highlights
$("#site-nav .nav2").on("click", function (event) {
switcher("#highlights", "highlightsVar", "recentVar", "all-web.php", "#site-nav .nav2");
event.preventDefault();
});
-
It has nothing to do with AJAX, but I think your issue is here.
$(thisVar)
thisVar
is simply text. If you check, you will see that$(thisVar).length
is 0. This is because you are calling:$("recentVar")
, which will search for any elements of type , which clearly there are none. If your intent is to append that text, you can useappend
or create an element and set the text torecentVar
and append that.EDIT: Another issue:
$(divToShow + "ul.top-level")
You need a space here:
$(divToShow + " ul.top-level")
Otherwise you are trying to match
#recentul.top-level
which is nonsense. -
Upon execution of switcher, thisVar is always going to be a string. It’s never going to have typeof undefined. It also LOOKS like you want to pass in an object (due to the declared variables) but… as stated, you’re always passing in a string.
[per James Montagne’s comment]
-
Try this:
if(typeof thisVar === 'undefined') { thisVar = $(divToShow + " ul.top-level").load("assets/includes/" + url, function () { alert("I'm new"); }); } else { $(thisVar).appendTo($("#content-listing")); alert("I'm old"); }
-
AMAIK, jQuery’s
load()
method directly inserts the result into the calling object. Thus the result should get loaded into$(divToShow + " ul.top-level")
element. Have you checked it? -
If the current document does not contain an element with an ID of
divToShow + " ul.top-level"
the.load()
method is not executed.Try Firebug or such things to track request. Maybe something is wrong with your response.
Originally posted 2013-11-09 19:43:11.