How to internationalize string used in javascript code? - php

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

Related

How to print JSON array inside script tag?

I'm trying to display JSON array inside <script> tag, is that possible?
Here is what I've tried so far:
<script>
var x = JSON.stringify(data);
var json = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "empdata.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
</script>
What I'm trying to do:
<script>
var videos = {"employee_id":"1","employee_name":"Steve","designation":"VP","hired_date":"2013-08-01","salary"
:"6000"};
</script>
Yea you just echo it like this, assuming you have an $array of parameters like array("employee_id"=>1 ... )
var videos = <?php echo json_encode(array(
"employee_id"=>1
)); ?>; // <- don't miss the java-script semi-colon though
This should just print
var videos = {"employee_id":1};
PHP doesn't care where you echo it at, in your page, it doesn't have a concept about what a <script> tag is. All it knows is some things are php code, everything else is string content.
OR you could just do this
var videos = <?php echo '{"employee_id":1}'; ?>;
But that is kind of pointless, unless you mean like this.
var videos = <?php echo '{"employee_id":'.$employee_id.'}'; ?>;
Or you can do this way to
var videos = {"employee_id":1};
And just put it in there, I don't understand anymore?
If you mean from a file containing your json, then sure.
<?php
$json = file_get_contents( 'pathtofile.json');
?>
<script> ... etc.\
var videos = <?php echo $json; ?>;
PHP can read files, and it can echo the contents of those files, PHP doesn't care whats in them. The only catch is the content has to be valid Json for the javascript to work. But php doesn't care if it's JSON, XML, Binary etc. it's all text because PHP is a loosely typed language. In fact php doesn't care if your Javascript works, it has no concept of what javascript is.
In fact this works too ( assuming image.jpg is a real image file. ).
$jpg = file_get_contents( 'image.jpg' );
echo '<img src="'. $jpg.'" \>
OR
header('Content-Type: image/jpeg');
echo file_get_contents( 'image.jpg' ); //assuming there is no other content

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

How can I access a multidimentional php array in javascript?

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>

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