Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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
}
share|improve this answer
    
can you explain what the text:item.Message means here? –  Nima Jul 22 '11 at 21:47
    
@Nima, it uses the .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 7:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.