Skip to content Skip to sidebar Skip to footer

Sanitize Ajax Response That Updates Options In Select Box

I have Bloggers and Blogs. Each blog is associated to a blogger. Here is a picture of the Blog records: Notice that the title attribute of Jennell's first blog has some javascri

Solution 1:

Set the text/values via attributes, not the html string.

var str = "<script>alert('x');<\/script>Test",
    opt = $("<option></option>", { "text" : str, value : "foo" });
$("select").append(opt);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select></select>

Solution 2:

In case anyone wants to see a code solution to the question:

$("body").on('change', '[data-action="blogger_sel"]', function() {
  var blog_sel = $(this).closest('[data-parent-for="blog_sel"]').find('[data-action="blog_sel"]');
  $.ajax({
    url: "/blogs",
    type: "GET",
    data: {blogger_id: $(this).val()},
    success: function (data) {
      blog_sel.children().remove();
      $.each(data, function (index, item) {
        blog_sel.append($('<option>', {
          value: item.id,
          text : item.title
        }));
      });
    }
  })
});

Post a Comment for "Sanitize Ajax Response That Updates Options In Select Box"