I'm doing the internationalization of a PHP project.
in PHP I use the getttext() function and poedit program.
example:
<?php
echo gettext("Hello world");
?>
Hello World will be the key with the associated translated words:
It all works.
I haven't any idea how to translate the .js file with html function of JQUERY.
For example:
inside javascript file, I have
if(exchange=='mo'){
$(#hopen.title).html("NEW WORD");
}
the question is: How can I call the gettext function to "NEW WORD" and then use it with poedit program?
You don't want to call gettext / php from your javascript file every time you need a translation as that would mean you would have to make an ajax request to the server for each text.
Instead, you could generate an object in php with all the keys and translations that you need and send that to the browser and make it available as a global variable in javascript.
<?php
...
$needed_translations = array(
'Hello world' => gettext("Hello world")
...
);
?>
<script>
var needed_translations = <?php echo json_encode($needed_translations); ?>;
// or
window.needed_translations = <?php echo json_encode($needed_translations); ?>;
</script>
If your javascript file is loaded after this or your code is located in a document ready block, you will have access to this global variable and can use it wherever you want:
if(exchange=='mo'){
$(#hopen.title).html( needed_translations['Hello world'] );
}
Related
I want to use javascript variable as php variable. I am echo php variable then its print. but when i am use for fetching data from database its show an error
Notice: Undefined index: document.write(i)
here my code
javascript
var i=0;
function inc()
{
i+=1;
}
<?php $foo="<script>document.write(i)</script>"; ?>
php
code work for
echo $foo
code not work for
$i=$foo;
$query="select * from TABLE where id = $i";
$result=mysqli_query($conn,$query);
while($row=mysqli_fetch_row($result))
{
echo $row[0];
}
Then It show This Error Notice: Undefined index: document.write(i)
PHP is server-side code that is run to generate a page. Javascript is client-side code that is run after the page is sent to the visitor's browser. Javascript can't affect the server-side code because the server code is done running by the time the Javascript runs. If you want to have a user's selection change the behavior of the PHP code the next time the form is loaded, pass a variable through a $_POST variable when the form is submitted.
If you want your PHP and Javascript code to be using the same value, have the PHP code write a Javascript variable initialization into the page's <head> section before any Javascript would run that would need to use it.
<script>
var i=0;
function inc()
{
i+=1;
return i;
}
</script>
<?php
$foo = '<script type="text/javascript">document.write(inc());</script>'; //Script function call which return the var i value to php variable
echo $foo;
?>
I'm trying to make my website multilingual, i have the php code also and i have translated files, but my site has also js file where is this words which i want to translate, there is example of this php code and how to insert it to js file?
There is JS code
// Update search list
rsParent.html($('<div>').attr({id: 'relatedSearches', class: 'contentBox'})
.append($('<div>').addClass('cbHead').text('Related Searches'))
.append($('<div>').addClass('cbBody').html(list)));
}
});
and the word "Related Searches" i want to replace with this php code
<?php echo $lang['CHARTS']; ?>
It is not possible to do it directly since PHP is a serverside language which is executed once on a webserver, unlike javascript that is executed in client's browser.
What you can do is encode your PHP array $lang to JSON and then output it as inline javascript and assign it to a variable in javascript.
<?php
echo "<script>";
echo "var lang = " . JSON_encode($lang) . ";";
echo "</script>";
?>
Make sure this php code is placed (executed) before your javascript file because variable lang has to be declared before your javascript is executed.
How to execute javascript+php in another file in current.js file?
The scenario as follows:
another-file.js
function foo()
{
var a = <?php echo "Hello world !"; ?>
}
current.js
function show()
{
var b = "Hi,";
// execute javascript (with php code embeded)
require(another-file.js) // <-- this is not work
alert(a + b); // I want result: "Hi, Hello World !"
}
You can use PHP to generate the string that is assigned to a JS variable like so:
var myvar = "<?php echo "Hello World"; ?>";
In your example you forgot the quotes around the PHP tags (before <?php and after ?>) so you were probably getting errors because the JS interpreter was looking for varables called Hello and World instead of considering "Hello World" as a string.
Now as we know, you can't have includes in JS as you would in other languages, what people normally do is just using multiple <script> tags to include more than one JS into the page. However, if for some reason that I ignore, you absolutely need to include the JS into another JS, what you can do is using jquery's getScript(), see here for more info https://api.jquery.com/jquery.getscript/:
$.getScript( "another-file.js" )
.done( function() {
alert(a + b);
})
.fail( function() {
console.log("Ooops there was a problem");
});
EDIT: as I said in my other comment you can also send an AJAX query and then eval() (which is what getScript() does behind the scenes), or you can use ES6 modules, but that's beyond the scope of this question.
There's a couple things wrong here.
You cannot execute PHP code in a JavaScript file. PHP is a server-side language, JavaScript is (traditionally) a client-side language. You can't execute PHP code with a JavaScript interpreter, or vice versa.
You cannot include a JavaScript file from another JavaScript file. Rather, you must include both scripts on a webpage, like this:
<body>
<script src="file1.js"></script>
<script src="file2.js"></script>
<script>
functionFromFile1();
functionFromFile2();
</script>
</body>
I feel like there is a disconnect here that needs to be resolved.
I have a form that gets submitted.
Now I would like to retrieve the submitted data with javascript on the next page.
This works just fine when I put it in the body of the html:
<script>
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["form_input_name"]);
</script>
Now I want to have this functionality in a jQuery plugin method.
I tried the following in my jquery plugin:
$.pluginname.test = function() {
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["form_input_name"]);
};
But when I try to execute it in the body of the html, I get the following error messages:
[Error] SyntaxError: Unexpected token '<'
[Error] TypeError: undefined is not an object (evaluating
'$.pluginname.test')
Why is this code-snipped working in a regular Javascript environment but not when called by a jQuery plugin?
Your PHP tags are being evaluated as JavaScript. That means that PHP is not processing them.
Presumably, this is because you have moved the script to a .js file.
While it is possible to generate a JavaScript file from PHP, that won't help you here: The data you are trying to generate is being submitted to the PHP script that generates your HTML document.
Move the script back between <script> and </script> in the PHP file that generates the HTML.
if this code:
$.pluginname.test = function(){};
is in external js file then you can't assign a php code values to it. It will cause errors. So i have one solution for it like make a args based plugin like:
$.pluginname.test = function(phpObj){
document.write(phpObj["form_input_name"]);
};
and you can call this on your php/html page in the script block like:
<script>
$.selector.test(<?php echo json_encode($_POST); ?>);
</script>
If you want to create a jQuery plugin:
$.fn.pluginname = function() {
var $_POST = 'SOME TEXT HERE';
$(this).text($_POST);
};
$('.el').pluginname();
Demo: http://jsfiddle.net/bfjLo02m/
Note: Make sure jQuery is included before
EDIT:
Since you've placed the plugin in a separate .js file you'll need to pass the PHP variables to your plugin in the index.html file. Here is an example:
// pluginname.jquery.js <-- separate file for your plugin
$.fn.pluginname = function(options) {
$(this).text(options.var1);
};
// index.html (or any html file)
$('.el').pluginname({ var1: $_POST["somePHPVar"], var2: 'var2Value' });
For example i declare some variable like test in server side of my PHP
echo('var test = ' . json_encode($abc));
Now i want to use this test variable in Jquery ..how can i use it?
What function do i need to use it?
For Example i have:
I have back end PHP code something like this
$abc = no
echo "var test= ".json_encode($abc);
I want jquery to do the following action(client side)
$(document).ready(function(){
function(json) {
if($abc == no )//this i what i want to be achieved
}
}
I think, you dont understand the diference between frontend (JavaScript) and backend (PHP). You can not directly access php variables from javascript. You need to make Ajax-request to some php file, that will return some data that you need in format that you specify.
for example:
<?php
$result = array('abc' => 'no');
echo json_encode($result);
?>
This is serverside script called data.php. In Javascript you can make so:
$(document).ready(function(){
$.getJSON('data.php', function (data) {
if(data.abc === 'no') {
your code...
}
});
}
You're comparing the wrong variable:
<?php
echo <<<JS
<script type="text/javascript">
var test = {json_encode($abc)};
$(document).ready(function(){
if(test == 'no' )
// here you go
}
});
</script>
JS;
If you really wanted to (though I don't think this is a very good practice), you could echo the PHP variable's value into a javascript variable like this:
<script type="text/javascript">
var phpValue = <?php echo $abc; ?>;
alert(phpValue);
</script>
I can see this being dangerous in many cases, but what this effectively does is echo the value of $abc onto the page (inside of your script tags of course). Then, when the javascript it run by the browser, the browser sees it like this:
<script type="text/javascript">
var phpValue = no;
alert(phpValue);
</script>
This is very basic, but you get an idea of what you could do by using that kind of code.