1

How can I protect against injection? (jQuery & ajax)

<input type="text" id="name" name="name" /> 
<input type="text" id="email" name="email" /> 

var name = $("#name").val();
var mail = $("#email").val();

Output:

$("#logga").html('Name: <b>' + name + ' </b>Comment:<b> ' + comment + '</b>');
Tunaki
  • 132,869
  • 46
  • 340
  • 423
LosAngeles
  • 83
  • 1
  • 11
  • 3
    What kind of injection? – jor Jun 25 '13 at 20:31
  • use OAuth to protect web services. – abc123 Jun 25 '13 at 20:34
  • A common thing developers protect themselves against is PHP mysql (or other database) injection. Here are some discussions: [SO](http://stackoverflow.com/questions/7043303/php-mysql-injection-protection) [wikipedia](http://en.wikipedia.org/wiki/SQL_injection#Mitigation) [tizag](http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php). Perhaps this is what you are wondering about? – cssyphus Jun 25 '13 at 20:38

3 Answers3

3

There is no way to secure data with JavaScript. because all the code in the client side code is available to the attacker.

But you would have some form of authentication so that only genuine requests from your application returned data;

prefer to read :How can I better protect my php, jquery, ajax requests from malicious users

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

If you want to ensure that the name/email contents are escaped properly for display, you can run them through .text first or create nodes and append their values with .textContent.

var name = document.createElement('span');
name.textContent = $("#name").val();
$("#logga").html("Name: <b>" + name.textContent);
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

Do you mean, that the user couldn't damage the produced html code? Then you'll need to escape the html entities:

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

Output line:

$("#logga").html('Name: <b>' + htmlEntities(name) + ' </b>Comment:<b> ' + htmlEntities(comment) + '</b>');
jor
  • 2,058
  • 2
  • 26
  • 46