I’m building a simple shoutbox.
Here’s the html :
<div id="shoutbox">
<form method="post" id="form" class="shoutbox-form">
<table>
<tr>
<td><label>User</label></td>
<td><input class="text user" id="nick" type="text" MAXLENGTH="25" /></td>
</tr>
<tr>
<td><label>Message</label></td>
<td><input class="text" id="shout" type="text" MAXLENGTH="255" /></td>
</tr>
<tr>
<td></td>
<td><input id="send-shout" type="submit" value="Dodaj!" /></td>
</tr>
</table>
</form>
<div id="shoutbox-container">
<span class="clear"></span>
<div class=".shoutbox">
<div id="shoutbox-loading"><img src="css/images/loading.gif" alt="Loading..." /></div>
<ul>
</ul>
</div>
</div>
</div
>
Here’s the js code :
$(document).ready(function(){
var inputUser = $("#nick");
var inputMessage = $("#shout");
var loading = $("#shoutbox-loading");
var messageList = $(".shoutbox > ul");
function updateShoutbox(){
messageList.hide();
loading.fadeIn();
$.ajax({
type: "POST",
url: "/shouts/",
data: "action=refresh",
success: function(data){
var data = JSON.parse(data);
loading.fadeOut();
messageList.html(data["response"]);
messageList.fadeIn(2000);
}
});
}
});
But apparently the messageList.html(data[“response”]) doesn’t work although firebug shows that my response is :
{"response": "<li><strong>user1</strong><img src=\"\" alt=\"\" >test<span class=\"date\">2010-10-07 19:36:13</span></li><li><strong>user2</strong><img src=\"\" alt=\"\" >test2<span class=\"date\">2010-10-07 20:23:56</span></li>"}
If instead of success in ajax I have complete I get var data = JSON.parse(data); error. Any ideas what can be changed to fix this issue ?
UPDATE :
Adding:
var c = data["response"];
console.log(c);
Gives me :
<li><strong>user1</strong><img src="" alt="" >test<span class="date">2010-10-07 19:36:13</span></li><li><strong>user2</strong><img src="" alt="" >test2<span class="date">2010-10-07 20:23:56</span></li>
in firebug console.
Nobody else noticed the error in your html.
Should be:
Fix that and see if your jQuery stuff works.
EDIT As mentioned in other answers you should also set your response type to JSON. Which would avoid you having to use
JSON.parse()on the data. But this isn’t necessary given your use ofJSON.parse()on the response data.