Is there a way to include some php file at javascript onClick
?
like,
if(isset(something)) ?
include "file.php";
Please help!
Is there a way to include some php file at javascript onClick
?
like,
if(isset(something)) ?
include "file.php";
Please help!
No. That's PHP syntax. PHP executes completely on the server and the result is sent back to the client. Clicks are on the client side. Javascript handles those. Your can't mix the two.
You can use AJAX to make a request to the server for a file and display its contents using JS, though. jQuery has a simple method called .ajax()
for this
$.ajax({
url: 'file.php',
success: function(data) {
$('#result').html(data);
alert('Load was performed.');
}
});
This method will load the contents of file.php
and show that in an element with the id result
.
Another option is to submit a form. You put the name of the file in a hidden form field and onclick, submit the form. PHP gets that information and you read the name of the file from $_GET[]
or $_POST[]
, make sure it's valid (wouldn't want somebody to be able to modify your HTML and include any file on your server) and then include it and render the page again.
You can simply use jQuery's load
function:
$("#elem").click(function()
{
$("#placeToLoad").load("http://path/to/file");
}
@sachleen his way is the same as this, only load
just grabs the file and puts it in the given location, instead of having to cope with success functions etc. If load
doesn't succeed, it won't do anything.
jQuery .load()
You can't include php file because it's server side code which can't be executed in client side.
But what you could actualy do is use ajax to call the file.php and execute its content and than append the result to your document.
When you make a request to a file using the jQuery load() method, it sends data just like any regular request through your browser. It has no knowledge of any of your existing PHP variables unless you pass them along with your ajax request as data.
function sendAJAX(){
$('#container').load(
"stuff.php", // url
{ // json object of data to pass to the page
stuff: "all your stuff goes in here...",
moreStuff: "even more stuff"
});
console.log('sendAJAX');
};