How can i start javascript via ajax ?
html file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>FusionCharts 3.0 Dashboard</title>
<script language="JavaScript" src="../FusionCharts.js"></script>
<script language="JavaScript" src="../PowerMap.js"></script>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","test.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="chart3" align="center"></div><br />
<div id="ajax"></div>
<input type="button" onclick="loadXMLDoc()" value="test" />
</body>
</html>
php file
<?
$html = '<script type="text/javascript">
window.onload = function start() {
onClick();
}
function onClick() {
var myChart = new FusionCharts("../Charts/HLinearGauge.swf", "chart3", "580", "80", "0", "0");
myChart.setDataXML("<chart bgColor=\'FBFBFB\' bgAlpha=\'100\' showBorder=\'0\' chartTopMargin=\'0\' chartBottomMargin=\'0\'\n\
upperLimit=\'30\' lowerLimit=\'0\' ticksBelowGauge=\'1\' tickMarkDistance=\'3\' valuePadding=\'-2\' pointerRadius=\'5\'\n\
majorTMColor=\'000000\' majorTMNumber=\'3\' minorTMNumber=\'4\' minorTMHeight=\'4\' majorTMHeight=\'8\' showShadow=\'0\'\n\
pointerBgColor=\'FFFFFF\' pointerBorderColor=\'000000\' gaugeBorderThickness=\'3\'\n\ baseFontColor=\'000000\'\n\
gaugeFillMix=\'{color},{FFFFFF}\' gaugeFillRatio=\'50,50\'>\n\
<colorRange>\n\
<color minValue=\'0\' maxValue=\'5\' code=\'FF654F\' label=\'z\'/>\n\
<color minValue=\'5\' maxValue=\'15\' code=\'F6BD0F\' label=\'x\'/>\n\
</colorRange>\n\
</chart>");
myChart.render("chart3");
}
</script> ';
echo $html;
?>
For a start, you're defining a window.onload event AFTER the page has loaded - by the time the user clicks the button, that event will have been fired long ago
If you're using jQuery, change the window.onload = function start() to $(document).ready(function(), then add a ");" at the end of the function.
For Prototype, use document.observe("dom:loaded", function()
Though it'd probably make more sense to just call the function, or even just remove the function and execute the statements straight
As for the JS not executing - I've experienced that niggle before, it's because innerHTML doesn't run any JS that's inserted. If you're using jQuery, try $('ajax').append(xmlhttp.responseText), or Element.insert($('ajax'), xmlhttp.responseText) for Prototype.
Though judging by the fact you've implemented the AJAX call yourself, you're probably not using any libraries. In that case, it'd be easier to make your PHP file return just the JS without the tags, then just eval(xmlhttp.responseText)
If you don't want to do that, then you'll need to loop through all of the script tags in the response X(HT)ML and eval their contents 'manually'
Using Javascript frameworks make things really easy. For example, if you use jQuery, you can do what you want this way:
$.getScript("test.php");
It gives you some advantages... for instance, you won't have to worry about problems with memory leaks in IE. It will work on most of the web browsers and it will make your code easier to read.
You probably have to call the function you want, i.e. onClick, manually after setting the innerHTML.
All of that javascript you have in the PHP file, you need to put that into the html file. Well, that's the way I'd do it at least. Otherwise, you'll have to use jQuery's live() function to call those javascript functions you have in the PHP file.
For instance, your script tag in the html file should look like this
<script type="text/javascript">
function Function4PHPHTML() {
var myChart = new FusionCharts("../Charts/HLinearGauge.swf", "chart3", "580", "80", "0", "0");
myChart.setDataXML("<chart bgColor='FBFBFB' bgAlpha='100' showBorder='0' chartTopMargin='0' chartBottomMargin='0'\n
upperLimit='30' lowerLimit='0' ticksBelowGauge='1' tickMarkDistance='3' valuePadding='-2' pointerRadius='5'\n
majorTMColor='000000' majorTMNumber='3' minorTMNumber='4' minorTMHeight='4' majorTMHeight='8' showShadow='0'\n
pointerBgColor='FFFFFF' pointerBorderColor='000000' gaugeBorderThickness='3'\n baseFontColor='000000'\n
gaugeFillMix='{color},{FFFFFF}' gaugeFillRatio='50,50'>\n
<colorRange>\n
<color minValue='0' maxValue='5' code='FF654F' label='z'/>\n
<color minValue='5' maxValue='15' code='F6BD0F' label='x'/>\n
</colorRange>\n
</chart>");
myChart.render("chart3");
}
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","test.php",true);
xmlhttp.send();
}
</script>
Then, you have the AJAX, retrieve only HTML from that PHP file.. So that after you click that DIV and populate whatever, you already have the existing Javascript ready for the new html.
The only way to do this is by, through some way or another, eval()ing the script that you're loading in via AJAX, in the AJAX call. Scripts are normally only evaluated if they're there on pageload, and new content loaded in via the DOM/AJAX isn't evaluated for scripts (for one thing, onload() fired a long time ago) so you have to manually call any scripts you're AJAXing in.
As has been mentioned above, frameworks make this easier - the evalScripts flag in Prototype, or just the evalScripts function, are really nice for this in my experience, and jQuery's live() or getScript are also an option.
If you're not using a framework, you'll have to do it manually, by calling eval() on the script that you're trying to load via AJAX. So your code would look something like this:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax").innerHTML=xmlhttp.responseText;
eval(xmlhttp.responseText);
}
}
You may not even need to set the innerHTML if the Javascript is all you're using it for. A caution: using eval() should as a rule make you wary due to the possibility of injection attacks. The frameworks above do some sanitizing and safety checks to more safely execute the scripts, but it's still a risky proposition.
If you can, you should consider rewriting your code to have the AJAX return JSON or some other data structure, and move the actual javascript into the recieve function (where I inserted the eval() above), to avoid such risks. In your code, depending on why you need to have the Javascript in the other file, you could probably easily pass the parameters you're generating the script for in a JSON array, and call the new FusionCharts() and mychart.render() within your AJAX call. That would look something like this:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax").innerHTML=xmlhttp.responseText;
cd = JSON.parse(xmlhttp.responseText);
var myChart = new FusionCharts(cd.chartPath, cd.chartID, cd.chartWidth, cd.chartHeight, 0, 0);
myChart.setDataXML(cd.dataXML);
myChart.render(cd.chartID);
}
}
With your AJAX returned being:
{
chartPath: "../Charts/HLinearGauge.swf",
chartID: "chart3",
chartWidth: "580",
chartHeight: "80",
dataXML: "<chart bgColor=\'FBFBFB\' bgAlpha=\'100\' showBorder=\'0\' chartTopMargin=\'0\' chartBottomMargin=\'0\'\n\ upperLimit=\'30\' lowerLimit=\'0\' ticksBelowGauge=\'1\' tickMarkDistance=\'3\' valuePadding=\'-2\' pointerRadius=\'5\'\n\ majorTMColor=\'000000\' majorTMNumber=\'3\' minorTMNumber=\'4\' minorTMHeight=\'4\' majorTMHeight=\'8\' showShadow=\'0\'\n\ pointerBgColor=\'FFFFFF\' pointerBorderColor=\'000000\' gaugeBorderThickness=\'3\'\n\ baseFontColor=\'000000\'\n\ gaugeFillMix=\'{color},{FFFFFF}\' gaugeFillRatio=\'50,50\'>\n\ <colorRange>\n\ <color minValue=\'0\' maxValue=\'5\' code=\'FF654F\' label=\'z\'/>\n\ <color minValue=\'5\' maxValue=\'15\' code=\'F6BD0F\' label=\'x\'/>\n\ </colorRange>\n\ </chart>"
}
Try to use jquery.live()
Related
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("abc=123");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
<?php if(isset($_POST['abc'])) {
$test123 = 'worked';
}
?>
}}
var worked = '<?php echo $test123;?>'; // <--- this is not working
How can I make this work? I don't receive the variable in PHP whether I use get or post methods.
You seem to have two fundamental misunderstandings. One is about AJAX, and the other is about client side vs. server side code. The latter is more important.
Server vs. Client
Essentially PHP and JavaScript are totally agnostic to each other. They do not run in parallel. In this context, they don't even run on the same machine (the PHP code runs on your server, the JavaScript on the user's computer). The only communication each script can do with the other is via HTTP.
It's test.php that needs to have the code
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
?>
As long as test.php exists, this should work, but I'm thinking of it as a standalone script.
Using AJAX
Because of the asynchronous nature of AJAX and its HTTP dependency, you can't rely on when an ajax request will complete or even if it will complete. That is to say that any code that depends on the result of an AJAX call must be done in the ajax response callbacks.
That is, you would do something like this:
//php
<?php if (isset($_POST['abc']) { echo json_encode(array('success' => true)); }
//JavaScript
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (JSON.parse(xmlhttp.responseText).success) {
console.log('it worked!');
}
}
Additionally to what #Explosion Pills explained this means the php inside the ajax doesn't work as you expect.
At the place inside test.php put this:
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
echo $test123;
?>
Then in the code you have up there replace this:
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
?>
by:
var worked = xmlHttp.responseText;
and finally remove this last line:
var worked = '<?php echo $test123;?>';
And check out what happens.
I need help figuring out how i can setInterval while keeping a "str" to the function.
The client chooses an option, and the function "GET"'s the selected option.. But when it refreshes in setInterval, it looses the string.. How can i do this?
I have tried this:
<script type="text/javascript">
function countrystats(str)
{
if (str=="")
{
document.getElementById("countrystats").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("countrystats").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","countrystats.php?q="+str,true);
xmlhttp.send();
setInterval(countrystats, 5000);
}
</script>
Hopefully you can help me sort out this mess :-)
I am aware that this can be done with some jQuery, but i cat seem to get that to work. Maybe those two things are related, i dont know :-)
Here is how the function countrystats gets its input:
script type="text/javascript">
$("#countrystats_menu > li > a").click(function (ev) {
var str = $(this).html();
countrystats(str);
$('#country_span').html(str);
});
</script>
EDIT/Solution:
It seems that the problem was, when doing setInterval, it looses the str attached, this code is however preserving it.
setTimeout((function(strPriorToTimeout)
{//IIFE's scope preserves state of str variable
return function()
{
countrystats(strPriorToTimeout);
};
})(str),5000);
The argument str goes out of scope at the end, the interval simply calls the function without passing any value to str. As some comments suggest, countrystats(str) would appear to do the trick, but it doesn't, here's why:
setInterval(countrystats(str), 500);
This line contains multiple expressions that will be evaluated/resolved to some value, like countrystats(str), which is a direct call to a function. The function, then, will be called prior to the interval being set. The quickest solution is creating an anonymous function, and call the function from within:
setInterval(function()
{
countrystats(str);
},5000);
You can even play it extra safe, by creating a closure, actually passing the intended value of str to the interval function. This is optional, and might look a bit confusing (and messy):
setInterval((function(strPriorToTimeout)
{//IIFE's scope preserves state of str variable
return function()
{
countrystats(strPriorToTimeout);
};
})(str),5000);
There is just one thing that's bothering me about your code: you're using setInterval, which repeats the same function call every X ms. If you only need to call a function once, it might be better using setTimeout.
Another thing is: setInterval returns the interval's id, so you can stop the constant function calls if needed. You don't seem to be assigning that ID anywhere, so your code will keep on running, unless you're brute-forcing the clearInterval calls. Perhaps consider assigning the return value of setInterval to some variable you can access.
If you don't the only way of clearing intervals AFAIK would be:
for (var i=0;i<Number.MAX_VALUE;i++)
{
clearInterval(i);
}
Now that's just terrible, isn't it?
In light of the comments, I thought I'd do well adding some info on webworkers here. From what I gather the OP wants to acchieve, I recommended using webworkers as much as possible. A basic setup here could be:
//client.js
var worker = new Worker('dashWorker.js');//worker script
//to kick off the worker:
function countrystats(str)
{
str = str || document.getElementById('countrystats').innerHTML;//get str value
worker.postMessage(str);//that's it, the worker takes care of everything else
}
worker.onmessage = function(response)
{
document.getElementById('countrystats').innerHTML = response.response;//cf worker code
return countrystats(response.str);//choose when to call the countrystats function again, as soon as the worker responded... easy!
};
//the worker:
self.onmessage = function(e)
{//you could add a way of stopping the constant updates, by posting a 'stopDash' or something...
//do ajax call using e.data --> this is the string anyhow
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(response)
{
if (this.readyState === 4 && this.status === 200)
{
self.postMessage({str: e.data,
response: response.responseText});
}
};
xhr.open('GET', 'countrystats.php?q=' + e.data,true);
xhr.send();
};
Of course, this code is far from "clean": it could do with some performance tweaks (like not querying the DOM all the time), but the basic principal stands...
A couple of important links for you here:
MDN
John Resig's blog post on workers
A step-by-step introduction to webworkers
you are calling setInterval(countrystats, 5000); in the same function. you can do with jquery also
url='countrystats.php?q='+str;
ajax calll
$.get(url, function(data) {
$('#countrystats').html(data);
});
once the get finishes. you can call setInterval(countrystats, 5000); for refreshing the content.
I've simplified your code with jQuery. I've used jQuery.load to load the remote html to the start element.
And whenever a new item is clicked you need to create the previous interval, otherwise multiple request threads will be running
function countrystats(str) {
if (str == "") {
$('#countrystats').empty();
return;
}
$('#countrystats').load('countrystats.php?q=' + str)
}
var interval;
$("#countrystats_menu > li > a").click(function(ev) {
if (interval) {
clearInterval(interval);
}
var str = $(this).html();
countrystats(str);
interval = setInterval(function() {
countrystats(str);
}, 5000);
$('#country_span').html(str);
});
The scenario is , below is the html file through which i want to display the content of a text file at div id="myDiv".
The file will be read by php . The php content is given below.
I am unable to get the content from the text file . Please tell me what should be added in the ajax part to correct the program.
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+tb,true);
xmlhttp.send();
}</script>
</head>
<body>
<div >
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest(myfile.txt)">Change Content</button>
</div>
</body>
</html>
Below is the PHP file
<?php
$tbName = $_GET['tb'];
$file = "/home/$tbName";
$f = fopen("$file", "r");
echo "<ul>";
while(!feof($f)) {
$a= fgets($f);
echo "<li>$a</li><hr/>";
}
echo "</ul>";
?>
Fix quotes
onclick="ajaxRequest('myfile.txt')"
make sure you use encodeURIComponent() on tb
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+encodeURIComponent(tb),true);
Test your php page in the browser: does http://localhost/TBR/getdata.php?tb=myfile.txt provide the data you want?
If so test the function gets called. (Place an alert or debug the code and place a breakpoint within the function, or use console.debug if your browser supports it)
If the function gets called then your event handler is working correctly, if not try to rewrite it or attach it differently like onclick="ajaxRequest('myfile.txt');" though I suspect the missing semicolon isn't the problem.
If that is called you can try to see if the ajax call is carried out my inspecting the network traffic. Any decent browser will let you do that (hit f12 and look for the network tab). You should be able to see the request and response if the ajax request is being issued and responded to.
Supposing that is all working fine, ensure that your event ajax event handler is getting called. I suspect there is an issue here because you are not setting the event handler to a function...
xmlhttp.onreadystatechange = function statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
And failing all of that your data insert code isn't working.
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
Remember to quote the string in the onclick.
Here's a fixed version:
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
if (window.XMLHttpRequest){
var xmlhttp= new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+ encodeURIComponent(tb),true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
</body>
</html>
What was wrong:
the presence of XMLHttpRequest was tested, but the function was not wrapped in an if, making that useless.
The variable names were a little mismatched - double check that
EncodeURI Component, as mentioned below
The proper syntax for a callback function is window.onload = function(){ alert('func!'); } not window.onload = alert(){ alert('load!'); }
That should be it, unless there's a problem with the PHP Script, try testing that out by visiting the URL directly.
I have a main page, call it Main.php. On this page, is a button that when clicked, sets a div's innerHTML (already on Main.php, called divResults) with the results from Results.php.
When Results.php is called, the returned HTML "These Are The Results" is properly received and set as the contents to divResults on Main.php. However, any javascript from Results.php is not executed. As an example, I attempt to do a simple window.alert. Here is example code:
Main.php link button to begin the action:
<img src="$MyImageSource" onclick=\"ExpandDropdownDiv()\" />
Main.php javascript function ExpandDropdownDiv():
function ExpandDropdownDiv(){
if (window.XMLHttpRequest)/* code for IE7+, Firefox, Chrome, Opera, Safari */
{
xmlhttp=new XMLHttpRequest();
}
else
{/* code for IE6, IE5 */
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
{
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Results.php",true);
xmlhttp.send();
}
Results.php code example:
<script type="text/javascript">
alert("Success");
</script>
These Are The Results
------------------ Edit - Update ------------------
The simple alert, from Results.php is just an example. If I were able to get this to work, I believe I could solve the rest of my problem on my own. However, I noticed a few comments suggesting to just place the alert in Main.php's javascript after i set the div's innerHTML. So, let me explain what I truly want to do with the javascript, after the div is set.
Image 1, shows some normal "Select" html elements, that have been transformed using jquery and the dropdown-check-list extension (.js). When the user clicks the colorful down arrow at the bottom, the div expands, (image 2) and two more "Select" elements are generated within this other .php file... the html is returned, and placed in the div. Thus, i do not need to reload the entire page, and can place the new select dropdowns just beneath the existing ones.
The problem is, to "transform" these normal select elements, there is some javascript that needs to be executed against that HTML:
$(document).ready(function() {
$(".MultiSelect").dropdownchecklist( {firstItemChecksAll: true, maxDropHeight: 300 , searchTextbox: true, width: 100, textFormatFunction: function(options) {
var selectedOptions = options.filter(":selected");
var countOfSelected = selectedOptions.size();
var size = options.size();
switch(countOfSelected) {
case 0: return "All";
case 1: return selectedOptions.text();
/* case size: return "All"; */
default: return countOfSelected + " selected";
}
}
}
);
}
So, somehow I need to be able to execute javascript against the HTML that is generated from this other .php file. And simply calling the above code, after my divs innerHTML is filled, only re-generates the already existing dropdowns, not the two new ones.
Example Images
Here is a good read on understanding what you are doing: Eval embed JavaScript Ajax: YUI style
Making your code work with using eval(); but its not recommend for various reasons:
Let's take your php and modify it like this:
<script type="text/javascript">
function result() {
alert("Success");
}
</script>
These Are The Results
and This is the callback function from AJAX. result(); is not executed because it doesn't get evaluated, and thus does not exist. which is in your case
if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
{
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
result(); // this function is embedded in the responseText
// and doesn't get evaluated. I.e. it doesn't exist
}
in order for the browser to recognize the result(); you must do an eval(); on all the JavaScript statements with in the script tags that you injected into the div with id divResults:
if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
{
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
var myDiv = document.getElementById("divResults");
var myscripz = myDiv.getElementsByTagName('script');
for(var i=myscripz.length; i--;){
eval(myscripz[i].innerHTML);
}
result(); //alerts success
}
Easy Way:
The easiest way i would do it is basically remove the JavaScript from the php and display the content, and after callback just do the rest of the JavaScript within the callback function
php:
echo 'These Are The Results';
JavaScript:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
{
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
alert('success'); // or whatever else JavaScript you need to do
}
}
try to wrap the javascript code from Result.php in a function and call it after inserting it like :
<script type="text/javascript">
function result() {
alert("Success");
}
</script>
These Are The Results
and
if (xmlhttp.readyState==4)/* && xmlhttp.status==200) */
{
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
if(result) result();
}
Your results.php needs to be something like...
echo 'eval("function results() { alert(\'success\'); }");';
And then call the results function.
I want to know is it possible to call a php function within javascript, only and only when a condition is true. For example
<script type="text/javascript">
if (foo==bar)
{
phpFunction(); call the php function
}
</script>
Is there any means of doing this.. If so let me know. Thanks
PHP is server side and Javascript is client so not really (yes I know there is some server side JS). What you could do is use Ajax and make a call to a PHP page to get some results.
The PHP function cannot be called in the way that you have illustrated above. However you can call a PHP script using AJAX, code is as shown below. Also you can find a simple example here. Let me know if you need further clarification
Using Jquery
<script type="text/javascript" src="./jquery-1.4.2.js"></script>
<script type="text/javascript">
function compute() {
var params="session=123";
$.post('myphpscript.php',params,function(data){
alert(data);//for testing if data is being fetched
var myObject = eval('(' + data + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
});
}
</script>
Barebones Javascript Alternative
<script type="text/javascript">
function compute() {
var params="session=123"
var xmlHttp;
var addend_1=document.getElementById("par_1").value;
var addend_2=document.getElementById("par_2").value;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("No Ajax for YOU!");
return false;
}
}
}
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
}
xmlHttp.open("POST", "http://yoururl/getjs.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
</script>
No that's not possible. PHP code runs before (server-side) javascript (client-side)
The other answers have it right.
However, there is a library, XAJAX, that helps simulate the act of calling a PHP function from JavaScript, using AJAX and a particularly designed PHP library.
It's a little complicated, and it would be much easier to learn to use $.get and $.post in jQuery, since they are better designed and simpler, and once you get your head around how they work, you won't feel the need to call PHP from JavaScript directly.
PHP always runs before the page loads. JavaScript always runs after the page loads. They never run in tandem.
The closest solution is to use AJAX or a browser redirect to call another .php file from the server.