Skip to content Skip to sidebar Skip to footer

Inject Html Using Ajax

I have a HAML page with some div elements. I need to inject this into a div on another page when a button is clicked. how do i do this? thanks

Solution 1:

You have to add the jQuery plugin from jQuery.com. you can download the plugin or use the link http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js as src in the js file.

then use the follwing code

$(document).ready(function(){
  $("#your_button_Id").click(function(){
    $.ajax({
      url: "test.html",
      context: document.body,
      success: function(response){
        $('#div_Id').html(response);
      }
    });
  });
});

Hope this helps!!! happy coding.

Solution 2:

try $('div').load('lol.HTML') if you want to use jquery

Solution 3:

To simplify this process, add the jQuery library to your page.

Below is an example of using jQuery to load data from a different page into the current page:

inject_to = $("div#id"); // the div to load the html into
load_from = "/some/other/page"; // the url to the page to load html fromdata = ""; // optional data to send to the other page when loading it// do an asynchronous GET request
$.get(load_from, data, function(data)
{
    // put the received html into the div
    inject_to.html(data);
}

Note that this opens for security/xss issues, and I would recommend using .text instead of .html, and load only plain text from the external page. More info on jQuery ajax: http://api.jquery.com/category/ajax/

To do this when a button is clicked, put the above code into a function, like this:

functionbuttonClicked()
{
    inject_to = $("div#id"); // the div to load the html into
    load_from = "/some/other/page"; // the url to the page to load html from
    data = ""; // optional data to send to the other page when loading it// do an asynchronous GET request
    $.get(load_from, data, function(data)
    {
        // put the received html into the div
        inject_to.html(data);
    }
}

Then add an event handler for the click event to the button, like this:

$("button#id").click(buttonClicked);

More info on jQuery events: http://api.jquery.com/category/events/

Post a Comment for "Inject Html Using Ajax"