Sunday, 9 April 2017

How to escape mysql special characters with sockets.io/node.js/javascript

I am using sockets.io to insert user-generated messages into MySQL, but I'm running into issues inserting records with an apostrophe. I've been trying to use the replace() method on the client side script, but the input text is passing with the apostrophe.

  socket.on('refresh feed',function(msg){
        str=msg.replace("'", "\'");
        alert(str);
    $("#chtxt").append(str + '<br />');
  });

The above attempt will alert any string without the special character, but does not alert when it exist. I believe that I'm actually alerting after the message has been sent to sockets.

So, I tried adapting this code which watches for the enter key press to also watch for the apostrophe, with no luck there either.

  $('#omnibox').keypress(function (e) {
    var key = e.which;
    if(key == 13)  // the enter key code
    {
      $('input[name = "clicky"]').click();
      return false;  
    }
    if(key == 222)  // the apostrophe key code
    {
            alert('Apostrophe!')
      return false;  
    }
    });

I researched the question of how to replace special characters for MySQL using javascript but found outdated stacks explaining why client-side validation for this is not a good idea.

That's fine. If I shouldn't do this client side, I need to know then how to do it in my server.js node script, then. It is still javascript, so a solution on either side, provided it's secure would be great.

Thanks!



via Dshiz

No comments:

Post a Comment