I need to use a php function inside this script which converts the ID into a required format.
function onlineStatus() {
$.getJSON('updateusers.php', function(data) {
$('#users').html('');
$.each(data, function(i, item) {
$('#users').append('[<span>'+ item.userid +'</span>]');
});
});
setTimeout("onlineStatus()",30000);
}
I have tried the following in various ways but I either get nothing or it fails with a missing ) after the argument list.
$('#users').append('[<span>'<?php nameFormat('+ item.userid +') ?>'</span>]');
I would appreciate your assistance.
PHP functions can only be executed on the server-side. You should probably translate the nameFormat function into javascript so you can use it on the client-side.
If you are trying to run this command on the server side before sending the script to the user, you have forgotten to echo the statement. Either type
$('#users').append('[<span>'<?php echo nameFormat('+ item.userid +'); ?>'</span>]');
or
$('#users').append('[<span>'<?=nameFormat('+ item.userid +')?>'</span>]');
... unless ofcourse the function nameFormat allready does an echo.
It's one side connection. You can use javascript in php, but you can't use php in javascript.
For example:
You can assign variable in php, and than use it in JS.
var a = <?php echo $a ?>;
The same thing you can do with functions ;)
Related
I am just getting used to jquery and have a drop down box that prompts an onchange event:
<select name="department_list" id="department_list" onchange="checkTeacherList(this.value);" >
This works fine and the AJAX command called is:
function checkTeacherList(str)
{
...
xmlhttp.open("GET","http://localhost/iobserve/php/getTeachers.php?departmentName="+str,true);
...
}
However I also want to use the $user_login variable such that:
<select name="department_list" id="department_list" onchange="checkTeacherList(this.value,$user_login );" >
and the AJAX command is:
function checkTeacherList(str, schoolName)
{
...
xmlhttp.open("GET","http://localhost/iobserve/php/getTeachers.php?schoolName="+schoolName+"&departmentName="+str,true); ...
}
but this does not seem to work. What am I doing wrong?
EDIT:
The problem is that as soon as I add a second parameter to the function call from:
onchange="checkTeacherList(var1);"
to
onchange="checkTeacherList(var1, var2);"
the function is not called. Is the syntax wrong using a comma as a separator?
when using more than 1 variable passed with GET you have to add a &:
url?var1=value1&var2=value2&var3=value3...
Also you say you are using jquery, but to me it seems you are using plain javascript, if you want to make a AJAX call using jquery and GET:
$.get("url", {var1: value1, var2: value2}, function(data){
//do something when the AJAX call finishes,
//the var data contains anything echoed by the script called.
});
EDIT: to follow your question.
onchange="checkTeacherList(this.value, '<?php echo $user_login;?>');"
If you are using a PHP variable in a HTML script you have to echo it, also you have to use ' or it will cause a javascript error.
try this
xmlhttp.open("GET","http://localhost/iobserve/php/getTeachers.php?schoolName="+schoolName+"&departmentName="+str,true);
Try like this
checkTeacherList(this.value,<?php echo $user_login;?> );
You need to echo the php variable.and try to put '&' between the two variables you are sending like
xmlhttp.open("GET",
"http://localhost/iobserve/php/getTeachers.php?schoolName="+schoolName+"&departmentName="+str,true); ...
You must include & between the parameters, like
xmlhttp.open("GET","http://localhost/iobserve/php/getTeachers.php?schoolName="+schoolName+"&departmentName="+str,true);
Then in the calling section edit like this,
checkTeacherList(this.value,<?php echo $user_login;?> );
I am calculating the distance between two places using jQuery and I want to pass this value (pickup_distance) for use in PHP.
I am wanting to send this value to tariff.fare.controller.php for use in the following function:
private static function getFare($int_terminate) {
// Function
if pickup_distance(<-- jQuery Value) > 5 {
// Do Something
}
}
How could I go about doing this? I'm aware I can do this via AJAX but being quite new to programming I'm not quite sure how I can do this.
Any help would be much appreciated!
using Jquery it's quite easy:
var your_var_value=1200;
$.post("your_php_script.php", {var_value: your_var_value}, function(data){
alert("data sent and received: "+data);
});
then in your PHP script you get the variable like this:
$distance=$_POST['var_value'];
And what you echo in "your_php_script.php" is returned as the data variable.
As jQuery is client side code and PHP is Server side code, the variables must somehow be passed to the server.
There are a few decent ways of doing this, by far the most common is GET and POST variables.
then you can pick them up in php and do whatever you wish with it.
A very simple example is to have an iframe/php image whatever and just load the src with JavaScript or jquery file.php?EEEE=YYY then fetch that variable $_GET['EEEE']
Best way to do it is to use jQueries built in Ajax functionality. Either use .ajax or .post and send in your required parameters to your PHP script.
I want javascript to be able to call a php script (which just echos a string) using jQuery.
I think $.get is the right way, but not too sure.
I then want to use the returned string as a javascript variable.
$.get() is the way to go, indeed.
First of all, you will need a page / url that outputs the result of the function you want to use (for example, *www.yoursite.com/test_output.php* ). You should create that page and call the function you want to use there.
Also keep in mind that I said output, not return, because .get will fetch the output of the http response, not the returned value of the php function.
So if you have the following function defined in your site (you can also define it in test_output.php, of course):
<?php
function say_hello() {
return 'hello world';
}
?>
In test_output.php, you will need something like this:
<?php
echo say_hello();
?>
Then on the client side, you need some JavaScript / jQuery:
var data_from_ajax;
$.get('http://www.yoursite.com/test_output.php', function(data) {
data_from_ajax = data;
});
Now you have the output of the ajax .get() function stored in data_from_ajax and you can use it as you please.
$.get() is the right way.
$.get('ajax/test.php', function(data) {
// use the result
alert(data);
});
i have javascript as below
html="<th>"+<?php echo __(); ?>+"</th>";
I want to add another javascript variable inside to __() function like this
<?php echo __(<js varible>); ?>
I tried
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
not working for me
can any one help me please
regards
You have a misunderstanding on how server side and client side code work.
The only way that you could possibly achieve what you are trying to do (apply a PHP localization function to a Javascript variable) would be like this (this code assumes you are using JQuery but can be done without it too):
var myvariable = 'hello';
$.get('http://yoursite.com/localize.php?text='+myvariable, function(localizedText) {
html = "<th>"+localizedText+"</th>";
console.log(html);
});
And then localize.php should look like this:
<?php
include('you localization library');
echo __($_GET['text']);
?>
Explanation: while your client side code (Javascript) is been executed in the browser it will call a URL which will execute your server side code (your PHP __(); function) in the server and then return the value to the client side code.
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
This would try to put the PHP variable "myvariable" into the script tag, what you want is closer to:
var myvarible=200;
html="<th>"+"<?php echo __("'myvarible'"); ?>"+"</th>";
console.log(html);
However, in this case, why not just skip PHP completely?
var myvarible=200;
html="<th>" + myvarible + "</th>";
console.log(html);
Javascript runs on client side and php on server side.
So var myvarible=200;
will be executed only on client side .
but will be get executed on server side. at that time myvariable will not be valid.
PHP is executed on the server, JS on the client. You cannot expect PHP to parse JS, in fact PHP will never see the JS statements, because they will be processed only once the server has processed the PHP.
var myvariable='<?php echo __("200"); ?>';
html="<th>"+myvariable+"</th>";
console.log(html);
However for this to work the javascript would need to be in a .php file that is being interpreted.
The OP wants to include a JS variable in a PHP call, which is not possible, unless you use AJAX. And you'll agree with me that code like this is only meant to cause big headaches and should be avoided at all costs.
Well yes and no.. i wouldnt do it this way. I use a helper that lets me do things like this in a consistent way. In my view file i have something like:
<?php js_call('jslib.myFunction(?,?)', __($value), 'some other value'); ?>
js_call its similar to using sprintf or a prepared statement except for js. The params are run through json_encode so the quoting and what not are correct. All these are stored in an array and then in the layout, just before my </body> i call:
<?php include_js_calls(); ?>
which then takes all the calls ive made with a js_call and outputs the string values inside a script tag resulting in something like:
<script type="text/javascript">
jslib.myFunction('first value', 'some other value');
</script>
Borrowed this brilliance from Apostrophe Cms
To do localization in javascript (for whatever reason), echo __() can obviously not be called directly.
There are different possible strategies
Include a localization string table in javascript when the page loads. Do lookup against it when needed. This table could be generated on server-side using echo __() then cached.
Make ajax requests for server-localized data. Might not be suitable for frequent updates.
How do I call PHP variables or queries in JavaScript?
<script>
var foo = <?php echo $foo; ?>;
// or, if foo is a string;
var foo = '<?php echo addslashes($foo); ?>';
// for anything more complex, you'll need to use json_encode, if available in your version of PHP
var foo = <?php echo json_encode($foo); ?>;
</script>
Please note, you can only do this one way. Don't expect any changes you make in javascript to come through to PHP.
PHP and JavaScript cannot mix directly. You use PHP server-side to generate and send JavaScript to the client. the JavaScript executes client-side and can communicate with PHP code on the server only via AJAX calls. This can be simplified drastically through the use of an AJAX library like jQuery.
You have to keep in mind that your PHP code is evaluated on the server, while JavaScript (normally) runs in the browser. The evaluations happen in different times, at different places. Therefore you cannot call a JavaScript function (or variable) from PHP, simply because you cannot call a function that exists on another computer.
You may want to check if Ajax is an appropriate solution for your problem.
Generally, you can't. PHP is server-side and Javascript is client-side (processed by the browser).
The exception is to use AJAX, which allows you to access PHP pages, which should then execute the action needed.
You can use JSON for this purpose which serves well for sending a big array to Javascript from PHP. We need to echo JavaScript code in PHP script or we can use Ajax for this. But usually we may need to send a big array. So we can do like this
<script>
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
?>
var foo = echo json_encode($arr);
</script>
The json_encode function will handle all escaping and other issues. Bug also make sure json_encode is available in your PHP version.