I just started this book - "AJAX and PHP Second edition" and I failed on the very first example.I'm pretty sure the code is just as it is shown in the book, but still when I run index.htm in the error console(Mozzila 6.0) I get this : "xmlResponse is NULL http://localhost/ajax/quickstart/quickstart.js.I don't know what's going on but really don't want to give up at the very begining so I'll pase all the 3 files and hopefully anyone would point me where the problem is.
Here is the index.htm :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX with PHP, 2nd Edition: Quickstart</title>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload="process();">
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" ></div>
</body>
</html>
here is the quickstart.js :
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
// stores the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer 6 or older
if(window.ActiveXObject)
{
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else
{
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process(name)
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(
document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send();
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
// callback function executed when a message is received from the
//server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed
//successfully
if (xmlHttp.status == 200)
{
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML
//structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// display the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage
+ '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else
{
alert("There was a problem accessing the server: " +
xmlHttp.statusText);
}
}
}
and finally the quickstart.php :
<?php
// we'll generate XML output
header('Content-Type: text/xml');
// generate XML header
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
// create the <response> element
echo '<response>';
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don\'t know you!';
// close the <response> element
echo '</response>';
?>
Thanks in advanced!
Leron
There are a couple of problems I found with your code. Mentioning some of them
You are calling the process() on body-onload. This means, when the DOM is ready, the browser calls the process() function. This, IMO, is not something you would want. Instead, have a button, which calls this process function with the onclick event. Something like:
<button onclick="process('YODA');return false;">Click Me!</button>
Process is defined as taking one parameter called name, you are passing none. So, make a fix something like this:
<button onclick="myProcess();return false;">Click Me!</button>
And is your JS section/file
function myProcess(){
process(encodeURIComponent(document.getElementById('myName').value));
}
Do not have that document.getElementById(..) inside the process function. It defeats the entire purpose of passing that parameter 'name'
I would ask you to use a really good browser like Mozilla Firefox, or Google Chrome (since you seem to give IE6 a prefence in your code, atleast seems like it!). Chrome has a fantastic inspector window. Once you get the hang of it, you will almost fall in love with it. I did! ;-)
I would suggest, you use libraries like jQuery(www.jquery.com) or something, for ajax. Makes your life easier! :-)
EDIT
I would suggest the following steps, since you want to get this piece of code working.
First open the url [BASE-URL]/quickstate.php?name=YODA. If everything is just fine, you should see the XML that should be the response to your AJAX call. If not, there's some problem with the PHP file(or a few settings of your server), and not anything else. I feel this step wouldn't be a problem.
Next, once the page is loaded, type 'YODA' in the textbox, type this in the browser's URL box: javascript:process(''). This should call the function that has the ajax call. You could keep a tab on the data transferred section of the firebug(I dont know the name exactly, but its the 'Network' section in Google Chrome). You could analyse the headers sent to the PHP scripts, and the response (including the HTTP error codes) sent back to you from the server. I also feel this wont be a problem.
What causes the problem is: The DOM of the page is loaded. The AJAX call is made once the DOM is ready. This means the AJAX request is made even before you type anything in that textbox. And thus, the request that goes to the server has a empty value for name parameter. This is exactly, (IMO) the reason why things are not working for you. But even then, this is not the reason why you see a null for XML out there. Could you do a console.log(xmlHttp) and tell us the results?
That all looks correct. Where are hosting the PHP script? On a local installation of Apache, or a server you have access to? In Firefox, you can install the incredible Firebug add-on, go to the scripts tab, and see exactly what the request is returning. Whatever it is, Fx isn't recognising it as XML (hence the xmlResponse member being NULL).
Related
Is there a way I can run a php function through a JS function?
something like this:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php
query("hello"); ?>";
}
</script>
<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
Plain Javascript
In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
test
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
With a javascript library (jQuery et al)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
AJAX on MDN - https://developer.mozilla.org/en/ajax
XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
jQuery - http://jquery.com/download/
jQuery.ajax - http://api.jquery.com/jQuery.ajax/
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
The only way to execute PHP from JS is AJAX.
You can send data to server (for eg, GET /ajax.php?do=someFunction)
then in ajax.php you write:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
I have a way to make a Javascript call to a PHP function written on the page (client-side script). The PHP part 'to be executed' only occurs on the server-side on load or refreshing'. You avoid 'some' server-side resources. So, manipulating the DOM:
<?PHP
echo "You have executed the PHP function 'after loading o refreshing the page<br>";
echo "<i><br>The server programmatically, after accessing the command line resources on the server-side, copied the 'Old Content' from the 'text.txt' file and then changed 'Old Content' to 'New Content'. Finally sent the data to the browser.<br><br>But If you execute the PHP function n times your page always displays 'Old Content' n times, even though the file content is always 'New Content', which is demonstrated (proof 1) by running the 'cat texto.txt' command in your shell. Displaying this text on the client side proves (proof 2) that the browser executed the PHP function 'overflying' the PHP server-side instructions, and this is because the browser engine has restricted, unobtrusively, the execution of scripts on the client-side command line.<br><br>So, the server responds only by loading or refreshing the page, and after an Ajax call function or a PHP call via an HTML form. The rest happens on the client-side, presumably through some form of 'RAM-caching</i>'.<br><br>";
function myPhp(){
echo"The page says: Hello world!<br>";
echo "The page says that the Server '<b>said</b>': <br>1. ";
echo exec('echo $(cat texto.txt);echo "Hello world! (New content)" > texto.txt');echo "<br>";
echo "2. I have changed 'Old content' to '";
echo exec('echo $(cat texto.txt)');echo ".<br><br>";
echo "Proofs 1 and 2 say that if you want to make a new request to the server, you can do: 1. reload the page, 2. refresh the page, 3. make a call through an HTML form and PHP code, or 4. do a call through Ajax.<br><br>";
}
?>
<div id="mainx"></div>
<script>
function callPhp(){
var tagDiv1 = document.createElement("div");
tagDiv1.id = 'contentx';
tagDiv1.innerHTML = "<?php myPhp(); ?>";
document.getElementById("mainx").appendChild(tagDiv1);
}
</script>
<input type="button" value="CallPHP" onclick="callPhp()">
Note: The texto.txt file has the content 'Hello world! (Old content).
The 'fact' is that whenever I click the 'CallPhp' button I get the message 'Hello world!' printed on my page. Therefore, a server-side script is not always required to execute a PHP function via Javascript.
But the execution of the bash commands only happens while the page is loading or refreshing, never because of that kind of Javascript apparent-call raised before. Once the page is loaded, the execution of bash scripts requires a true-call (PHP, Ajax) to a server-side PHP resource.
So, If you don't want the user to know what commands are running on the server:
You 'should' use the execution of the commands indirectly through a PHP script on the server-side (PHP-form, or Ajax on the client-side).
Otherwise:
If the output of commands on the server-side is not delayed:
You 'can' use the execution of the commands directly from the page (less 'cognitive' resources—less PHP and more Bash—and less code, less time, usually easier, and more comfortable if you know the bash language).
Otherwise:
You 'must' use Ajax.
I have a problem with my chat system on my website. It keeps sending XHR Finished loading in the console. I know that i can disable it in chrome but other users who are using the site should not need to go through that process. It sends the message every one second as you see in setinterval and i want it to only send it when something in database has been added/deleted/changed
I link my js here:
function ajax() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
document.getElementById('chatbox').innerHTML = req.responseText;
}
}
req.open('GET', 'includes/chatbox.php', true);
req.send();
}
setInterval(function(){ajax()},1000);
That should be the only thing that needs to be edited but let me know if you need to see the php code or html code too.
UPDATE: Interwebs suggests people seeing that XHR Finished loading are just you and those who are logging ajax requests. Uncheck Log XMLHttpRequests in the console's context menu. See here. Don't worry; it doesn't impact user experience at all for your users: logging of ajax requests is disabled by default so 99% of users won't actually log it, the console is hidden by default and the cost of a console.log is insignificant even on a Pentium machine from the 1990s.
Even if you would disagree, actually all you can do is worry; if Facebook can't stop those logs from showing up, neither can you :) You're fine.
Not sure what you mean, but try this; maybe it will make your problem more evident and you can ask better:
server.php
<?php
header("Access-Control-Allow-Origin: *");
echo "hi!";
client.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id='chatbox'></div>
<script>
function ajax() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
document.getElementById('chatbox').innerHTML = req.responseText;
}
}
req.open('GET', 'http://localhost:1234/', true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
</body>
</html>
Run the server with
php -S localhost:1234 server.php
Open client.html on your browser and see if your problem is still happening.
Some ideas:
When you say "It keeps sending XHR Finished loading in the console", do you mean "in the networking tab"? If so, there's nothing you can do; if you send a request every second, it will appear there every second.
The client-side (html code) doesn't know about the DB state change, so that's why you are polling every second. If instead, you want the server-side (php code) to tell you when the DB state changes, you need to use some form of WebSockets. PHP is not ideal for that, but you can try something like Ratchet.
I have this bit of java script that is just grabbing an ID off a website and passing it to another php script on a seperate domain:
javascript is on:
https://myspot.com
and is going to
http://theotherwebsite.edu
This was more or less working, I had to work a previous cross site solution that now seems not to be honored on firefox 23 and IE10.
The previous solution was using something like this:
var isIE10 = false; //this is beacuse stupid IE10 now does not work with the window.XDomainRequest
/*#cc_on
if (/^10/.test(#_jscript_version)) {
isIE10 = true;
}
#*/
console.log(isIE10);
var isIE8 = window.XDomainRequest ? true : false;
var invocation=createCrossDomainRequest();
function createCrossDomainRequest(url, handler)
{
var request;
if ((isIE8) && (!isIE10)) //tried to hack my own isIE10 fix didnt work
{
request = new window.XDomainRequest();
}
else
{
request = new XMLHttpRequest();
}
return request;
}
function callOtherDomain()
{
if (invocation)
{
if("withCredentials" in invocation) //was taking a stab in the dark with this.
{
invocation.onload=outputResult;
invocation.open("GET", url, true);
invocation.send();
}
else if(isIE8)
{
invocation.onload = outputResult;
invocation.open("GET", url, true);
invocation.send();
}
else
{
invocation.open('GET', url, true);
invocation.onreadystatechange = handler;
invocation.send();
}
}
else
{
var text = "No Invocation TookPlace At All";
var textNode = document.createTextNode(text);
var textDiv = document.getElementById("textDiv");
textDiv.appendChild(textNode);
}
}
function handler(evtXHR)
{
if (invocation.readyState == 4)
{
if (invocation.status == 200)
{
outputResult();
}
else
{
alert("Invocation Errors Occured " + invocation.status + " state: " + invocation.readyState);
}
}
}
function outputResult()
{
var response = invocation.responseText;
//get JSON of response
var obj = JSON.parse(response);
var mtype = obj.messagetype;
var output = obj.message;
var url = obj.url;
if(mtype=="error")
{
parent.location=url;
}
else if(mtype=="warning")
{
var answer=confirm(output);
if(answer)
parent.location=url;
}
//var textDiv = document.getElementById("textDiv");
//textDiv.innerHTML += response;
}
callOtherDomain();
So I am not sure what is going on here, I get on firefox 23 an error in the console:
Blocked loading mixed active content "http://theotherwebsite.edu"
I know this is because the main script is loaded on https, vs http. But it was not caring before. I also am aware of this error puts a shield up in the address bar of firefox where the user can tell it to enable the blocked content. This is not an acceptable solution for me. Also if i put my silly little php script under https, that is a certificate I need too?
Then IE10 just doesn't work:
SCRIPT5: Access is denied.
landing, line 64 character 421
So I am not sure what I need to do to get my code working again, having the user adjust the browser isn't feasible cause this is distributed enterprise wide, it was for a nag screen to let them know to change their password based on some ldap entry that the php file accesses with the ID passed from the website via ajax.
I was doing some googling but found nothing, most I found was the php handle to make the website I guess CORS compatible:
<?php
header('Access-Control-Allow-Origin: *');
Which I implemented originally as well. So not sure what to try or where to look next? It is a simple JSON string that comes back, can I try the preflight method as described here:
http://ppe.blogs.msdn.com/b/ie/archive/2012/02/09/cors-for-xhr-in-ie10.aspx
??? if i do I am not sure what the headers should look like.
I was going to post the firefox 23 response header but it never makes the request as it straight up blocks the loading mixed active content. So I guess I have two issues to contend with, one that the javascript lives on https and makes a call to http...this might be my only issue in firefox, not 100% sure if i would have cross site issues.
IE10 the network request header is never find and I am looking inside the F12 key pressed area in IE10, under network and I click start capturing before I load the page with the xhr call.
So I guess I am asking what changed in firefox23 and IE10 to not let my code work anymore?
Firefox 23+ will block what they call "active mixed content". That is: Content hosted at a non-secure (http) location that is requested from a secure webpage (https). "Active" in this context essentially means everything that is not a media type (not an image, audio or video resource). This is to prevent man-in-the-middle attacks that would use non-secure sub-requests to get into secure pages.
For more information see the Mixed Content article on MDN.
As the request is blocked before even hitting the network, there won't be any response headers/data.
Not sure about IE10, but their documentation seems to indicate they block such requests for the same reasons, saying:
Cross-domain, cross-port, and mixed protocol requests are not allowed.
Is there a way I can run a php function through a JS function?
something like this:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php
query("hello"); ?>";
}
</script>
<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
Plain Javascript
In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
test
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
With a javascript library (jQuery et al)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
AJAX on MDN - https://developer.mozilla.org/en/ajax
XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
jQuery - http://jquery.com/download/
jQuery.ajax - http://api.jquery.com/jQuery.ajax/
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
The only way to execute PHP from JS is AJAX.
You can send data to server (for eg, GET /ajax.php?do=someFunction)
then in ajax.php you write:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
I have a way to make a Javascript call to a PHP function written on the page (client-side script). The PHP part 'to be executed' only occurs on the server-side on load or refreshing'. You avoid 'some' server-side resources. So, manipulating the DOM:
<?PHP
echo "You have executed the PHP function 'after loading o refreshing the page<br>";
echo "<i><br>The server programmatically, after accessing the command line resources on the server-side, copied the 'Old Content' from the 'text.txt' file and then changed 'Old Content' to 'New Content'. Finally sent the data to the browser.<br><br>But If you execute the PHP function n times your page always displays 'Old Content' n times, even though the file content is always 'New Content', which is demonstrated (proof 1) by running the 'cat texto.txt' command in your shell. Displaying this text on the client side proves (proof 2) that the browser executed the PHP function 'overflying' the PHP server-side instructions, and this is because the browser engine has restricted, unobtrusively, the execution of scripts on the client-side command line.<br><br>So, the server responds only by loading or refreshing the page, and after an Ajax call function or a PHP call via an HTML form. The rest happens on the client-side, presumably through some form of 'RAM-caching</i>'.<br><br>";
function myPhp(){
echo"The page says: Hello world!<br>";
echo "The page says that the Server '<b>said</b>': <br>1. ";
echo exec('echo $(cat texto.txt);echo "Hello world! (New content)" > texto.txt');echo "<br>";
echo "2. I have changed 'Old content' to '";
echo exec('echo $(cat texto.txt)');echo ".<br><br>";
echo "Proofs 1 and 2 say that if you want to make a new request to the server, you can do: 1. reload the page, 2. refresh the page, 3. make a call through an HTML form and PHP code, or 4. do a call through Ajax.<br><br>";
}
?>
<div id="mainx"></div>
<script>
function callPhp(){
var tagDiv1 = document.createElement("div");
tagDiv1.id = 'contentx';
tagDiv1.innerHTML = "<?php myPhp(); ?>";
document.getElementById("mainx").appendChild(tagDiv1);
}
</script>
<input type="button" value="CallPHP" onclick="callPhp()">
Note: The texto.txt file has the content 'Hello world! (Old content).
The 'fact' is that whenever I click the 'CallPhp' button I get the message 'Hello world!' printed on my page. Therefore, a server-side script is not always required to execute a PHP function via Javascript.
But the execution of the bash commands only happens while the page is loading or refreshing, never because of that kind of Javascript apparent-call raised before. Once the page is loaded, the execution of bash scripts requires a true-call (PHP, Ajax) to a server-side PHP resource.
So, If you don't want the user to know what commands are running on the server:
You 'should' use the execution of the commands indirectly through a PHP script on the server-side (PHP-form, or Ajax on the client-side).
Otherwise:
If the output of commands on the server-side is not delayed:
You 'can' use the execution of the commands directly from the page (less 'cognitive' resources—less PHP and more Bash—and less code, less time, usually easier, and more comfortable if you know the bash language).
Otherwise:
You 'must' use Ajax.
Ok, this is my second post, and PLEASE accept that I am a complete newbie, willing to learn, spending many hours trauling various sites for answers, and I've almost got to where I need to be (at least for this bit).
I have a web page which has a nubmer of javascript functions that work together to generate a Google Map with various lines etc. using the google maps API.
I also have a MySQL Database with some information in.
I have created a PHP script to dynamically generate a dropdown box with information from the database. (and that bit seems to work fine) - http://www.bournvilleconservatives.com/temp/select.php
What I now need to do is get that dropdown box to appear in the HTML / Javascript page that I already have, so that when a user selects something from the list, it calls a javascript function with the value selected.
I'm told I need to use AJAX to pull the box in, and use innerhtml to display it, but I really have no idea how, and could do with an example of something similar to help me on my way.
I would put the PHP in the html page, but that page is actually wrapped up in a Joomla! wrapper, so its all rather complicated.
Thanks in advance.
jQuery solution
If you are willing to use jQuery, it will help you a lot with accessing the DOM, making Ajax calls and stuff. Let me give you a solution in jQuery:
First, put a div into HTML (this will store your select box):
<div id="i_want_my_select_here"></div>
Then put this code in the end of you HTML before </body>.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#i_want_my_select_here').load('/temp/select.php');
});
</script>
In the first script tag, we include the jQuery library from Google's CDN. In the second, we write our Javascript/jQuery code. The .load() function makes it easy to make an Ajax call and load the response into an HTML element.
You can see this is much easier than all that code in my other answer :).
If you're using prototype, you can use either Ajax.Request or Ajax.Updater, tho you should have a parent div with either to replace/insert into.
Example w/ Request:
new Ajax.Request('select.php', {
method: 'post',
onSuccess: function(r) {
var select = r.responseText;
$('parent_div').update(select);
}
});
Example w/ Updater:
new Ajax.Request('parent_div', 'select.php', { method: 'post' });
First, the Ajax example (taken from tizag.com and modified), Javascript code comes:
var ajaxRequest; // The variable that we will put an XMLHTTPRequest object in
//We try to create an XMLHTTPRequest object,
//it is the object that lets us use Ajax
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
// and do stuff with it (this function will only run,
// when the data arrives back from the server!)
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){ //if request is successful
//HERE COMES THE DOM INSERTION
}
}
//We call the PHP file
ajaxRequest.open("GET", "/temp/select.php", true);
ajaxRequest.send(null);
What basically happened is that through XMLHTTPRequest we called your PHP file. When the response (PHP file's output) comes, ajaxRequest.onreadystatechange will run instantly. So whatever we want to do with the data received, we have to do it in the place I've written //HERE COMES THE DOM INSERTION.
We want to insert the output into the HTML. To take the easiest route, first create a div/span in your HTML at the exact place you want your select to appear (it's very important to define the ID).
<div id="i_want_my_select_here"></div>
Then again, here comes the Javascript that replaces //HERE COMES THE DOM INSERTION.
//use the id to get Javascript access to the DIV
var div=document.getElementById('i_want_my_select_here');
//put the output of PHP into the div
div.innerHTML=ajaxRequest.responseText;