1

Why does this ajax fail when html tags are added to the json, if the <br /> is not there then is works. The only work around that I can think of is by encoding the text.

Do you know why or /and have any other suggestions.

Thanks

 $.ajax({
            type: "POST",
            url: "/url",
            //data: { "myText" : '[{ "a": "test1", "b": "test2"}]' },//works
            data: { "myText": '[{ "a": "<br />dfgdfgdfgdfgdgd", "b": "test2"}]' },//causes error
            dataType: 'json',
            success: function (data) {
                        alert("pass");
            },
            error: function () {
                        alert("error");

            }
        });
Mat
  • 202,337
  • 40
  • 393
  • 406
Hello-World
  • 9,277
  • 23
  • 88
  • 154

1 Answers1

3

Try using the JSON.stringify method:

data: { "myText": JSON.stringify([{ "a": "<br />dfgdfgdfgdfgdgd", "b": "test2"}]) }

or if you don't want to send myText as JSON string remove the single quotes:

data: { "myText": [{ "a": "<br />dfgdfgdfgdfgdgd", "b": "test2"}] }

Now of course, if on your server side you are using some technology (such as ASP.NET) which forbids characters such as < > in the request you will have to fix your server side script so that it accepts those characters.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    this is the fix. most servers will not allow `<...>` in as a security precaution, they must be escaped. – jbabey Aug 12 '12 at 15:32
  • JSON.stringify does not work but I tried html encoding it and that worked - is that ok if it works? – Hello-World Aug 12 '12 at 15:34
  • When you say *it did not work* you are not very specific. If the problem comes from your server side script it might be better fixing that. – Darin Dimitrov Aug 12 '12 at 15:44
  • Of course that it hits the server. It is the server that returns this 500 error. Because your script probably rejects those characters. What server side technology are you using? If it is ASP.NET you could disable validation. – Darin Dimitrov Aug 12 '12 at 16:13