Tutorial :ajax response does not write to html page what to do?



Question:

languages used: html, javascript/jquery, and php 5.2

So I created this function that onclick creates a "group". For simplicity, we'll say this is a group (aka the response from ajax.):

<div id="group1">Group #1</div>  

This is where the groups go: (html page)

<div id="groups">      <!-- groups go here -->  </div>  

So the user creates group #1. No problem. The response is returned and Group 1 appears on the screen where it should.

The problem I run into is when the user creates group #2.

success:function(data){                      $('#groups').prepend().html($.trim(data));                  }  

The above script is what assigns the new group to the div. The trouble is, instead of prepend group2 before group1, group2 replaces group1. (not good)

I'm not exactly sure what is happening but when the user creates a 2nd group the script looks for a child element of group to prepend the script finds none so it replaces group1.

If I go to view source I do not see the div for group1 or two but I can visually see the response on my screen.

What is going on here and how do i fix it?

Thanks!


Solution:1

If your response is HTML, you can do it like

$("#groups").prepend(data);  //or  $(data).prependTo($("#groups"));  

What you're doing is prepend()ing nothing, and then setting #groups' html to the data


Solution:2

You should be passing the content as a parameter to prepend, like this:

$('#groups').prepend($.trim(data));  

Calling html afterwards will simply replace the contents of #groups.

Also, this content is generated dynamically, so you won't be able to see it if you view the source of the page. If you want to see such things, consider installing Firebug - it lets you view dynamic content, debug scripts and much more.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »