Question

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

  1. XMLHttpRequest won't work in IE 7/8 but works in other browsers
  2. jQuery.ajax()
  3. jQuery.ajaxSetup()
  4. .append()
  5. jquery .html() vs .append()
  6. Can't append HTML code into one div by using jQuery
  7. Add Html to Div with effect jQuery
  8. Use append() to add text/html to an element with jQuery

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 ! =)

Was it helpful?

Solution

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.

OTHER TIPS

As requested. A more simple solution

$("#section").load("sectionhandler.php?section=inventory");

jQuery .load()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top