Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading page framents with Jquery AJAX

Tags:

jquery

ajax

I would like to use $.ajax() to request a page, but load only fragments of that page. I know you can specify what page fragments you want with .load() but I was wondering if this is possible with $.ajax?

like image 260
user288423 Avatar asked Mar 08 '10 00:03

user288423


People also ask

How can I load a page in ajax?

load(URL,data,callback); The required URL parameter specifies the URL you wish to load. The optional data parameter specifies a set of querystring key/value pairs to send along with the request. The optional callback parameter is the name of a function to be executed after the load() method is completed.

How ajax get data from another page in PHP?

ajax({ type: 'POST', url: '../portal/curriculum. php', data: 'studentNumber='+$('#StudentID'). val(), success: function(data) { $('#curriculum'). html(data); } }); });


2 Answers

For those of you who are wondering, stoplion is referring to this feature: Loading Page Fragments (scroll down on the page):

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

Since $.get() doesn't appear to support it, I assume that $.ajax wouldn't either. A simple way to implement this would be the following:

$.ajax({
   url: 'http://example.com/page.html',
   data: {},
   success: function (data) {
      $("#el").html($(data).find("#selector"));
   },
   dataType: 'html'
});

This would be the equivalent of

$("#el").load('http://example.com/page.html #selector');

However, note that the special syntax (' #selector') means that scripts present in the loaded HTML will not be executed. See Script Execution in the .load() docs.

like image 169
Jordan Reiter Avatar answered Oct 28 '22 21:10

Jordan Reiter


You could get your fragment via post, append the html to a div with display: none; Then use the selector to get the fragment that you want and append it to the region that you wish to display.

Air Code:

<div id="tempRegion" style="display:none;">

</div>

$.ajax({
    url: "page.htm",
    type: "GET",
    success: function(results){

        $('#tempRegion').html(results);

        ...

        //  Now select fragment, append to display area
        var fragement = $('#someFragment').html();

        $('#displayRegion').html(fragement);

    })

});
like image 3
David Robbins Avatar answered Oct 28 '22 19:10

David Robbins