kalaba2003 kalaba2003 - 1 month ago 5
jQuery Question

IE (all versions) adds "undefined" while loading content with $.post(JSON)

When I click a link, it redirects to a PHP file. The content is loaded and fetched as JSON and is displayed. There is no problem there.

In all versions of IE though, the content is displayed with an

"undefined"
string before the content, which is loaded with
$.post(JSON)
.

NOTE: In the requested PHP file, data is send with
json_encode()
.

jQuery code:

$(".letter").click(function(e){
e.preventDefault();
$.ajaxSetup({cache:false});
var letter= $(this).text();
$.post("http://localhost/ajax.php/", {letter:letter},function(data) {
var listdata;
$.each(data, function(i,item) {
listdata += "<tr>";
listdata += "<td>"+item.book_name+"</td>";
listdata += "<td>"+item.author+"</td>";
listdata += "</tr>";
});
$("#result").empty();
$("#result").html(listdata);
},"json"
);
});


HTML code:

<div id="letters">
<span class="letter">A</span>
<span class="letter">B</span>
<span class="letter">C</span>
<span class="letter">D</span>
</div>
<h3>My Books </h3>
<table id="result"> </table>


In IE browser, display like:

My Books
undefined

| Science and Tech | Author1 |
| Web Development | Author2 |


How can I solve this IE problem?

Answer

You have to initialize listdata to an empty string var listdata = ''; by default it is undefined.