0

Is there a way to include some php file at javascript onClick?

like,

if(isset(something)) ?
include "file.php";

Please help!

1
  • 3
    You can't. PHP is server side whereas JavaScript is client side. Commented Aug 2, 2012 at 13:57

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If you are so eager to use jQuery, just use $("#result").load("file.php", function(){alert("Load was performed");}).
1

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()

Comments

0

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.

Comments

0

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'); 

};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.