Jump to content

Included Javascript AND PHP


AndieB

Recommended Posts

Hi all,

 

I've got a Javascript code (in an external file) that has the function to validate values in a FORM. Now, I've created my webpage to support more than one language, this by creating a lang.php file where variables are set.

 

As an example eng.lang.php looks like this:

$langpack["title"] = "Welcome!";

 

and for another language, Swedish, the "almost" same file looks like this:

$langpack["title"] = "Välkommen!";

 

Based on the visitors selection of language, the relative language file is included.

 

My question now is:

 

Is it possible to put PHP variables in a Javascript, so that it is processed when the page is loaded and the PHP variables are replaced with values that Javascript can interpret?

 

In my current Javascript code for validating the FORM, is something is not according to my rules, an ALERT box appears, but the text is in English. I would like to be able to use my *.lang.php files variables together with Javascript, so the ALERT boxes displays the message in the language that the visitor has choosen.

 

Am I clear with what I want to achieve?

 

Thank you in advance!

 

Sincerely,

Andreas

Link to comment
Share on other sites

i see your php vars are arrays. you could simply make php build a jsarray from your php array like so

/**
* Returns a jsArray in string format
* @param array $array
* @param string $name
* @return string
*/
function jsArray($array,$name){
$jsArray="var {$name} = new Array();\n";
foreach($array as $key=>$val){
	$jsArray.=(is_numeric($val))?"{$name}['{$key}']={$val};\n":"{$name}['{$key}']=\"{$val}\";\n";
}
return $jsArray;
}
$langpack=array();
$langpack["title"]="some tite";
$langpack["error"]="some error";
$langpack["someothercrap"]="someothercrap";

echo jsArray($langpack,"jsarray");//this will be a jsarray

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.