Can you refresh or rather reload a php include file via AJAX? I want a form when submitted (via AJAX) to also reload (via AJAX) the data contained in a php file thats included on the same page. Is this possible?
| SitePoint Sponsor |
Can you refresh or rather reload a php include file via AJAX? I want a form when submitted (via AJAX) to also reload (via AJAX) the data contained in a php file thats included on the same page. Is this possible?
Yes! You can do anything you like as long as The client has javascript enabled. You can even write php functions and access the output from javascript. Heres an example of calling php functions from javascript:
PHP Code:<?php
// html section
if(!isset($_GET['function'])){
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
/*<![CDATA[*/
function loadXMLDoc(url)
{
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send();
}
}
}
function processReqChange()
{
if (req.readyState == 4) {
if (req.status == 200) {
response = req.responseXML.documentElement;
method = response.getElementsByTagName('method')[0].firstChild.data;
result = response.getElementsByTagName('result')[0].firstChild.data;
eval(method + '(\'\', result)');
}
}
}
function str_replace(input, response)
{
if (response != ''){
// Response mode
document.getElementById("str_replace").innerHTML = '<textarea style="width: 150px; height: 70px;" rows="5" cols="16" name="str_replace_result" id="str_replace_result">' + response + '</textarea>';
}else{
// Input mode
url = 'http://<?php print $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
?>?function=str_replace&arg[]=' + input.find.value + '&arg[]=' + input.replace.value + '&arg[]=' + input.str_replace_result.value;
loadXMLDoc(url);
}
}
function mail(input, response)
{
if (response != ''){
// Response mode
if(response == 'TRUE'){
document.getElementById("mail").innerHTML = '<span style="color: green;">Mail sent OK!</span>';
}else{
document.getElementById("mail").innerHTML = '<span style="color: red;">Mail sending failed!</span>';
}
}else{
// Input mode
document.getElementById("mail").innerHTML = 'Standby...';
url = 'http://<?php print $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
?>?function=mail&arg[]=' + input.to.value + '&arg[]=' + input.subject.value + '&arg[]=' + input.message.value;
loadXMLDoc(url);
}
}
/*]]>*/
</script>
</head>
<body>
<h1 style="font-size: 12pt; font-weight: bold;">Example: using php function str_replace</h1>
<form style="font-size: 10pt; margin-top: 25px; text-align: right; width: 125px; font-family: verdana, sans serif;" action="" method="post" onsubmit="str_replace(this,''); return false;">
Find: <input style="width: 150px; position: absolute; left: 150px;" type="text" name="find" id="find" value=""><br><br>
Replacement: <input style="width: 150px; position: absolute; left: 150px;" type="text" name="replace" id="replace" value=""><br /><br />
Subject string: <span id="str_replace" style="position: absolute; left: 150px;"><textarea style="width: 150px; height: 70px;" rows="5" cols="16" name="str_replace_result" id="str_replace_result"></textarea></span><br><br><br><br><br>
<input style="position: absolute; left: 150px;" type="submit" value="str_replace() it"><br><br>
</form>
<h1 style="font-size: 12pt; font-weight: bold;">Example: using php function mail</h1>
<form style="font-size: 10pt; margin-top: 25px; text-align: right; width: 125px; font-family: verdana, sans serif;" action="" method="post" onsubmit="mail(this,''); return false;">
To: <input style="width: 150px; position: absolute; left: 150px;" type="text" name="to" id="to" value=""><br><br>
Subject: <input style="width: 150px; position: absolute; left: 150px;" type="text" name="subject" id="subject" value=""><br /><br />
Message: <textarea style="width: 150px; height: 70px; position: absolute; left: 150px;" rows="5" cols="16" name="message" id="message"></textarea><br><br><br><br><br>
<span id="mail" style="position: absolute; left: 150px;"><input type="submit" value="mail() it"></span><br><br>
</form>
</body>
</html>
<?php
}
// XML section
//The following array contains the php functions javascript is permitted to access
$allowed_functions = array('str_replace', 'mail');
if(in_array($_GET['function'], $allowed_functions)) xmlRequest();
function xmlRequest()
{
ini_set('display_errors', '0');
$eval = '$output = @'.$_GET['function'].'(';
if(!empty($_GET['arg'])){
$i = 0;
$j = count($_GET['arg']) -1;
foreach($_GET['arg'] as $arg){
// need to think about some sort of validation here
if(!ini_get('magic_quotes_gpc')) $arg = addslashes($arg);
$eval .= "'".$arg."'";
if($i < $j) $eval .= ',';
$i++;
}
}
$eval .= ');';
eval($eval);
if(is_bool($output)) $output = ($output) ? 'TRUE' : 'FALSE' ;
header('Content-Type: text/xml');
print '<response>'."\n".' <method>'.$_GET['function'].'</method>'."\n".
' <result>'.$output.'</result>'."\n".'</response>';
exit;
}
?>
Location: Alicante (Spain)... Hot and Sunny...
Texas Holdem Poker Probability Calculator | DNS test
Avatars | English Spanish Translation | CAPTCHA with audio
Email | PHP scripts | Cruft free domain names | MD5 Cracker
Thanks. I will give it a shot.
Ok. I have the refresh include working great.. but how do I post form data ....
this is what I have... the first function (makePOSTRequestadd) is to post data to a script from a form and the other function (makePOSTRequest) refreshes the include (I want it to refresh after the form data is posted in the first function)
The second function action works but not the first...
How can I change the first section of this code to actually grab and npost the form data to the url in the first function...Code:function makePOSTRequestadd(url, parameters) { http_request = false; if (window.XMLHttpRequest) { // Mozilla, Safari,... http_request = new XMLHttpRequest(); if (http_request.overrideMimeType) { http_request.overrideMimeType('text/xml'); } } else if (window.ActiveXObject) { // IE try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if (!http_request) { alert('Cannot create XMLHTTP instance'); return false; } http_request.onreadystatechange = alertbContents; http_request.open('POST', url, true); http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http_request.setRequestHeader("Content-length", parameters.length); http_request.setRequestHeader("Connection", "close"); http_request.send(parameters); } function alertbContents() { if (http_request.readyState == 4) { if (http_request.status == 200) { //alert(http_request.responseText); result = http_request.responseText; } else { alert('There was a problem with the request.'); } } } function get(obj) { var poststr = "subject=" + encodeURI( document.getElementById("subject").value ) + "&tid=" + encodeURI( document.getElementById("tid").value ) + "&message=" + encodeURI( document.getElementById("message").value ); makePOSTRequestadd("http://www.myurl/actionscript/" + encodeURI( document.getElementById("tid").value ), poststr); } function makePOSTRequest(url, parameters) { http_request = false; if (window.XMLHttpRequest) { // Mozilla, Safari,... http_request = new XMLHttpRequest(); if (http_request.overrideMimeType) { http_request.overrideMimeType('text/xml'); } } else if (window.ActiveXObject) { // IE try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if (!http_request) { alert('Cannot create XMLHTTP instance'); return false; } http_request.onreadystatechange = alertContents; http_request.open('POST', url, true); http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http_request.setRequestHeader("Content-length", parameters.length); http_request.setRequestHeader("Connection", "close"); http_request.send(parameters); } function alertContents() { if (http_request.readyState == 4) { if (http_request.status == 200) { //alert(http_request.responseText); result = http_request.responseText; document.getElementById('myspan').innerHTML = result; } else { alert('There was a problem with the request.'); } } } function get(obj) { var poststr = "subject=" + encodeURI( document.getElementById("subject").value ) + "&tid=" + encodeURI( document.getElementById("tid").value ) + "&message=" + encodeURI( document.getElementById("message").value ); makePOSTRequest("http://www.myincludefile/" + encodeURI( document.getElementById("tid").value ) + ".php", poststr); }
Bookmarks