Reputation: 24132
I'm currently learning PHP through a real website project and want to use Ajax calls to change sections of the website.
CODE SAMPLE
myproject.js
$(document).ready(function() {
$("#inventory").click(function() {
$.ajaxSetup({
url: "sectionhandler.php?section='inventory'",
type: "get",
dataType: "html"
});
$.ajax().done(function(html) {
alert(html); // This works!
$("#section").html(html); // This doesn't work.
$("#section").append(html); // This neither.
});
});
});
inventory.html
<table><tr><td>Hello world with AJAX!</td></tr></table>
sectionhandler.php
<?php echo file_get_contents( 'inventory.html' ); ?>
menu.html
<a id="inventory" href="">Inventory</a>
index.php
<div id="menu" class="content"><?php echo file_get_contents( 'menu.html' ); ?></div>
<div id="section" class="content"></div>
RELATED ARTICLES FOUND AND READ AND TRIED
And there are many many more...
RESULT
When I click on the Inventory link contained within menu.html
and displayed through index.php
, the jQuery code executes just fine. I get the result from the server while displaying the right content from inventory.html
in the alert()
.
However, when I come to either set the innerHTML
to the <div id="section" class="content"></div>
, I can't seem to be able to get the expected result. The background of the page seems to flash, though not supposed to as per Ajax definition, and the content of my XMLHttpRequest.responseText
never get displayed.
The closer I got to make it work was when I was double-clicking on the Inventory
link, so that after the first "flash" from the page background, it showed the content of my section.
I have tried multiple ways using classic Javascript with an onclick
element on my <a>
tag, I have tried with document.getElementById("section")
, though getting the right element, I was not able to show my content on the page.
Any thoughts are welcome!
Thanks in advance ! =)
Upvotes: 1
Views: 1345
Reputation: 3385
As requested. A more simple solution
$("#section").load("sectionhandler.php?section=inventory");
Upvotes: 1
Reputation: 22817
With all chance, you need to prevent browser default behavior:
$("#inventory").click(function(event) {
event.preventDefault();
...
});
Notice the event
parameter added to the click handler.
By the way, you HTML response is invalid - a <table>
should contain a <tbody>
element wrapping any <tr>
s.
Upvotes: 1