Jack
Jack

Reputation: 683

How to include a file OR PHP code with JS?

How can I include code, for example using Javascript? Or if that can't be done, how can I include a whole PHP file?

P.S. Found some script called "require" or "include," but I prefer two lines of code instead of a huge library (using jQuery though). If that can't be done, let me know, I will try to think of something else.

EDIT:

Okay, an example of what I want to do:

function foo() { if(x = 1) return 1; else return 0; }

Then if the function returns 1, I want to either add HTML/PHP code to DIV tags OR I want to include a PHP file containing that code.

EDIT #2:

What about only HTML?

document.getElementById('test').innerHTML = '<a href="google.com">a cool link</a>';

That doesn't seem to work either.

I have an empty div tag with id="test" in my code.

Upvotes: 1

Views: 119

Answers (3)

Overcode
Overcode

Reputation: 4334

Javascript can call any file as long as it is on your server.
It can't call files on the user's local files, for obvious security reasons.

However, javascript cannot, and will never be able to call PHP code, as in it cannot execute php code. This is because since javascript is client side, users can call their own javascript on your page, and execute PHP code, and potentially mess up your site or browse your backend.

You can, however add HTML code to your page using javascript, fairly simply using the innerHTML property of DOM elements or JQuery.
Javascript can also call more javascript code if you wanted, using eval()

If you wanted to call files off your server onto the page using javascript, you'd have to use AJAX

Google it up, and you can code it from scratch, or use JQuery's convenient AJAX handler.

Let's say you had a php file myfile.php that had some html/php, and you wanted to insert it into a div with the id "mydiv", or in css, "#mydiv"

If you just want to quickly load the html/php and push it into the div:

$("#mydiv").load("myfile.php");


If you want to have maximum control of the response from the html/php file:

$.ajax({
    url: "myfile.php", // url to load
    success : function(data) { // on success function
        // data is the response of the ajax request, the response text
        // you can manipulate it here
        manipulateData(data);
        $('#mydiv').html(data); // set the html of the div
    }
});

Upvotes: 0

mplungjan
mplungjan

Reputation: 177721

function foo() { 
  if(x = 1) {$("#divid").load("somephp.php");return 1;} 
  else return 0; 
}

Or

if (foo()) $("#divid").load("somephp.php");

Upvotes: 1

user1350140
user1350140

Reputation:

The only files could Javascript includes is Javascript files, what ever the extension is. and the only way to do it is using

<script src="path/to some/file.ext"></script>

You should note that the file should be javascript text contents, else errors may be generated.

Upvotes: 0

Related Questions