0

I'm trying to do some jquery ajax and I want to know the right way to get the specific content to load. In my case it is loading the entire HTML document within my given area when what I want is the content within my div with id of "main" to load.

Here is the code:

(function($){
// target the links
$link = $('nav a');
// on click 
$link.on('click', function(event){

    // create variables
    $el = $(this);

    var value = $el.attr("href");
    event.preventDefault();

    $.ajax({
        url: value,
        method: 'POST',
        data: { href: value }       
    })
    .done(function( html ) {
    $( "#main" ).append( html );
  });
});

})(jQuery);

And here is the HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>AJAX jQuery</title>
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Mobile Specific Meta -->
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>


    <!-- Stylesheets -->


  </head>
  <body>

      <nav>
          <a href="/ajax-test">Main</a>
            <a href="external.html">Some link</a>
      </nav>

      <div id="main">
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
      </div>
  <script   src="https://code.jquery.com/jquery-3.1.0.min.js"   integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="   crossorigin="anonymous"></script>
     <script src="ajax.js" charset="utf-8">

     </script>
  </body>
</html>

I want the content in the external.html to load but instead it loads the whole document including etc..

Example of page loading incorrectly

Thanks for your help!

Ryan Mc
  • 833
  • 1
  • 8
  • 25

2 Answers2

3

You can use the load method to do that :

(function($){
    // on 'Nav' click 'a' delegation
    $('nav').on('click', 'a', onNavLinkClick)

    // nav links click callback
    function onNavLinkClick(e){
        $("#main").load( $(this).attr("href") ); // will put the ajax response inside #main
        return false;
    });
})(jQuery);

Same as above using $.ajax method:

 (function($){
    // on 'Nav' click 'a' delegation
    $('nav').on('click', 'a', onNavLinkClick)

    // nav links click callback
    function onNavLinkClick(e){
        getPage( $(this).attr("href") ).done(function(HTML){
            $("#main").html( HTML ); // replace the content of "#main" with the server response
        })
      return false;
    });

    // returns an AJAX promise
    function getPage( URL ){
        return $.ajax({
            url      : URL,
            method   : 'GET',
            dataType : 'html'
        })
    }
 })(jQuery);
vsync
  • 118,978
  • 58
  • 307
  • 400
  • Thanks. I know about the load method but I wanted to use the more comprehensive $.ajax({}) object. – Ryan Mc Jul 22 '16 at 08:43
  • 1
    @RyanMc - why? why not use something the fits like a glove for your needs? – vsync Jul 22 '16 at 08:44
  • I dont have a real need except better understanding ajax. I already know how to do it using load method. – Ryan Mc Jul 22 '16 at 08:48
  • Yes but like I said I already know how to do that. I could have made it work that way without your help. No offence but I'm looking for the ajax object approach. Thanks – Ryan Mc Jul 22 '16 at 09:54
  • @RyanMc - Then what is the problem? that you don't know how to do it using `$.ajax` ? – vsync Jul 22 '16 at 12:54
  • Answer updated with plain `$.ajax` (I disagree on this approach) – vsync Jul 22 '16 at 13:04
0

You should check in backend if this is ajax request, and if this is ajax request render only needed parts(no <head> etc.).

Or You can modify Your .done() callback:

.done(function( html ) {
    $( "#main" ).append( $(html).find('#main').html() );
});

I would modify backend side, not to put html overhead to response

Bogdan Kuštan
  • 5,427
  • 1
  • 21
  • 30