-1

Hi stackoverflow people,

I'm making a variable code where you can easily put another file-code in between e.g. a div. I'm wondering if you can include a PHP-file via JavaScript, with JS variables. I can do it via PHP but can I include a file with JS?

HTML:

<div id="someId">THE INCLUDE HERE</div>

JS:

var tag_id = 'someId'; //comes form DB
var url = 'data/includes/code.php'; // comes from DB

$('#' + tag_id).html('<?php include("' + url + '"); ?>');

As you can see, tag_id is the id of a object and the url is not static but comes from the DB.


I've read and tried those (but didn't work..):

Maybe I have to think out of my box, can you guys help me?

(Sorry for bad English...)

6
  • just so you know, this won't work because php is executed before javascript runs, and php won't run again until the next page load. Commented Jul 27, 2015 at 18:00
  • yes, but can js not include a file or something? Commented Jul 27, 2015 at 18:01
  • 1
    you can use AJAX to get the html output of a page and display that, but you wont be able to include php variables from that file into your current file. Commented Jul 27, 2015 at 18:02
  • You can't do that. You need to look into Ajax. Commented Jul 27, 2015 at 18:03
  • Wait, i've found something else: $('#' + tag_id).load(url) , this works! Commented Jul 27, 2015 at 18:04

1 Answer 1

1

No you cant include a php page through a JS variable, however you could use AJAX to retrieve the HTML contents and place it in a DOM like so:

$.ajax({
    type: "GET",
    url : "data/includes/code.php",
    success: function(result) {
        $('#' + tag_id).html(result);
    }
});

This can be simplified to:

$('#' + tag_id).load(url);
Sign up to request clarification or add additional context in comments.

1 Comment

brilliant this works much better!! Thanks @Daniel McAssey

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.