1

This question has been asked before, but I must realize, I havn't found the real/best way of doing this!

The issue is, that I want to encode the response I get from the AJAX call in order to prevent Cross-site scripting (XSS) attacks. I have a form with a textbox and submit-button. When submitting, the value is posted to the server and returned to the client. Here i need to html encode the response, as the message e.g. could be " alert('Hello') " etc.

How do I encode item.Message in the following?

View

$(document).ready(function () {

    $("form[action$='SubmitChatMessage']").submit(function () {
        $.ajax({
            url: $(this).attr("action"),
            type: "post",
            dataType: "json",
            data: $(this).serialize(),
            success: function (response) {
                $("#chatMessages").empty();

                var chatMessages = "";
                $.each(response, function (i, item) {
                    chatMessages += '<div>' + item.Message + '</div>';
                });

                $("#chatMessages").html(chatMessages);
                $("#message").val(''); // Clear the textbox value
            }
        });
        return false;
    });
});

<div id="chatContent">
    <% using(Html.BeginForm("SubmitChatMessage", "ProductDetails"))
       {%>
    <%: Html.TextBox("message")%>
    <%: Html.Hidden("productId", Model)%>
    <input type="submit" value="Tilføj" />
    <% }%>
    <div id="chatMessages">
    </div>
</div>

Controller Action

[HttpPost]
[ValidateInput(false)]
public JsonResult SubmitChatMessage(string message, Guid productID)
{

    // 1. Store message in db

    // 2. Fetch messages from db
    List<Message> chats = DB.GetMessages(productID);
    var json = (from c in chats 
               select new {Message = c.Message, CreatedDate = c.Created});

    return Json(json);
}

Hope to get an answer, this is driving me insane! A similar question was given here, but I cant see how to use .text in my case.

UPDATE: Is this really the solution?

Community
  • 1
  • 1
Nima
  • 937
  • 1
  • 13
  • 20

2 Answers2

4

Try like this:

success: function (response) {
    var messages = $('#chatMessages');
    messages.empty();

    $.each(response, function (i, item) {
        messages.append(
            $('<div/>', {
                text: item.Message
            })
        );
    });

    $('#message').val(''); // Clear the textbox value
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • can you explain what the text:item.Message means here? – Nima Jul 22 '11 at 21:47
  • @Nima, it uses the [`.text()`](http://api.jquery.com/text/) method to set the contents of the newly created div and which takes care of properly HTML encoding the value (contrary to the `.html()` method). – Darin Dimitrov Jul 22 '11 at 21:53
  • thank you very much. That worked. I can see that the same is mentioned in the "Is this really the solution?" link I have posted in the update section. But thanks, this is not the first time you are helping me with answers :) – Nima Jul 25 '11 at 07:23
1

Alternatively you could use something like HttpUtility.HtmlEncode on the controller's action.

var json = (from c in chats 
           select new {
               Message = HttpUtility.HtmlEncode(c.Message), 
               CreatedDate = c.Created
           });

return Json(json);
Justin Skiles
  • 9,373
  • 6
  • 50
  • 61