Jump to content

PHP code inside Javascript - How to handle it?


XRS

Recommended Posts

Hello,

 

I'm here with a question that maybe silly for most of you but I just can't handle it.

As I know, there's no way in built in PHP inside JS because diferent kind of languages ( Server Side and Client Side ).

 

But I have a problem that I need help to handle.

 

I have a multilanguage system in my site ( PHP ) and form validations ( JS ).

I have the error messages showed by JS instantly, but I can only print text, not a PHP variable info.

 

For example:

$(function()
{
	// validate signup form on keyup and submit
	$("#loginform").validate({
		rules: {
			user: "required",
			password: "required",
		},
		messages: {
			user: "Please enter your username or email.",
			password: "Please enter your password",
		}
	});
}); 

And my multilanguage system uses the following system:

$lang['login_error'] = 'Incorrect details provided.'; 

There is any way to make something like this:

$(function()
{
	// validate signup form on keyup and submit
	$("#loginform").validate({
		rules: {
			user: "required",
			password: "required",
		},
		messages: {
			user: <?php echo $lang[login_error']; ?>,
			password: "Please enter your password",
		}
	});
});  

 I know this doesn't work, but it's to make an easy example in what I need, because depending the language the user as choosen, the error should be there in that language, not only in one language.

 

Could you please help me to handle this ? Thanks in advance.

There is any way to make something like this:

Use json_encode when outputting variables:

$(function()
{
	// validate signup form on keyup and submit
	$("#loginform").validate({
		rules: {
			user: "required",
			password: "required",
		},
		messages: {
			user: <?php echo json_encode($lang['login_error']); ?>,
			password: "Please enter your password",
		}
	});
});  
This is assuming your JS is within the PHP page. If it's in a separate .js file you'll need to either make the JS file parsed by PHP or possibly load the messages w/ ajax or similar.

You can define your language variables as a global javascript variable in your page and use that variable in your validation function

for example, in your php page add the following (You might want to only print out the error messages used by your javascript instead of the entire language array).

<script type="text/javascript">
var $lang = <?PHP echo json_encode($lang); ?>;
<script>

and in your javascript validation file, you can use the language variable as

user: $lang['login_error'],

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.