0

I wrote a php and jquery-ajax script that works good. But the following scripts work slow and I found that this type of script is vulnerable to XSS attack, I found something regarding it in this link's first answer please see the first answer. Here is my jquery code:

<script>
$(".question").keyup(function(){
 var question = document.forms["myForm"]["question"].value;
 $.ajax({
  type: "POST",
  url: "http://www.example.com/view_result.php",
  data: { question: question }
 })
.done(function( msg ) {
  $("#show_typing_question").html( msg );
 });
});
</script>

Here is the view_result.php script:

<?php
 function html_converter($val)
  {
    $turned = array('`&lt;b&gt;','`&lt;/b&gt;','`&lt;mark&gt;','`&lt;/mark&gt;');
    $turn_back = array('<b>','</b>','<mark style="background-color:#999;">','</mark>');
    $val = str_replace( $turned, $turn_back, $val );
    $val = preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n\n", $val);
    return $val;
  }
  $question = $_POST['question'];
  $question = htmlspecialchars($question, ENT_QUOTES, 'UTF-8');
  echo html_converter($question);
?>

How can I write the whole script only in jquery function without using ajax. Is this script safe?

Community
  • 1
  • 1
Hasib Mahmud
  • 806
  • 1
  • 10
  • 29
  • jquery .text() escapes all html tags including the tags mentioned in the $turned variable. Only .html() works for html tags of $turned variable. – Hasib Mahmud Nov 30 '13 at 10:50

1 Answers1

0

I think you are asking how to simply avoid XSS attacks client-side. I think you are currently using PHP as a way to "clean" your question data coming from the user. If this is not what you are asking, please clarify your question.

If you want to use text from a user, don't use .html() to set it, simply use .text():

$('.question').keyup(function(){
  var question = document.forms['myForm']['question'].value;
  $('#show_typing_question').text(question);
});

Then, no escaping is necessary since you're using text in a text context.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • Sorry, I am not clear with .html() and .text(). I am trying to only display the question what is typed by the user in a textarea field and I want that the whole input should be escaped except some mentioned in the $turned array(). – Hasib Mahmud Nov 30 '13 at 09:34
  • This ajax system causes some problems when a user types fast. Is it possible to do the whole things only in jquery so that no load is needed? – Hasib Mahmud Nov 30 '13 at 09:36
  • Did you try my answer? It does what you want. – Brad Nov 30 '13 at 09:40