1

I am trying to display ajax response output ,which is an array , it output is looking good in console.log ,but not getting displayed in resp div .

Here is jquery ajax code

index.php

$(document).ready(function(){
   $("#demo").click(function(){
        $.ajax({
            url:"response.php",
            type:"post",
            data:{ "a":"a"},
                success: function(obj){
                var json = $.parseJSON(obj);
                $.each(json,function(k,v){
                    $(".resp").html("<li>"+v+"</li>");
                    console.log("<li>"+v+"</li>");
                }); 
            },
            error: function(error){
                alert(error);
            }
        })
 });
});

here is response.php

$a=array("1"=>"a","2"=>"b","3"=>"c","4"=>"d","5"=>"e","6"=>"f","7"=>"g","8"=>"h","9"=>"i","10"=>"j");
echo json_encode($a);

here is html

<div><button id="demo">Click me</button></div>
<div class="resp"></div>
7
  • 4
    $(".resp").append("<li>"+v+"</li>"); instead of $(".resp").html("<li>"+v+"</li>"); Commented Apr 1, 2016 at 12:02
  • great it works, but why it is so,why .html no working Commented Apr 1, 2016 at 12:04
  • 2
    because .html will replace all the html first and then add the new one. while .append is adding to next not removing anything. Commented Apr 1, 2016 at 12:06
  • Thanks for helping @Anant Commented Apr 1, 2016 at 12:09
  • one more thing @Anant , i also want to add <ul> tag in that code Commented Apr 1, 2016 at 12:12

1 Answer 1

1

You need to do .append() instead of .html:-

$(".resp").append("<li>"+v+"</li>");

Note:- When you are using .html() then first it removes the complete html attached with the corresponding element and then add the new one.

While .append() is not going to remove anything, its just append the new one to the existing html of that element.

As you asked that you want to append it inside <ul></ul> then you can do it in two ways:-

1.<div class="resp"><ul></ul></div> and then $(".resp ul").append("<li>"+v+"</li>");

2.Directly use this code,No other changes are required:-

success: function(obj){ var json = $.parseJSON(obj); var data = '<ul>'; $.each(json,function(k,v){ data += "<li>"+v+"</li>"; }); data += '</ul>'; $(".resp ul").append(data); },
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.