0

Hi guys can How to assign $_GET value to a variable using pure JavaScript I have HTML structure not php

Boyrock75
  • 53
  • 1
  • 2
  • 5

2 Answers2

1

You could do something like this

function getGETParameter(key) {
    var params = window.location.search.slice(1).split('&'),
        i = params.length;
    key += '=';
    while (i-- > 0) {
        if (params[i].lastIndexOf(key, 0) === 0)
            return params[i].slice(key.length);
    }
    return false;
}

You may also want to consider if you want to use decodeURIComponent on these values as they may be URI encoded


If you want to also permit keys to be URI encoded then this method starts to have issues and you would have to create an Object mapping, which would look something like this

function getGETParameter(key) {
    var params = window.location.search.slice(1).split('&'),
        i = params.length,
        j,
        o = Object.create(null);
    for (i = 0; i < params.length; ++i) {
        j = params[i].indexOf('=');
        if (j === -1) // how do you want to treat found but no value?
            o[decodeURIComponent(params[i])] = null;
        else
            o[decodeURIComponent(params[i].slice(0, j))] = decodeURIComponent(params[i].slice(j + 1));
    }
    if (key in o) return o[key];
    return false; // how do you wan to treat not found?
}

You could also create and cache this Object in advance instead of generating it for each invocation

Paul S.
  • 64,864
  • 9
  • 122
  • 138
-1

combine the php code and javascript code !

var x=<?php echo $_GET['whatever'];?>;

so first the php code is being executed server-side and then it's result in html is assigned to a variable in javascript ...