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....
Related
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]
);
}
I have a php page with
<?php echo $_SERVER['DOCUMENT_ROOT']?>
Then my javascript is
var data = "Not Set";
$.get("test.php",function(returnData,requestStatus,requestObject){
data = returnData;
alert(data);
});
If I navigate directly to the php page on the site, it displays the data that I need.
I just can't seem to get the data into my javascript.
Am I on the right track and if so where am I going wrong?
Or is there an easier way to get the full filepath when working with a server?
Currently if I run document.location.href in my javascript it returns .
http ://127.0.0.1/etc
The code below will work on ".php" file. NOT ON ".html" file.
You can use the php variable with echo in javascript. For example
alert('<?=$phpvariable?>');
or
alert('<?php echo $phpvariable ?>');
It seems you are overthinking this. There is hardly any need to use ajax, but of course you can and just append() the data from the ajax call to your $('body') and jquery will automatically execute things inside a <script> tag.
var serverRoot = '<?php echo $_SERVER['DOCUMENT_ROOT']?>';
Try following
Instead of GET send $.post request and file don't return any thing just write
$.post("Requestedfile.php",
{
data :data
},
function(data) {
if(data == false)
{
//do something
}
else
{
//do somthing
}
}
);
I have a javascript file pet.js. I want to pass a value of variable in test.php. But i can't.
my pet.js is like
$('#pmWorkOrderDetailsPage').live('pageshow', function(event) {
var id = getUrlVars()["id"];
$.get("test.php", { test1: id } );
$.getJSON('pmworkorderdetails.php?id='+id, displaypmWODetails);
});
function displaypmWODetails(data) {
..............code..........
}
My test.php is like
<?php
$ms = $_GET["test1"];
echo $ms;
?>
But it is not working. I tried with Ajax and post method.
It will be best if I can store the variable value on the session in test.php.
Thanks in advance for any help.
1 do not use getUrlVars() it can make site vulnerable to xss
$('#pmWorkOrderDetailsPage').live('click', function(event) {
var id;// get id
$.get("test.php?id="+id,function(data){
var result=$.parseJSON(data);
alert(result["content"])
});
})
test.php
<?php
$id=$_GET['id'];
$data=array();
$data=array("content"=>$id);
echo json_encode($data);
?>
I have a php code that provides the database values. I need those values in the javascript variable.
Javascript Code
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text() {
var textVal=$("#busqueda_de_producto").val();
$.ajax(
{
type:"POST",
url:"index.php", //here goes your php script file where you want to pass value
data: textVal,
success:function(response)
{
// JAVSCRIPT VARIABLE = varable from PHP file.
}
});
return false;
}
</script>
PHP FILE CODE:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
?>
Your returning data is in the response parameter. You have to echo your data in PHP to get the results
Using JSON format is convenient
because of its key-value nature.
Use json_encode to convert PHP array to JSON.
echo the json_encoded variable
you will be able to receive that JSON response data through $.ajax
JavaScipt/HTML:
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text()
{
var textVal=$("#busqueda_de_producto").val();
$.post('index.php', { codigo:textVal }, function(response) {
$('#output').html(response.FIELDNAME);
}, 'json');
return false;
}
</script>
<span id="output"></span>
PHP:
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo='".mysql_escape_string($_POST['codigo'])."'";
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo json_encode($row11);
You aren't echoing anything in your PHP script.
Try altering your PHP to this:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo $row11; //This sends the array to the Ajax call. Make sure to only send what you want.
?>
Then in your Ajax call you can alert this by writing alert(response) in your success handler.
Tips
Send your data to the server as a URL serialised string : request=foo&bar=4. You can also try JSON if you fancy it.
Don't use mysql_* PHP functions as they are being deprecated. Try a search for PHP Data Objects (PDO).
i see lots of things that needs to be corrected
the data in your ajax do it this way data: {'codigo':textVal}, since you are using $_GET['codigo'], which leads to the second correction, you used type:"POST" so you must also access the $_POST variable and not the $_GET variable and lastly the target of your ajax does not display / return anything you either echo it or echo json_encode() it
The best solution is to use
echo json_encode("YOUR ARRAY/VALUE TO BE USED");
and then parse JSON in the javascript code as
obj = JSON.parse(response);
The code is like this:
<SCRIPT LANGUAGE="JavaScript">
function showReview(){
//javascript stuff
<?php
$http="obj.href ='http://localhost/PROJECT1/thispage.php'";
if (array_key_exists(0, $arr)){
$http .= "+'&PQID={$arr[0]['ID']}'+
'&PQNo={$arr[0]['QNo']}'+
'&PNextSWF={$arr[0]['NextSWF']}';";
}
echo $http;
?>
}
</SCRIPT>
But I can't access $arr array. I tried to declare it global or use the $GLOBALS variable.
Show Review is called during onclick.
$arr is set in the main php code.
I tried just accessing the array in the main php code and passing the resulting string to the javascript which is the '?&PQID=ar&PQno=1...' part of the URL but it doesn't pass successfully. I tried passing the array itself to the javascript but js but I couldn't access the contents.
PHP runs on the server, Javascript on the client - they can't see each other's variables at all really. Think of it this way - the PHP code just generates text. It might be Javascript, but as far as the PHP concerned, it's just text.
Basically, you need to use PHP to generate text which is valid Javascript for creating the same data structure on the client.
Add this to the JS-function:
var arr=<?php echo json_encode($arr); ?>;
The PHP-Array "$arr" should now be accessible to JS via "arr" inside the JS-function.
I guess you are trying something like this:
<?php
//example array
$arr=array(
array('ID'=>'0','QNo'=>'q0','NextSWF'=>1),
array('ID'=>'1','QNo'=>'q1','NextSWF'=>2),
array('ID'=>'2','QNo'=>'q2','NextSWF'=>3),
);
?>
<script type="text/javascript">
function showReview(nr)
{
//make the array accessible to JS
<?php echo 'var arr='.json_encode($arr);?>
//some obj, don't no what it is in your case
var obj={};
var href='http://localhost/PROJECT1/thispage.php';
if(typeof arr[nr]!='undefined')
{
href+='?PQID='+arr[nr]['ID']+
'&PQNo='+arr[nr]['QNo']+
'&PNextSWF='+arr[nr]['NextSWF'];
}
else
{
alert('key['+nr+'] does not exist');
}
//check it
alert(href);
//assign it
obj.href=href;
}
</script>
<b onclick="showReview(0)">0</b>-
<b onclick="showReview(1)">1</b>-
<b onclick="showReview(2)">2</b>-
<b onclick="showReview(3)">3</b>
Try this
<SCRIPT LANGUAGE="JavaScript">
function showReview(){
//javascript stuff
var http =
<?php
$http="obj.href ='http://localhost/PROJECT1/thispage.php'";
if (array_key_exists(0, $arr)){
$http .= "+'&PQID={$arr[0]['ID']}'+
'&PQNo={$arr[0]['QNo']}'+
'&PNextSWF={$arr[0]['NextSWF']}';";
}
echo $http;
?>
}
</SCRIPT>