Include php file with JS

Hi,

I need to include a php file on my page when clicking a text, but I can't find the right JS code that does that.

Here is an example where the text changes color to red when clicked, and what I what is to include a php file on the page in stead (like the <?php include(filename.php);?>).

<p id="ft_kbh" onclick="show_ft()">Ønsker du et overblik over folketællinger i København, så klik på denne tekst.</p>
      

<script>
function show_ft() {
    document.getElementById("ft_kbh").style.color = "red";
}
</script>

Open in new window



I hope someone can guide me a little on this :)
Peter KromanSales ExecutiveAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
That's confusing.  PHP executes on the server and not in the browser.  Using <?php include(filename.php);?> will execute on the server and not in the browser though it may send data to the browser.
0
Peter KromanSales ExecutiveAuthor Commented:
I know, but I thought I could use some AJAX or something like that for the purpose.

Anyway - it does not have to be JS code - it is the functionality, clicking on a <p> element should include a php file, I am after :)
0
Peter KromanSales ExecutiveAuthor Commented:
When I do something like this, it does not load anything.
The file ftH_table.php is located in the same folder as the the file including the code below.

<button type="button" style="text-align: left; color: #666666;" onclick="show_ft()">Ønsker du et overblik over folketællinger i København, så klik her.</button>
</div>

<script type="text/javascript">
function show_ft() {
    var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    document.getElementById("ft_kbh").innerHTML = this.responseText;
}
};
  xhttp.open("GET", "./ftH_table.php", true);
  xhttp.send();
}
</script>

Open in new window

0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Olaf DoschkeSoftware DeveloperCommented:
Taken from http://blog.teamtreehouse.com/14-handy-jquery-code-snippets-for-developers

$("#content").load("somefile.html", function(response, status, xhr) {
  // error handling
  if(status == "error") {
    $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
  }
});

Open in new window


This obviously needs jQuery as a basis, otherwise, you can load HTML or also make a request to a PHP script returning whatever HTML it returns. Ideally the PHP script only has the HTML tagging you need at that place, you're setting the inner HTML of an element with id="content", but if you know jQuery, you know the first part $(..) may also address any tag by other means, like class name, etc.

Bye, Olaf.
0
deepak singhPhp Web Developer Cum DesignerCommented:
you have to use ajax with your code. you can not include server side page in client side page. if you want to do so you have to use ajax.
0
Peter KromanSales ExecutiveAuthor Commented:
Thanks,

But what is wrong with my AJAX code, since it does not load anything?
0
Julian HansenCommented:
Why are you writing your own AJAX routine - there is no benefit to doing that at all - rather use an existing library that does it for you.

As Olaf recommended the jQuery .load() does exactly what you want it to. Not only does it fetch the page and place the contents of that page in the specified element you can also specify a hash id after the URL of the page and jQuery will find the element in the fetched page that has that ID - extract just that element and its children and place that in the target element

$('#target-element').load('somepage.php #source-id

Refer to jQuery loading source fragments
0
Julian HansenCommented:
to answer your question about what is wrong with your code - nothing - the code works (according to my tests).

Things to test
1. That the URL you are targeting exists
2. Check the console for errors - you should see the request in the console you can look at the response to see what is being returned
3. The id you are using to target the result element is not correct or not defined.

Working sample here
0
Peter KromanSales ExecutiveAuthor Commented:
The console is totally "silent" when clicking the button :)
I'll work a bit with it, and get back later.

Thanks.
0
Julian HansenCommented:
Then you function is not firing or your console is not configured to show the activity - you checked the Network tab as well?
0
Olaf DoschkeSoftware DeveloperCommented:
I would always choose jQuery as the minimum framework for any site, also because it solves most if not any cross-browser issues. Also, it'll show you any HTTP errors, if you keep it at the default.

You could extend your code to show you, whether xhttp.status became anything else but 200, too. The way you did, you simply suppress anything, if the HTTP request fails. That way you don't find out errors.

Bye, Olaf.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Slick812Commented:
greetings  Peter Kroman, , I looked at your javascript, and to me, your problem is this line -
                       xhttp.open("GET", "./ftH_table.php", true);

Because as you say  "file ftH_table.php is located in the same folder as the the file"

I feel this change may help -
                       xhttp.open("GET", "ftH_table.php", true);

- - - - - - - - - - - - - - - - - -
Just my thoughts, , , Most coders that start using AJAX will copy and paste code work to see if it works. And for the moat part it does, since it's just the same code that worked for others. BUT there is much more to the Browser - Server communication that is the AJAX process, that is very difficult at first to see what is happening, and a challenge to try and understand what to do to FIND and FIX a problem.

The javascript you use is NOT set up to have any output if there is a problem, for any problem on browser or server, it just does nothing, shows nothing and has no indicators for errors, even in the javacript console, (although, info may be in the http-network activity tab).
You may try and understand more about the AJAX  XMLHttpRequest()  processes, when you try and use them for a page, AJAX is now a very useful tool for web site builders to use.
0
Peter KromanSales ExecutiveAuthor Commented:
Thanks Slick 812,

Very helpful input I'll just keep on working :)
0
Slick812Commented:
maybe this will help you? ?
, I changed the var form xhttp to ajax, and changed the 'this'  to 'ajax' in the .onreadystatechange to show you what is being used there

function show_ft() {
  var ajax = new XMLHttpRequest();

  ajax.onreadystatechange = function() {
	  
// IMPORTANT this function is ASYNCRONUS, NOT used until LATER, after the function show_ft() is finished

    if (ajax.readyState == 4) { // I Changed the 'this' to 'ajax' to help you see what reference is being used here
      if (ajax.status == 200) { // the status is the HTTP result type Number, 200 for success
		  
        document.getElementById("ft_kbh").innerHTML = "Change- "+ajax.responseText;
// I added the text "Change- ", so is the responseText is empty from PHP, then you will still have a visual that the responseText was returned
        } else {
        document.getElementById("ft_kbh").innerHTML = ajax.status;// sever indicator for HTTP result
        }
    }
  };
  
ajax.open("GET", "ftH_table.php", true);
ajax.send();
}

Open in new window

0
Olaf DoschkeSoftware DeveloperCommented:
Yes, I pointed out already, that there should be code displaying errors, that would for example easily reveal a 404 not found or other very fundamental problems.

The jQuery code I posted includes that. If you reject to add the jQuery library to keep your pages slim, I can't blame you, but it's very common to be included. If you don't have it yet, it's just a single script tag in the HTML head.

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

Open in new window

<100 KB.

Bye, Olaf.
0
Julian HansenCommented:
We have already established his code is good - the only thing outstanding is to find out why his specific implementation is not working which points to configuration more than code.

If Slick's suggestion of the path does not pan out then ideally we would need to see a sample page to see what is going on.
0
Olaf DoschkeSoftware DeveloperCommented:
Yes, and if removing ./ from the path really works, then the expected error would have been 404 and the jQuery solution would have displayed that Friday already.
And dito for a script error resulting in status 500, dito for a permission problem...

Bye, Olaf.
0
Peter KromanSales ExecutiveAuthor Commented:
Thanks to all. I'll be back later :)
0
Peter KromanSales ExecutiveAuthor Commented:
Thanks to all participitants. I'm not sure that I have given points to all - haven't got used to the new way of closing questions yet.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.