I need a bit of help with PHP and JQuery. How would I go about passing a variable from PHP to JQuery while at the same time redirecting to another page that accesses the JQuery in the front end? Any help will be very much appreciated. I need the systemFeedBack to be sent when I redirect
Mysql::runAdhocQuery($insert_sql, $link);
echo MyClass::systemFeedBack(202, "Registration successful", "User can Log in");
header("Location: http://localhost/myProject/#/");
Since you would be passing the variables via url you can either get the variables using Jquery or Javascript. Below is a pure JavaScript code to GET the query params.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)
Credits : How can I get query string values in JavaScript?
Related
I there a possible way to use a GET variable in jQuery url. Like in PHP we have something like this:
header('location : path/to/page.php?id='.$id);
And In the page.php we do this:
$id = $_GET['id'];
So in jQuery can we do something like:
window.location.replace(path/to/page.html/* and pass the url query here*/);
I think what you are looking for is to access the query string ($_GET in php) variables in javascript. You can use this function for that.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
and then call getParameterByName('id') to get ?id=val part of the current URL.
You can also pass data to another page using location.replace:
idVal = 1;
window.location.replace("path/to/page.php?id="+idVal);
Use a js function to do this...
var 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(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
}
if(vars[0] == window.location.href){
vars =[];
}
return vars;
}
Then where ever you wish to use
var params = getUrlVars();
console.log(params["id"]);
console.log(params["whatever"]);
You can use it anywhere you want.
the property 'search' of the 'location' javascript object will give you the querystring parameters of the url, eg:
url: http://www.w3schools.com/submit.htm?email=someone#example.com
console.log(location.search);
// output: ?email=someone#example.com
after that you can parse it as you wish
I have some javascript sorting my ul, alphabetically a-z or z-a. It works fine on page one, but if there is more than one page it ignores the list on page 2 etc.
So, instead of using javascript to sort the li's, I want to pass the selection back to the page's query and reload
here's my script, most of which is redundant now.
var select = document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
} else {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
});
So I want to detect the selected dropdown value (either A or Z) and pass that into the url and reload. I'm stuck ;-?
Rich :)
I am not sure this is the best way to approach the problem, and maybe you should elaborate what doesn't work with your pagination. In any case, you can achieve what you need to do by doing something like this (explaination in the code comments):
var queryString = {};
// Get the previous query string with a little help from PHP
// this shouldn't be a problem since you are already using PHP
// for your project.
queryString = <?php json_encode( $_GET ); ?>;
$('#organise').change( function() {
// Set the sort property of the object to the value of the select.
queryString.sort = $(this).val();
// jQuery will help you serialise the JSON object back to
// a perfectly valid query string (you may want to escape
// characters)
newQueryString = $.param( queryString );
// Append the new query string
window.location = newQueryString;
});
This function will properly check if you already have any query string and preserve that; also, if the user changes the select multiple times, it will not add up several query strings.
you can change the url and pass the param with
document.location.href = document.location.href + "?arg=" + document.getElementById("organise").value;
You can use localstorage for this if you don't want to show in url
For example:
function Ascending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
}
function Descending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
if(localStorage.order=='A')
{
return Ascending();
}
else
{
return Descending();
}
var select=document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
localStorage.order=='A';
return Ascending();
} else {
localStorage.order=='Z';
return Descending();
}
});
Refer more for localStorage on http://www.w3schools.com/html/html5_webstorage.asp
I'm doing cross-domain GET to get cnn html like this:
$(function(){
var site = 'http://cnn.com';
$.get('proxy.php', { site:site }, function(data){
$(data).appendTo('#div');
}, 'html');
});
Im getting everything that I need except the url's sometimes are not complete urls but point to a certain path on there server like this:
/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3
So the problem is that if someone is clicking the link on my site the url will look like this:
http://MY-WEBSITE/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3
How can I get rid of my own url being inserted and replace it with 'cnn.com'?
I tried jquery split and replace but it doesn't work:
href = $(this).prop('href');
url = href.split('/');
href.replace(url[2], 'cnn.com');
I usually get an error in console 'split is not defined', when I fixed it the error moves on to 'url is not defined' and so on. Sometimes (with other code variations) I get no errors but it still doesn't work. I cant figure it out.
Looking at your code I am assuming you are using jQuery.
The problem is occurring because the source code on cnn.com seems to be using relative links. You can insert cnn.com at the beginning with the following jQuery
$(function() {
$('a').each(function() {
if ($(this).attr('href').indexOf('http') === 0) {
$(this).attr('href', 'http://www.cnn.com' + this.href);
}
});
});
You can simply check if the url is relative or not. Easiest way to do this is to check if it starts with http://.
var url = $(this).prop('href');
if (!(/^http/).test(url))
{
url = site + url; // prepend "http://cnn.com" to the address
}
alert(url); // url is now a full url
if you want a more generalised solution, you can use the regexp object on the site to determine if the prefix is there.
var site = "http://cnn.com";
var siteRegex = new RegExp("^" + site); // Regex - Starts with site
var url = $(this).prop('href');
if (!siteRegex.test(url))
{
url = site + url;
}
alert(url);
This little function can be used in a general purpose:
function RelativeToAbsoluteURL(root, url) {
var httpMatch = /https?:\/\//ig;
if (!httpMatch.test(url)) {
return root + (url.substr(0, 1) != "/" ? "/" + url : url);
} else {
return url;
}
}
Use:
RelativeToAbsoluteURL("http://www.cnn.com", "http://www.cnn.com/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3");
RelativeToAbsoluteURL("http://www.cnn.com", "/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3");
Both will output the same URL (http://www.cnn.com/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3)
DEMO
Either seems to work:
var href = $(this).attr('href');
var url = (href.indexOf("/")===0) ? "http://...."+href:href;
Possible alternative - this one will return the fully qualified URL from the href
var href = this.href; // actual href and not the property
var url =(href.indexOf(location.hostname)===7) ? href.replace(location.hostname,"www.cnn.com"):href;
Using prop
var href = $(this).prop('href');
var url = (href.indexOf("/")===0) ? "http://...."+href:href;
I suppose I could use PHP to access $_GET variables from JavaScript:
<script>
var to = $_GET['to'];
var from = $_GET['from'];
</script>
<script src="realScript" type="text/javascript"></script>
But perhaps it's even simpler. Is there a way to do it directly from JS?
Look at
window.location.search
It will contain a string like this: ?foo=1&bar=2
To get from that into an object, some splitting is all you need to do:
var parts = window.location.search.substr(1).split("&");
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split("=");
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
alert($_GET['foo']); // 1
alert($_GET.bar); // 2
Here's another idea:
<script type="text/javascript">
var $_GET = <?php echo json_encode($_GET); ?>;
alert($_GET['some_key']);
// or
alert($_GET.some_key);
</script>
I know this topic is old, but I want to share my own ES6 solution for $_GET in JavaScript.
One Liner
window.$_GET = location.search.substr(1).split("&").reduce((o,i)=>(u=decodeURIComponent,[k,v]=i.split("="),o[u(k)]=v&&u(v),o),{});
Here is the MDN documentation on array.reduce(), arrow functions, the comma operator, destructuring assignment, and short-cicuit evaluation.
So, for a URL like google.com/webhp?q=foo&hl=en&source=lnt&tbs=qdr%3Aw&sa=X&ved=&biw=12 you've got an object:
$_GET = {
q: "foo",
hl: "en",
source: "lnt",
tbs: "qdr:w",
sa: "X",
ved: "",
biw: "12"
}
and you can do things like $_GET.q or $_GET['biw'] to get what you need. Note that this approach replaces duplicated query parameters with the last-given value in the search string, which may be undesired/unexpected
URLSearchParams()
Now we also have URLSearchParams() in new browsers, which lets you do things like:
window.$_GET = new URLSearchParams(location.search);
var value1 = $_GET.get('param1');
I suppose you were thinking this:
<script type="text/javascript">
var to = "<?= $_GET['to']; ?>";
var from = "<?= $_GET['from']; ?>";
</script>
...this would just be syntax-correction of your idea :)
document.get = function (d1,d2,d3) {
var divider1 = (d1 === undefined ? "?" : d1);
var divider2 = (d2 === undefined ? "&" : d2);
var divider3 = (d3 === undefined ? "=" : d3);
var url = window.location.href; //the current url
var pget = url.split(divider1)[1]; //slit the url and assign only the part after the divider 1
var pppget = {}; //define the contenitor object
if (pget.search(divider2) > -1) { //control if there is variable other than the first (?var1=a&var2=b) the var2 in this example
var ppget = pget.split(divider2); //split the divider2
for (i = 0;i==ppget.lenght; i++) { //start a for and stop it when i == at object length
if (ppget[i].search(divider3) > -1) { //control if is an empty var
psget = ppget[i].split(divider3);//if is split in 2 part using divider 3
pppget[psget[0]] = psget[1];//assign to the object the value of first element and for value the second value ex {var1=a,...}
} else {//if is a empty var (?var1&...)
pppget[ppget[i]] = "";//assign only the value of first element with value a blank string
}
}
} else {//if the url don't contain other variable
if (pget.search(divider3) > -1) { //control if is an empty var
var ppget = pget.split(divider3);//if is split in 2 part using divider 3
pppget[ppget[0]] = ppget[1];//assign to the object the value of first element and for value the second value ex {var1=a}
} else {//if is a empty var (?var1)
pppget[pget] = "";//assign only the value of first element with value a blank string
}
}
return pppget;
/* return the object
* the use of the function is like this $_GET=document.get()
* echo $_GET[var]
* or use custom divider the default is setted for php standard divider
*/};
As others have explained you can parse page URL from JS to get the variables.
You could also use AJAX in the page which submits the values. It really depends on what kind of information you're passing and then returning back to the user. (It's definitely not simpler or more direct way of doing it, just an alternative approach)
i use this one for Get request (like $_GET in php):
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
class Utils {
static HTTP_GET(key){
let map = this.HTTP_GET_ALL();
if(map.has(key)){
return map.get(key);
}else {
return null;
}
}
static HTTP_GET_ALL(){
let parts = window.location.search.substr(1).split("&");
let map = new Map();
for (let i = 0; i < parts.length; i++) {
let temp = parts[i].split("=");
map.set(decodeURIComponent(temp[0]), decodeURIComponent(temp[1]));
}
return map;
}
}
From what I can see: the URLSearchParams function is a widely-available in-built function gives you to ability to get all of the current query parameters into a single object. You can then access those parameters either individually as a replacement to $_GET, or you can foreach loop over it to make it into an array.
/* Example - Accessing a property with using URLSearchParams in place of $_GET */
const params = new URLSearchParams(window.location.search);
// Expected Output: (string) "true"
console.log(params.get("is_the_cake_a_lie"));
/* Example - Creating a $_GET array using URLSearchParams */
const params = new URLSearchParams(window.location.search);
window.$_GET = {};
for (const [key, value] of params.entries()) {
window.$_GET[key] = value;
}
// Expected Output: (object) { "is_the_cake_a_lie": "true" }, (string) "true"
console.log(window.$_GET, window.$_GET["is_the_cake_a_lie"]);
REF: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
I am trying to dynamically get a php variable and place them into my javascript variable as seen below:
var site_url = "getsite.php?name=SiteName&link=linkURL";
That above script is what I have now and it is harcoded(SiteName,linkURL).
I want to change 'SiteName' and 'linkURL' to display whatever the PHP variable is on another page.
Any help would be great, Thanks.
You can try this method: http://www.netlobo.com/url_query_string_javascript.html
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
How is the user arriving at this page from the one with the PHP variables you want to access?
The simplest way would be to store them in the session, like so:
previous page:
<?php
session_start();
$_SESSION['siteName'] = 'mySiteName';
$_SESSION['linkURL'] = 'http://somesite.com';
?>
then, on the current page:
<?php
$name = $_SESSION['siteName'];
$url = $_SESSION['linkURL'];
?>
<script type="text/javascript">
var site_url = "getsite.php?name=<?php echo $name; ?>&link=<?php echo $linkURL; ?>";
</script>
That should work for you - good luck!
you will need to send thru and AJAX request via XMLHttpRequest etc to load a page like that in JS. however i am not sure if i understand that logic of that flow correctly