Not entirely sure why this is going wrong. Jquery Novice. It should work, according to all the examples I’ve seen, but it doesn’t.
In the following script, the function sets new values for variables, but the new values don’t persist outside the function. (console logs show this)
$(document).ready(function() {
// url
var path = location.pathname.split("/"),
pos1_path = path[1] != undefined ? path[1] : false,
pos2_path = path[2] != undefined ? path[2] : false,
pos3_path = path[3] != undefined ? path[3] : false;
//console.log('before: ' + pos2_path);
if (pos1_path = 'article') {
$.post("/js/ajax/article_crumbs.php", { func: "getArticleCrumbs" },
function(data){
pos2_path = data.category;
//console.log('during: ' + pos2_path);
return pos2_path}, "json");
}
//console.log('after: ' + pos2_path);
// navigation
// set category nav to current category
if ( path[2] ) {
$('#category_nav a[class$="' + pos2_path + '"]').toggleClass('current');
}
else {
$('#category_nav a:first').toggleClass('current');
}
});
The PHP:
<?php echo json_encode(["category"=>"arts-and-culture"]);
Also, according to the console printouts, the “after” print out appears before the “during”, does that mean the function doesn’t run until the end of the rest of the script?
EDIT: To clarify, I need to keep the { if(path[1]) setcurrent } part of the script out of the { if(pos1_path = ‘article’) } part so that if pos1_path is NOT article, it sets the value to whatever is in the URI..
SOLUTION as per answer below:
$(document).ready(function() {
// url
var path = location.pathname.split("/"),
pos1_path = path[1] != undefined ? path[1] : false,
pos2_path = path[2] != undefined ? path[2] : false,
pos3_path = path[3] != undefined ? path[3] : false;
if (pos1_path = 'article') {
//console.log('before: ' + pos2_path);
var data = {id: pos2_path}
$.ajax({
type: 'POST',
url: "/js/ajax/article_crumbs.php",
data: data,
success: function(data){
pos2_path = data.category;
//console.log('during: ' + pos2_path);},
dataType: "json",
async: false
});
}
//console.log('after: ' + pos2_path);
// navigation
// set category nav to current category
if ( path[2] ) {
$('#category_nav a[class$="' + pos2_path + '"]').toggleClass('current');
}
else {
$('#category_nav a:first').toggleClass('current');
}
}
$.post request is asynchronous call so obviously it will move on to rest of the lines of code and not wait for callback of $.post
Try using
$.ajaxinstead and make itasync=falseto use same codeOR
Move your code inside success callback.