How can I access a multidimentional php array in javascript? - php

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>

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....

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

Pass PHP value to javascript using Ajax

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);

php inside javascript checkbox value

I have a list list of checkbox with name of files that came froma DB. Then I have button for delete the files. I have the following code for the button:
<input type='button' id='submit_btn' onclick='eraseFile()' value='DELETE FILES' />
and the eraseFile function
...
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
<?php
echo "HElllo World";
?>
}
</script>
It gives an error "missing ; before statement" and "eraseFile is not defined"
Is it possible to write php inside javascript right??
Is it possible to write php inside javascript right??
Unless the PHP code is generating valid JavaScript, then no.
The reason eraseFile is being called undefined is that your echo statement is causing a syntax error since it is printing the string literal Hellllo World at the end of the JavaScript function which violates JavaScript syntax rules.
Yes, it is possible.
PHP is parsed on the server, so you will literally be printing "HElllo World" inside your javascript function, which would probably cause an error.
You might be looking do do the following:
<?php echo 'document.write("Hello World!");'; ?>
Your PHP output gets appended to your JS function making your javaascript look like this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World //syntax error here
}
</script>
You can do this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
alert("<?php echo "HElllo World"; ?>");
}
</script>
This will give a pop-up saying 'Hello World'
To pass a value from your Javascript function to your PHP script, you can do this:
var yourJsVar = {assign value here};
url = "yourPHPScript.php?value=" + yourJsVar;
if (window.XMLHttpRequest)
{ // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = someFunction;
//someFunction will get called when the PHP script is done executing
try
{
req.open("GET", url, true);
}
catch (e)
{
alert(e);
}
req.send(null);
}
else if (window.ActiveXObject)
{ // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = someFunction;
req.open("GET", url, true);
req.send();
}
}
In your PHP script:
$yourPhpVar = $_GET['value'];
I mentioned someFunction above that gets called after the PHP script completes execution. This is how it should look. (Note that this is on your Javascript)
function someFunction()
{
if(req.readyState == 4 && req.status == 200)
{
//this will only execute after your AJAX call has completed.
//any output sent by your PHP script can be accessed here like this:
alert(req.responseText);
}
}
Try to echo a meaningful javascript code, "Hello World" it's not a valid JS statement.
Try something like
<?php
echo "alert('HElllo World');";
?>
Where is your eraseFile function defined?
if it is not defined until after the place it is called, you will get that error.
Side note:
You can have php echo inside of the javascript, except what you have there will not do much...
Yes, you can use PHP code in you script files, but your code generate invalid script code here.
<?php
echo "HElllo World"; // becomes: HElllo World (text!) in JS
?>
It is possible to write PHP in Javascript, but it is not the best pratice. The way we normaly do this is through AJAX read the documentation : http://api.jquery.com/category/ajax/
Yes, it is possible to include PHP inside JavaScript, since the PHP will be executed on the server before the page contents are sent to the client. However, in your case, what is sent is the following:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World
}
</script>
This doesn't validate as JavaScript, since the "Helllo World" is not a valid JavaScript command. This is why the function isn't being defined properly. You need to replace the "Helllo World" string with an actual JavaScript command.

Pass JSON from php to javascript

I want to localize my webapp. Since localization through javascript only is not recommended I thought using php would be an alternative.
So with php I read a messages.json file that stores all localization data.
$json = file_get_contents("_locales/en/messages.json");
In the header of my webapp I generate some javascript with php according to the user's browser language.
echo "var localeObj = " . $json . ";";
So this is just a var that holds all data from the messages.json file that looks like that
{
"extTitle": {
"message": "Test1"
},
"extName":{
"message": "Test2"
}
}
Now I want to be able to access each item from the json like
var title = getItem("extTitle");
and it returns Test1. Any idea how to do that?
I am not very familar with json but if I just alert the localeObj it gives me just [object Object].
var getItem = function(item) {
return localObj[item].message;
};
You could always encapsulate your i18n strings too...
(function() {
var localObj = { ... };
window.getItem = function(item) {
return localObj[item].message;
};
})();
This way, no other variables can possibly clobber your localObj.
You use array syntax [], or dot syntax ., to access javascript object properties.
Example:
localeObj["extTitle"];
localeObj.extTitle;
I would recommend reading something like this to get more familier with JSON.
You can initialize javascript variable like this.
var json = eval(<? echo $json ?>);
alert(json.extTitle.message+ ' '+json.extName.message);
Inside messages.php:
<?php
header('Content-type:application/javascript');
$messages = array(
"yes"=>"hai",
"no"=>"iie"
);
$messages = json_encode($messages);
echo "window.messages = $messages";
?>
Inside index.html:
<html>
<body>
<script type="text/javascript" src="messages.php"></script>
<script type="text/javascript">
console.log(window.messages)
</script>
</body>
</html>
As long as you tell the browser to interpret the php file as a javascript file, you can echo anything you want.

Categories