Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an element with selector after using jquery ajax? $.ajax()

Tags:

jquery

I want to get a div element with an ID after calling $.ajax() Here is my code:

$.ajax({

  url: "PO_Header.php",
  data: "supplier="+selectedId,
  cache: false,
  success: function(html){
    $("#PO_Header").empty(); 

    $("#PO_Header").append(html);

  }
});

$("#PO_Header").append(html); will append the entire html page, what I want to have is get an element with a specific id. Let's say inPO_Header.phpa div element with an id='mydiv' would be injected in my current page.

like image 229
Randel Ramirez Avatar asked Jan 21 '26 14:01

Randel Ramirez


2 Answers

Use jQuery's load:

$('#PO_Header').load('PO_Header.php #mydiv', { 'supplier': selectedId } );

It allows you to load page fragments. As their documentation points out:

Loading Page Fragments 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.

It will therefore only inject <div id="myDiv"></div> from PO_Header.php into your element.

like image 132
hohner Avatar answered Jan 23 '26 02:01

hohner


You can use .load() for this.

Loading Page Fragments

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.

Source: http://api.jquery.com/load/

Basically you can use it like this:

$('#PO_Header').load('PO_Header.php #mydiv', { 'supplier': selectedId } );

To disable cache you can use at the start of your code:

$.ajaxSetup({
  cache: false
});

EDIT:

.load() is roughly the same as .get() except for a couple of reasons:

  1. .load() has an implicit callback function which set the returned HTML content into the supplied element when a successful response occurs.

  2. It has a special syntax for the url parameter for specifying just a determined portion of the returned document to be inserted.

  3. Default method is GET. Unless the data parameter is passed as an object then a POST method is used.

like image 33
Alexander Avatar answered Jan 23 '26 04:01

Alexander