Reputation: 2893
I found some code which enables me to obtain URL query strings
var QueryURL = function () {
var query_url = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof query_url[pair[0]] === "undefined") {
query_url[pair[0]] = decodeURIComponent(pair[1]);
} else if (typeof query_url[pair[0]] === "string") {
var arr = [ query_url[pair[0]],decodeURIComponent(pair[1]) ];
query_url[pair[0]] = arr;
} else {
query_url[pair[0]].push(decodeURIComponent(pair[1]));
}
}
return query_url;
}();
The above code works perfectly. There is something I am not quite getting however. I am doing the following
$( ".search" ).click(function(e) {
console.log(QueryURL.someID); //outputs undefined
if(QueryURL.someID !== "undefined") {
$.ajax({
url: "someurl",
type: "POST",
success: function (data) {
console.log(data)
},
error: function(xhr, ajaxOptions, thrownError){
}
});
}
});
So if I do not provide the URL with a query someID, then it should not execute the Ajax call. Now the console logging outputs undefined, as I expect it too. However, for some reason it is still firing the Ajax request even though I have a condition that should stop this from happening.
Why would it still make the ajax request if QueryURL.someID
is undefined?
Thanks
Upvotes: 0
Views: 31
Reputation: 3458
"undefined"
is a string, you need to compare with variable undefined
if(QueryURL.someID !== undefined) {
//ajax call
}
From MDN:
The global undefined property represents the primitive value undefined. It is one of JavaScript's primitive types.
Upvotes: 1