1

I have a navigation bar saved as menu.php.Then in my main page I created a button called" Inject".This is supposed to append a php include tag when clicked. Here is my code:

$(document).ready(function(){
        $("#inject").click(function(){
                $("body").append("<?php include  '../menu.php'; ?>");
            });
        });


<body>


<div class="container">
    <div class="jumbotron landing">
        <h1 class="text-center"><span class="text-primary">Hex to Rgb converter V1.0 </span></h1>
    </div>  
    <div id="inject" class="btn btn-danger">Inject</div>
    <h1>Enter hex code without <kbd>#</kbd> and press <kbd>Enter</kbd></h1>
    <kbd class="h3">#</kbd><span class="h4 bg-primary">+</span><input type="text" maxlength="6" id="hex" class="text-warning bg-info h3 img-rounded" pattern="[A-Fa-f]{6}" title="Type a hex code please">
    <h1>Rgb</h1>
    <p id="rgb" class="h4 text-primary bg-success"></p>
</div>
</body>

The problem That i get on js console(chromium) is"Uncaught SyntaxError: Unexpected identifier" The php include tag will work fine when it is not inserted by javascript. Any ideas?

  • Make sure you use tages not in external .js file. It should in same php file. – Isuru Madusanka Dec 20 '14 at 16:05
  • @No nick please: The php include is working fine in both instances. The problem in the JS case is that what the PHP includes in not valid JavaScript. What is your reason for having your JS append this html rather than putting it in your document to begin with? – 76484 Dec 20 '14 at 18:09

1 Answers1

2

I would probably use ajax for that, but to include arbitrary string in you js code you would have to encode it properly.

$("body").append(<?php echo json_encode(file_get_contents('../menu.php')); ?>);
Musa
  • 96,336
  • 17
  • 118
  • 137
  • Your code works when menu.php contains only html.If i change menu.php to php tags it will not work – No nick please Dec 20 '14 at 16:14
  • 2
    I didn't even think of that but take a look at this http://php.net/manual/en/function.include.php#example-159 and http://stackoverflow.com/questions/1314162/return-from-include-file – Musa Dec 20 '14 at 16:16