0

I'm facing a freak problem in jquery. When I try to populate a list from a table it becomes empty if it contains a special character like sid'ahmed. When I change it to sidi ahmed it works perfectly. This is my code to populate two lists:

$.getJSON("get-data.php?dat=driver", function(data) {
  var stringToAppend1 = "<option value='" + day_Shift + "'>" + day_Shift + "</option>";
  var stringToAppend2 = "<option value='" + night_Shift + "'>" + night_Shift + "</option>";

  $.each(data, function(key, val) {
    stringToAppend1 += "<option value='" + val.prenom + " / " + val.nom + " : " + val.telephone + "'>" + val.prenom + " / " + val.nom + " : " + val.telephone + "</option>";
    stringToAppend2 += "<option value='" + val.prenom + " / " + val.nom + " : " + val.telephone + "'>" + val.prenom + " / " + val.nom + " : " + val.telephone + "</option>";
  });

  $("#night_Shift_text" + id).html(stringToAppend2);
  $("#day_Shift_text" + id).html(stringToAppend1);
});
Mike Hanslo
  • 274
  • 3
  • 14
NoGodButAllah
  • 69
  • 1
  • 7
  • have you tried escaping the input? It's a bad idea to just insert stuff from external sources that way (XSS voulnerabilty). It also creates your problem. – Mirko Vukušić Feb 23 '17 at 11:46
  • the single quote is the string delimiter. you need to escape it when it occurs inside a string: http://stackoverflow.com/questions/2428572/how-to-escape-single-quote, http://stackoverflow.com/questions/16134910/how-to-escape-a-single-quote-in-javascript – Cee McSharpface Feb 23 '17 at 11:47
  • it is already in database I want just to use it to populate my list – NoGodButAllah Feb 23 '17 at 11:48

1 Answers1

0

You should escape the single quote by using replace function as shown below. Use this replace whereever needed.

day_Shift = day_Shift.replace(/'/g, "\\'");

Hope this helps!!

Praveen
  • 1,449
  • 16
  • 25