Search code examples
jqueryjquery-postjquery-get

jQuery - check for POST in the URL


Is there any way to check with jQuery for POST within the URL similar to the PHP way?

PHP version:

if(!empty($_GET)) { // do stuff }

Sorry. I mean GET not POST.

I'm looking to fetch the URL on the page load $(document).ready( function() { // here });

Example URL: http://www.domain.com?a=1

And than past value of the var a into the function OnLoad();


Solution

  • extend jquery to get the url vars

    $.extend({
      getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
        }
        return vars;
      },
      getUrlVar: function(name){
        return $.getUrlVars()[name];
      }
    });
    

    then you can call

    if($.getUrlVars().length > 0){ // do something }
    

    you can also query a specific value by

    if($.getUrlVar('name') == 'frank'){