Accessing javascript array from function - php

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

Related

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

How To Pass PHP Variable To This Javascript Function?

Let's say I have this PHP variables :
$SelectedCountry = "USA";
$SelectedState = "Texas";
on the other hand, I have this javascript function to display all available countries and states :
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Where do you live now?','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
}
}
function print_state(state_id, state_index){
var option_str = document.getElementById(state_id);
option_str.length=0; // Fixed by Julian Woods
option_str.options[0] = new Option('Select state','');
option_str.selectedIndex = 0;
var state_arr = s_a[state_index].split("|");
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
my question is... how to make 'USA' and 'Texas' becomes selected <option> which generated by those two javascript functions? thanks.
NOTE #1 : you can see the complete code of javascript here : http://sourceforge.net/projects/countries/files/
NOTE #2 : those function called by adding this line on my PHP :
<script type="text/javascript" src="scripts/countries.js"></script>
<script language="javascript">print_country("country");</script>
so basically I need your help how to pass that PHP variables so that it can be 'received' by javascript function INSIDE that countries.js file.
One way is to just echo out some JavaScript statements:
<script>
<?php
echo "
var SelectedCountry = '$SelectedCountry';
var SelectedState = '$SelectedState';
";
?>
</script>
Then just use them in your loops to check if the option needs to be selected or not.
If you're going to be doing a lot of this sort of thing, though, embedding PHP into JavaScript isn't really the best approach. Read up on AJAX and PHP's json_encode() function.
There are two answers:
1 Use AJAX cal and pass back JSON
$.ajax({
url: '/myScript.php',
success: function(data) {
//Do something
}
});
myScript.php
return json_encode($myVar);
2 Embed PHP into the JavaScript
<script>
var myPHPVariable = <?php echo $myVar; ?>
</script>

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

Passing php array as variables to javascript load url and back to php array?

I saw many examples related but I'm still confused. I'm using ajax (which I don't know much about) to get the results of a file updated every xxx seconds. It's working perfectly if I pass just one variable, but what is the best way if I need to pass an array from php through it?
Structure is simples:
show_results.php
<?php
include_once('modWhosonlineCustom.inc.php');
$document->addScript("http://code.jquery.com/jquery-latest.js");
$document->addScript("ajax.js");
$array_name = modWhosonlineCustom::getOnlineUserNames();//the array I need to pass to javascript variable
?>
<script>
var whosonline = '<?php echo "$array_name"; ?>';
</script>
<div id="results"></div>
Ajax code than would have more than one param to build in the url load:
ajax.js
$(document).ready(function() {
$("#results").load("response.php?array_name[param1]&array_name[param2]");
var refreshId = setInterval(function() {
$("#results").load("response.php?array_name[param1]&array_name[param2]&randval="+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
And back to PHP response page, how could I use again the array params passed through url?
response.php
<?php
$names = $_GET['array_name'];
foreach ($names as $name) {
//do something
Any suggestions is really appreciated, thanks!
EDIT
Thanks guys, I think I'm the right way now, but ramains the problem to pass this array through a url in the javascript. Or maybe I'm not getting it in the right way in the php end callback file. I'll show you what a modifyed:
show_results.php
...
<?php
$names = modWhosonlineCustom::getOnlineUserNames();
?>
<script>
var whosonline = '<?php echo "json_encode($names)"; ?>';
</script>
ajax.js
$(document).ready(function() {
$("#atendentes").load("response.php?names=" + whosonline);
var refreshId = setInterval(function() {
$("#atendentes").load("response.php?names=" + whosonline + "&randval="+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
response.php
$users = $_GET['names'];
$users = json_decode($users);
echo "user: $users";
$names = $users;
foreach ($names as $name) {
...
Here in the other side I'm getting: Warning: Invalid argument supplied for foreach() in response.php on line 33, and the echo is empty
What is missing?
To pass arrays/objects from PHP to JavaScript you may use the json_encode()/json_decode() functions.
Your code wouldn't work. If you have
$arr = array('a', 'b', 'c');
echo $arr;
you actually get
Array
as the output. Not the contents of the array. To "output" an array from PHP to JS, you have to convert it to native Javascript, which is where json_encode comes in:
<?php
$arr = array('a', 'b', 'c');
?>
var js_array = <?php echo json_encode($arr) ?>;
which will produce
var js_array = ["a","b","c"];
As a general rule, anytime you are using PHP to generate javascript code and are filling in Javascript variables with PHP values, you should use json_encode to ensure that you're generating valid Javascript. Any syntax errors and the whole Javascript code block is dead in the water once the client starts trying to execute it.

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