Liz Banach Liz Banach - 2 months ago 7
Ajax Question

Run if/else script with only part of a URL

I am trying to edit my Javascript to pull different data via an AJAX call based upon only part of a URL. Currently, my if/else script looks like this:

if (window.location.href=="london") {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data-london.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
} else {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
}


This doesn't work as currently written since
if window.location.href=="london")
is only part of the URL, not the full URL. Is there a way to edit this script to run only based off of the last bit of the page URL? For example:
/london
,
/nw
, etc.? Is there a better way to accomplish this task?

Answer

Instead of

if (window.location.href=="london") {

Use below code

var URL = window.location.href;
if(URL.indexOf("london") !== -1)

The .indexOf function will find out a substring is exist or not in a string. And in your case you wants "london" is exist or not in URL.