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.
Related
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);
I want to execute any JavaScript function that is part of a JSON using eval() but obviously I can't do it right, and can't figure out where exactly is the mistake/s. I'm using two very simple files, just for trying - the first is index.php and is at it is:
<!DOCTYPE html>
<html>
<head>
<title>Simple form sending and receiving a JSON object to/from PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data =
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
var dataString = JSON.stringify(data);
$.post('simpleformSubmi.php', { data: dataString}, showResult, "text");
});
function showResult(res)
{
var data = eval('(' + res + ')');
$("#fullresponse").html("Full response: " +data);
}
</script>
<div id="fullresponse"></div>
</head>
<body>
and the second one is simpleformSubmi.php :
<?php
$logFile = 'logFile';
$res = json_decode(stripslashes($_POST['data']), true);
$arr = "function(){alert('Hi')}";
echo json_encode($res);
echo json_encode($arr);
So what I expected was after executing echo json_encode($arr); to get and alert but instead I get a mistake, and in Firebug the console shows error "missing ) in parenthetica". So the question is - how to send a valid JS function this way and to execute it properly?
Thanks
Leron
Why you are json_encodeing $arr. You may just return it as a string echo $arr and eval('(' + res + ')()') in the JavaScript (notice the () in the JS to execute the function). You may need to remove echo json_encode($res) just to get this to work for now.
You can't. A JSON object cannot contain functions, only values.
You will have to setup some sort of webservice that actually prints JavaScript, which you in turn can call through a <script src="/your/endpoint"></script> declaration client side.
You can send the js function as data.
$data = array("something"=>"12345");
$js = "alert('hi!')";
$data["autoexec"] = $js;
echo json_encode($data);
Then on the clientside do something like eval(data["autoexec"]);
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.
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>
While developing AJAX program, I met the design decision to make string I18N in JavaScript.code. Some string is only used by JavaScript. For example.
$('#submit').click(function() {
$(#target).html('Please wait while submitting...').load(someURI);
}
I'd like to I18N the string 'Please wait while submitting...'. I'm not sure what's the best way to do it. Currently, I just have the string I18N-ed in server and rendered into a javascript variable in page (I'm using PHP/wordpress).
<script>strSubmit = <?php _e('Please wait while submitting...'); ?></script>
Then, in javascript, I just use the varialble
$('#submit').click(function() {
$(#target).html(strSubmit).load(someURI);
}
This works, but it looks messy. Is there any better way to achieve this?
You should use JSON to convert the server side l10n strings to a JSON object :
// In the <head> tag :
<script type="text/javascript" src="locales.php"></script>
and this in locales.php :
var l10n = <?php echo json_encode($l10n); ?>;
where $l10n is an array which contains all the locales, like this :
$l10n = array(
'Please wait while submitting...' => 'Veuillez patienter durant le traitement...',
'bah' => 'bih'
);
You can now use these strings like this in JS :
function $T(s){
return l10n[s] || s;
}
alert($T('Please wait while submitting...'));
you can also automate this by using a php "preprocessor" for javascript
<script src="script.php?file=blah.js">
where script.php is something like
function _repl($x) { return '"' . _e($x[1]) . '"'; }
$js = file_get_contents($_GET['file']);
$js = preg_replace_callback('~_e\("(.+?)"\)~', '_repl', $js);
echo $js;
this will transparently replace _e(something) in javascript code with actual strings
You could generate the text into the original script itself.
$('#submit').click(function() {
$(#target).html('<?php _e('Please wait while submitting...'); ?>').load(someURI);
}
you could create sort of REST application, where you would fill the elements of javascript strings on document load from a service:
$(function(){
var handleResponse = function.....; // fill your string elements from response
var lang = "fr"; // language of localized document
$.ajax(
type: "GET",
url: "/i18n.php?lang=" + lang + "&names=someName+someName1+someName2",
success: handleResponse
);
});