PHPLover
PHPLover

Reputation: 13005

How to execute if condition based on a value from query string in JavaScript/jQuery?

I've a variable called url as follows :

url = "http://56.177.59.250/static/ajax.php?core[ajax]=true&core[call]=prj_name.contactform&width=400&core[security_token]=c7854c13380a26ff009a5cd9e6699840"

Now I want to use if condition only if core[call] is equal to the value it currently has i.e. prj_name.contactform otherwise not.

How should I do this since the parameter from query-string is in array format?

Upvotes: 0

Views: 2838

Answers (2)

Invicnaper
Invicnaper

Reputation: 21

You can use location.search :

 <script>
function get(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if(get("core[call]") == "prj_name.contactform"){
    alert('ok');
}else{
    alert('no');
}
</script>

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59282

Just use String.indexOf and check if it is present (that is not -1, which means it doesn't exist)

if(url.indexOf("core[call]=prj_name.contactform") > -1){
   // valid. Brew some code here
}

Upvotes: 3

Related Questions