Reputation: 331
I Want to execute a php function inside the jquery function .html(). The php function takes 2 integers as parameter.
This code works
$(function() {
var myVar = 1;
$('#myDiv').html('<? echo my_function('+myVar+','+1+'); ?>');
});
and this one doesn't:
$(function() {
var myVar = 1;
$('#myDiv').html('<? echo my_function('+myVar+','+myVar+'); ?>');
});
I don't have a php error, but nothing happens
Upvotes: 0
Views: 56
Reputation: 17797
I just tried it. So, what happens is this: The PHP parser only cares what's inside the <? ?>
tags, nothing else. So it sees this:
echo my_function('+myVar+','+1+');
The function is called with two Parameters, both strings: +myVar+
and +1+
. You can check that by putting this in your function:
function my_function() {
$argv = func_get_args();
var_dump($argv);
}
It will output this:
array(2) {
[0]=>
string(7) "+myVar+"
[1]=>
string(3) "+1+"
}
After the PHP generated file is served the client sees this:
$(function() {
var myVar = 1;
$('#myDiv').html('The output of your my_function()');
});
Your JavaScript variable now isn't used anymore.
If you want to print content with a already known ID you can either define the variable in PHP or use a $_GET
or $_POST
variable to set it in PHP.
If you want to use a dynamic value you will need an AJAX call to another file (where you will have to do what I suggested above).
Mixing PHP and JavaScript like you did is just not possible.
Upvotes: 0
Reputation: 7756
You are doing a wrong method, You cant use this method, var myvar; is a javascript variable,That will only available in your browser.But my_function() executed in web server;You can put a php variable in javascript,But not possible to use a javascript variable as argument in php function.make myvar as a php variable,if possible then put it into your function.Or you can use ajax to pass a javascript variable to php function.
Put your function into a php file,Then
$('#mydiv').load('file.php?myvar='+myvar);
is possible,You can get the value in $_GET['myvar']
Upvotes: 1
Reputation:
write a file.php
<?php
my_function(myvar,1);
?>
and in html page use
$('#mydiv').load('file.php');
Upvotes: 1