Access GET variables using jQuery/Javascript
<p>I know that this question has been asked before, but I have had trouble with all of the solutions posted so far. I have a url that looks like this:</p>

<pre><code>http://localhost:3000/virgil/1/render_lesson?toggle=view
</code></pre>

<p>It is a Rails call through AJAX, but that should not matter. Everytime I try a function that is supposed to get the variable for "toggle" I get "undefined" instead when I print it to the consoles log. I have tried this function</p>

<pre><code>function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&amp;');
    for(var i = 0; i &lt; hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
</code></pre>

<p>And when I call <code>console.log(getUrlVars());</code> I get <code>["http://localhost:3000/"]</code></p>

<p>But when I call <code>console.log(getUrlVars()["toggle"]);</code> I simply get <code>undefined</code></p>

<p>I appreciate any help!</p>

<p>EDIT:</p>

<p>Adding the relevant parts of my code. This is a Rails application, that makes the call using AJAX.</p>

<p><code>&lt;%= link_to 'View Lessons', render_lesson_virgil_path(course, :toggle =&gt; :view), :remote =&gt; true, :class =&gt; 'toggle_lesson', :id =&gt; "toggle_lesson#{course.id}" %&gt;</code></p>

<p>And then in the javascript file that it calls:</p>

<pre><code>function $_GET( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&amp;]"+name+"=([^&amp;#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

console.log($_GET('toggle')); //This is where it prints the incorrect value to the log, regardless of the function I use.

$("#Course&lt;%= @course.id %&gt;").append('&lt;div id="Lesson&lt;%= @course.id %&gt;" class="render_lesson"&gt;&lt;/div&gt;');
$("#Lesson&lt;%= @course.id %&gt;").html("&lt;%= escape_javascript(render( :partial =&gt; "lesson" )).html_safe  %&gt;");
</code></pre>
