...

View Full Version : Embed language strings into Javascript code



guvenck
07-27-2007, 12:35 PM
Hi,

I am using language files to localize my script. For example, I include lang_english.php that holds the english language strings like:



define("_WAIT","Please Wait...");
define("_ERRORNAME","Please enter your name");


Then use the defined string in my scripts like



echo _ERRORNAME;


As fas as PHP scripts are concerned, everything works fine so far. But, I can't localize my Javascript codes. For example form error alerts. I include my javascript files externally in my header.php, like



<script language="JavaScript" type="text/javascript" src="js/form.js"></script>


and for example in form.js:



function validateForm() {

var myForm = document.forms["myForm"];

if (myForm.name.value == "") {
// This is what I'm trying to localize!
alert("Please enter your name");
myForm.name.focus();
return false;
}

}


So far, I couldn't get it to work. I tried to rename form.js to form.php and tried



alert(<?php echo _ERRORNAME; ?>);


But that didn't work either. Any advices?

_Aerospace_Eng_
07-27-2007, 12:43 PM
You would have to do link to a php file as the javascript source.

<script language="JavaScript" type="text/javascript" src="js/form.php"></script>
Then in form.php you would do something like this

<?php
header("Content-Type: text/javascript");
include('lang_english.php');
$errorname = _ERRORNAME;
echo <<<EOF
function validateForm() {

var myForm = document.forms["myForm"];

if (myForm.name.value == "") {
// This is what I'm trying to localize!
alert("$errorname");
myForm.name.focus();
return false;
}

}
EOF;
?>

guvenck
07-27-2007, 12:50 PM
Hi Aerospace, that answer was fast!

Could there be an easier way to do this? lang_english.php includes already all the strings and I have some forms which almost have 100 variables, so defining each variable again would supersize the file, I guess.

_Aerospace_Eng_
07-27-2007, 12:55 PM
Without using heredoc you would have to echo out each line of the js file, then you would just concatenate the constants where needed.

<?php
header("Content-Type: text/javascript");
include('lang_english.php');
echo "alert('"._ERRORNAME."');";
?>
You really should be doing the validation server side. Seriously 100 variables? Are you kidding? What the heck are you submitting?

guvenck
07-27-2007, 02:20 PM
You really should be doing the validation server side. Seriously 100 variables? Are you kidding? What the heck are you submitting?


No, I am not :) I am already doing a validation on server side. I am doing the javascript validation to prevent the "heck" from being submitted in case there is an error :)

Please check your PM :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum