Reputation: 75
I haven't found a clear answer for this at all. I've been looking for an hour or two.
I have a PHP page doing SQL call and building out my page. I have a list of items with onClick JavaScript functions that trigger the page's additional events. Among other things, I need that onClick function to append the HTML page with additional PHP code. I've been hopping to append in a PHP file via an include but that seems unavailable to me using this JS function.
And ideas would be most helpful. If you can support your answer with code references or existing tutorials that make since that would be fantastic.
Upvotes: 2
Views: 12514
Reputation: 7536
Use AJAX, with jQuery you could do this:
$.get('test.php', function(data) {
$("#MyDiv").html(data);
});
This would insert "test.php" generated content inside <div id="MyDiv">
.
Ok. You don't want jQuery... The same above using plain javascript:
function getHTTPObject() {
var xmlhttp;
/*@cc_on
@if (@_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function $(id) { return document.getElementById(id); }
function AJAX_GetAsinc(ajax, id, url) {
ajax.abort();
function statechange() {
if ((ajax.readyState==4) && (ajax.status==200)) $(id).innerHTML=ajax.responseText;
}
ajax.open('GET', url, true);
ajax.onreadystatechange = statechange;
ajax.send(null);
}
var ajax = getHTTPObject();
AJAX_GetAsinc(ajax, 'MyDiv', 'test.php'); // This loads the content
Ohhh yes... this is less confusing :S
Upvotes: 1
Reputation: 182
Using ajax is the solution. :) What ajax (Asynchronous JavaScript and XML) does is run an external php page and returns its results dynamically without reloading the page. :)
Of course another solution would be to have your html file in .php and just echo the php you want added.
Upvotes: 1
Reputation: 252
You can use JQuery+Ajax to load an external file and then just append the element, for example:
// when the page loads
$(document).ready(function () {
$.ajax({
url: "test.html",
cache: false
}).done(function( html ) {
$("#results").append(html);
});
});
or
// when the an element is clicked
$(document).ready(function () {
$.fn.appendElement = function (){
$.ajax({
url: "test.html",
cache: false
}).done(function( html ) {
$("#results").append(html);
});
}
});
$('#buttonId').click(function(){ $(this).appendElement(); });
HTH
Upvotes: 3
Reputation: 21899
JavaScript is code that executes in the client's browser, PHP is code that executes on the server. Attempting to output PHP from JavaScript will never work.
If you wish to trigger PHP code via JavaScript, you could make an XML Http Request to a PHP file on your server.
Upvotes: 4