Grab/input php variable in javascript? - php

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

Related

How to store PHP session variable in JQuery variable?

How to store PHP session variable in JQuery variable.
I have one php file where i am using session variable as
$local_session = $_SESSION['sessionusername'];
and that PHP falls also using one .js file where i want to store this $local_session which is PHP variable to JQuery variable
It is as
session_start();
ob_start();
if(!$_SESSION['sessionusername'])
{
header("location:index.php");
}
else
{
include ('connection2.php');
include('PHP/combo_val.php');
$local_session = $_SESSION['sessionusername'];
}
and after this my HTML code starts
You might do something like this in your java script:
var sessionVar = '<?php echo $local_session; ?>';
and then use this global JS variable wherever in your page.
You can write some php-script which return session data, for example
JS:
//my.js
$.getJSON( "myssesiondata.php", function( data )
{
console.log(data);
}
PHP:
<?php
//mysession.php
return json_encode($_SESSION);
?>
# Axel Amthor
My JQuery Code is as
var lgn_usr = '<?php echo $_SESSION["sessionusername"] ?>';
alert(lgn_usr);
and it display
<?php echo $_SESSION["sessionusername"] ?>
as message
# Axel Amthor
My Jquery file code is as:
$(document).ready(function() {
$('#submit').click(function() {
submit_fxn();
$('#form_nuser').submit(function(e) {
return false;
});
});
function submit_fxn(){
var check_flag = 0;
var lgn_usr = '<?php echo $local_session; ?>';
alert(lgn_usr);
};
});
OKay, I got it. $_SESSION is a PHP array, we cannot set it on the client side via Javascript. The value has to be sent to the server to be stored in the array. Now, I am going for other method....

Passing Get value to different jquery file

I'm newbie at Jquery. I stacked to passing php $_GET['myvalue'] to my jquery file.
I struggled very much but I cannot find solution.
I have different one php file and one jquery file. I call my php file like
myphpfile.php?myvalue=testvalue
Then I want to receive myvalue's value to my jquery file. I tried document.getElementById but It doesnt work.
For any helping Thanks.
If you want to access the $_GET['myvalue'] value in your Javascript you can echo it out straight into it.
<script type="text/javascript">
// Your code
// The var you want to assign it to
var value = '<?php echo $_GET['myvalue'];?>'
</script>
Try this in your jQuery File:
First create a function to parse the parameters in the URL:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
vars[key] = value;
});
return vars;
}
Then you call the function:
var myUrlParameters = getUrlVars();
Then you can access them with:
var myParameter = myUrlParameters['myParameter'];
You need to read more about jQuery and Javascript...
You might want to add the variable you want in an HTML element, for example:
PHP
<?php
$myValue = $_GET["myvalue"];
echo '<input type="hidden" name="_method" value="'.$myValue.'" id="myElement" />';
?>
At jQuery:
$(document).ready(function(){
alert($('#myElement'));
});
If you want to access the $_GET['myvalue'] value in your script but using only Javascript.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}

Accessing javascript array from function

Okay, so in my <head> section i have the following:
<script>
var userDefaultInfo = '<?=$userInfo;?>';
var jGets = new Array ();
<?
if(isset($_GET)) {
foreach($_GET as $key => $val)
echo "jGets[\"$key\"]=\"$val\";\n";
}
?>
</script>
Now In my external .JS file, In the $(document).ready() section I can access userDefaultInfo fine, however, I am trying to access jGets, but not directly from there.
in the external .JS file, outside of $(document).ready(); I have the following function:
var sendGET = function () {
var data = $(this).val();
var elementName = $(this).attr("name");
var url = "zephi.php?p=home/support/admin_support.php&"+elementName+"="+data;
jQuery.each(jGets, function(i, val) {
alert(val);
});
alert(url);
window.location = url;
}
When a user changes a box, this function fires and changes the window location using the data. However, I want to add the data in the variable jGets, but I do not seem to be able to reference it at all in there.
Why is this?
You're "mis"-using an Array as an Object.
var jGets = {};
Perhaps doing either one of the following might work:
echo 'var jGets = '.(isset($_GET) ? preg_replace('/^"|"$/','',json_encode($_GET)) : '{}').';'
//or
echo 'var jGets = JSON.parse('.isset($_GET) ? json_encode($_GET); : '"{}"'.');'
This will produce an object literal, assigning everything you need to jGets, without having to mess about with loops. Since JSON stands for JavaScript Object Notation, it seems only logical/natural to use that to set the variable accordingly. Read more on json_encode here, more on JSON in PHP can be found here

Php and javascript communication : Passing javascript value to php value in the same method

I have been looking for hours, I know javascript is the client side and php is the server side and for communicating they need to use POST or whatever.
I have made this code in javascript first to retrieve the value i want and send it to php with jquery.
function getGroupName(test){
var groupName = ($(test).parent().attr('id'));
$.post("setGroup.php",{ groupName:groupName } ,function(data) {
if(data == 'yes'){
<?php
$testing = $_SESSION['currentGroup'];
$tsql2 = "select emailName,email from privacyEmails where tagID = '$tagid' and userEmail = '$testmail' and circleName = '$testing'";
$stmt2 = sqlsrv_query( $conn, $tsql2);
$order = 0;
$emailNameT = "";
$NameT = "";
while( $row = sqlsrv_fetch_array( $stmt2, SQLSRV_FETCH_NUMERIC))
{
$emailNameT = $row[0];
$NameT = $row[1];
?>
makeEditPeople('<?php echo $NameT ?>','<?php echo $emailNameT ?>','<?php echo $order ?>');
<?php
$order = $order +1;
}
?>
}
});
}
this is the php code (setGroup.php) to get the $testing :
<?php
include "connectionString.php";
session_start();
$groupName = $_POST['groupName'];
$_SESSION['currentGroup'] = $groupName;
echo "yes";
?>
Please note that the makeEditPeople() in the js is a method that append the user received in parameter into a table which works well.
My problem is : I want to send a javascript value (groupName) to SESSION value in php throught jquery $Post, then in the same time, I want to retrieve it without refreshing the page. Is that possible?
What you are looking for is called AJAX, it's a JavaScript "feature" that allows you to make requests to the server without refreshing the browser.
Since you are using jQuery it couldn't be simpler:
$.post (
'http://example.com/your.php', // URL of your script
{
Param1: 'value',
Param2: 123
},
function ( response ) {
// request holds whatever the server returned
}
);
See this for more info: http://api.jquery.com/jQuery.post/
If you are refreshing the page after you click on a link to activate and AJAX action, then this means one of two things:
You have an error in javascript (so the link ends up getting followed)
You haven't told javascript to not refresh the page.
You probably have and "onclick" or (if using jQuery "correctly") then you have $("#id").click( function(e) {} ) handler*. Make sure these "return false;" at the end
Click
function RunSomeFunction() {
// Do Stuff
return false
}
or, using jQuery
Click
$("#RunMyFunction").click( function(e) {
e.preventDefault();
// Do Stuff
return false;
)}
Notes:
You can also use other binding functions, not just click(). But click is easier to read
e.preventDefault is enough, you don't need that and return false; just giving you two options.
The issue is your "if (data == 'yes')" Javascript command cannot control whether or not inline PHP get executed; the contents there will run regardless, since it's another language all together.
The better solution is to modify setGroup.php to not return just 'yes' but both set and return the value:
<?php
include "connectionString.php";
session_start();
if (isset($_POST['groupName']))
$_SESSION['currentGroup'] = $_POST['groupName'];
echo $_SESSION['currentGroup'];
?>
Now if you POST to setGroup.php with no groupName set, it won't update the session, but will return the current value (data in the javascript function). If you do set it, it will return back the new value to Javascript.

Returning Data From Server To Page Using Ajax

I wanted to know if I can pass back individual parameters from a php script to be stored in dfferent JS variables on the page I'm working on, while also returning generated html code from the php script along with those parameters.
Basically I would like to return some data like this from php using ajax:
$valid = "true";
$access = "false";
$htmlcontent="lorem ipsum<br/>some more text<b>bold</b>";
And all of this should go into equivalent javascript variables on my page, using ajax, so that I can contruct my response on the page using this data...
Add the data to an array and json_encode then:
$ret = array();
$ret["valid"] = "true";
$ret["access"] = "false";
$ret["htmlcontent"] ="lorem ipsum<br/>some more text<b>bold</b>";
echo json_encode($ret);
And in your client side:
$.ajax({
url:"your_script.php",
success:function(resp) {
var json = jQuery.parseJSON(resp)
alert(json.valid)
}
})
Just let PHP print them directly as JS variables. It also saves your client one HTTP request.
<script>
var valid = <?= $valid ?>;
var access = <?= $access ?>;
var htmlcontent = <?= json_encode($htmlcontent) ?>;
</script>

Categories