Matt Elhotiby
Matt Elhotiby

Reputation: 44066

How do I replace a big chuck of code with another chunk of code via JQuery

I have a php page that I am calling via ajax and the returned value i want to place in the page as a new element. For example I have

<div id="main">

<div class="element">
 Old stuff
 ....
</div>
<div class="element">
 ....
</div>
<div class="element">
 ....
</div>

</div>

This is my page

I have a php page I am calling view Jquery ajax that returns this structure

<div id="main">

<div class="element">
 New stuff
 ....
</div>
<div class="element">
 ....
</div>
<div class="element">
 ....
</div>

</div>

So i need to hide the old stuff and replace it with the new block

Upvotes: 0

Views: 99

Answers (4)

Jake
Jake

Reputation: 1332

I think what you want is

$.ajax({
   url: 'ajax/myajax.php',
   success: function(data) {
   $('#main').html(data);
   }
});

Upvotes: 1

Jacob Mattison
Jacob Mattison

Reputation: 51062

JQuery ajax actually has a shortcut for that, if you want to replace the contents of your "main" div:

$("#main").load("myAjaxPHPURL.php");

Upvotes: 1

morgancodes
morgancodes

Reputation: 25265

Or...

$('#main').replaceWith($jq(newHtml));

That way you don't have to strip out the outer div from the new content.

Upvotes: 0

pharalia
pharalia

Reputation: 709

$('#main').html("New markup to replace");

Will replace the content of the div within id=main.

$('#main').append("New markup added to end of target");

Will add the content to the end leaving the original content intact.

$('#main').prepend("New markup added to beginning of target");

Will add the content to the top leaving the original content intact.

Upvotes: 0

Related Questions