0

I need to pass fields content from a table database to a JavaSricpt function in my web page.

I found an error when I have a backslash in the string :

{"DT_RowId":"4427","pront":"4427","nome":"JOHN DOE","conv":"PETROBRAS\ DISTR ( R)","cpf":"","email":""}

See:"PETROBRAS\"

In this case, I found that backslash was the cause of the problem.

I know I can solve this particular problem, but the table database I am using has many rows, and may be, can have others chars that can cause problems to JavaScript in my page

Is there a delphi function to escape all invalids chars(considering JavaScript) in a delphi string in order to pass to jasvascript function?

function EscapeDelphiStringToJS(s:string):string
begin
  result:= "how  could I do the escaping?"
end;

Remy, Here is the code I am using to create the Json. I am using XE8.

In order to return the data to my ajax function, I just convert the result function to string using: jso.tostring; But, this is not the problem.

function TContentClient.select_client(aParams: TStrings): 
var so,jsoItem:TJsonObject;
    jsa:TJsonArray;
    jsp:TJSONPair;
    ds:Tdataset;
  .....
begin
            TJsonObject;_recordsTotal:=IntToStr(ds.RecordCount);
            jso:=TJsonObject.Create;
            jso.AddPair('draw',TJsonNumber.Create(_draw));
            jso.AddPair('recordsTotal',TJsonNumber.Create(_recordsTotal));
            jso.AddPair('recordsFiltered',TJsonNumber.Create(_recordsTotal));
            //create an json-array
            jsa := TJsonArray.Create();
            //add array to object
            while not ds.eof do begin
                //add items to the _first_ elemet of array
                jsoItem := TJsonObject.Create();
                //add object pairs
                jsoItem.AddPair(TJsonPair.Create('DT_RowId',TJsonString.Create(ds.FieldByname('pront').AsString)));
                jsoItem.AddPair(TJsonPair.Create('pront', TJsonString.Create(ds.FieldByname('pront').AsString)));
                jsoItem.AddPair(TJsonPair.Create('nome', TJsonString.Create(ds.FieldByname('nome').AsString)));

                jsoItem.AddPair(TJsonPair.Create('endereco', TJsonString.Create(ds.FieldByname('endereco').AsString)));
                jsoItem.AddPair(TJsonPair.Create('bairro', TJsonString.Create(ds.FieldByname('bairro').AsString)));
                jsoItem.AddPair(TJsonPair.Create('cidade', TJsonString.Create(ds.FieldByname('cidade').AsString)));
                jsoItem.AddPair(TJsonPair.Create('estado', TJsonString.Create(ds.FieldByname('estado').AsString)));
                jsoItem.AddPair(TJsonPair.Create('telefone', TJsonString.Create(ds.FieldByname('telres').AsString)));
                jsoItem.AddPair(TJsonPair.Create('convenio', TJsonString.Create(ds.FieldByname('convenio').AsString)));
                jsoItem.AddPair(TJsonPair.Create('cpf', TJsonString.Create(ds.FieldByname('cpf').AsString)));
                jsoItem.AddPair(TJsonPair.Create('email', TJsonString.Create(ds.FieldByname('email').AsString)));
                //put it into array
                jsa.AddElement(jsoItem);
                ds.Next;
            end;
            jsp := TJSONPair.Create('data', jsa);
            jso.AddPair(jsp);

            result:=jso;
end;

This is the result of the function:

{
    "draw": 3,
    "recordsTotal": 5303,
    "recordsFiltered": 5303,
    "data": [{
        "DT_RowId": "2582",
        "pront": "2582",
        "nome": "XXXXX",
        "endereco": "RUA TEODORO DA SILVA,333/103",
        "bairro": "VILA ISABEL",
        "cidade": "RIO DE JANEIRO",
        "estado": "RJ",
        "telefone": "3683*2690",
        "convenio": "GOLDEN CROSS ( B)",
        "cpf": "",
        "email": ""
    }, {
        "DT_RowId": "2818",
        "pront": "2818",
        "nome": "YYYYY",
        "endereco": "RUA PEREIRA NUNES , 395 AP 308",
        "bairro": "VILA ISABEL",
        "cidade": "RIO DE JANEIRO",
        "estado": "RJ",
        "telefone": "YYYYY",
        "convenio": "UN",
        "cpf": "216820707-00",
        "email": ""
    }, {
        "DT_RowId": "1015",
        "pront": "1015",
        "nome": "YYYYYY",
        "endereco": "rua francisca zieze, 192",
        "bairro": "aboliçao",
        "cidade": "RIO DE JANEIRO",
        "estado": "RJ",
        "telefone": "25945909",
        "convenio": "UN",
        "cpf": "71883592704",
        "email": ""
    }, {
        "DT_RowId": "1701",
        "pront": "1701",
        "nome": "JJJJJJ",
        "endereco": "AV 28 DE SETEMBRO 163 APT 704",
        "bairro": "VILA ISABEL",
        "cidade": "RIO DE JANEIRO",
        "estado": "RJ",
        "telefone": "2253-7625",
        "convenio": "PETROBRAS DISTR\ ( R)",
        "cpf": "",
        "email": ""
    }, {
        "DT_RowId": "1076",
        "pront": "1076",
        "nome": "LLLLLLLL",
        "endereco": "RUA ARISTIDES ,241/304",
        "bairro": "MEIER",
        "cidade": "RIO DE JANEIRO",
        "estado": "RJ",
        "telefone": "2501*6600",
        "convenio": "CORREIOS",
        "cpf": "",
        "email": ""
    }, {
        "DT_RowId": "5959",
        "pront": "5959",
        "nome": "ZULEICA IIIII",
        "endereco": "rua dos araujos 11a, bl 02 ap 301",
        "bairro": "tijuca",
        "cidade": "RIO DE JANEIRO",
        "estado": "RJ",
        "telefone": "2254-5682",
        "convenio": "AMIL",
        "cpf": "53150457734",
        "email": ""
    }, {
        "DT_RowId": "5894",
        "pront": "5894",
        "nome": "ZULEICA AAAAA",
        "endereco": "RUA PROF GABIZO,332/102",
        "bairro": "TIJUCA",
        "cidade": "RIO DE JANEIRO",
        "estado": "RJ",
        "telefone": "2568*9654",
        "convenio": "UNIMED (SCOFANO)",
        "cpf": "54016843715",
        "email": ""
    }, {
        "DT_RowId": "4034",
        "pront": "4034",
        "nome": "ZILENE KAKAKA",
        "endereco": "RUA AFONSO FERREIRA ,162",
        "bairro": "ENGENHO DE DENTRO",
        "cidade": "RIO DE JANEIRO",
        "estado": "RJ",
        "telefone": "2597*2352",
        "convenio": "CORREIOS",
        "cpf": "",
        "email": ""
    }, {
        "DT_RowId": "5126",
        "pront": "5126",
        "nome": "ZILDA MAMAMA",
        "endereco": "AV DOM HELDER CAMARA 1201",
        "bairro": "BENFICA",
        "cidade": "RIO DE JANEIRO",
        "estado": "RJ",
        "telefone": "7646-0691",
        "convenio": "BRADESCO (B)",
        "cpf": "",
        "email": ""
    }, {
        "DT_RowId": "4497",
        "pront": "4497",
        "nome": "ZILDA LALALA",
        "endereco": "RUA SABARRETO , 13 CASA",
        "bairro": "FONSECA - NITEROI",
        "cidade": "RIO DE JANEIRO",
        "estado": "RJ",
        "telefone": "2721-6646",
        "convenio": "UNIMED (SCOFANO)",
        "cpf": "",
        "email": ""
    }]
}
Luiz Alves
  • 2,575
  • 4
  • 34
  • 75
  • The data you are passing to JavaScript is JSON. What are you using to convert the database data to JSON? It needs to escape slash characters, but it is not doing so in your case. Are you converting the data manually? If so, you should be using a JSON library instead. – Remy Lebeau Jan 27 '17 at 22:23
  • Use a JSON library as nature intended. – David Heffernan Jan 27 '17 at 22:48
  • You can also have a look here :[convert-a-string-to-and-from-json](http://stackoverflow.com/questions/11785963/how-do-i-convert-a-string-to-and-from-json-with-escaped-special-characters-using) – moskito-x Jan 28 '17 at 01:28
  • @Remy I am coding manually, because I would not want add Json library overhead to my app. This is a Intraweb app. I just thought there would be a delphi function to do it. I already used JSON delphi library, but in this case, it´s more than I need. – Luiz Alves Jan 28 '17 at 20:52
  • @LuizAlves then you have to manually detect and encode the few reserved characters that JSON has (double-quote, forward slash, and a few control characters). See the definition at http://json.org – Remy Lebeau Jan 28 '17 at 22:35
  • What overhead?? – David Heffernan Jan 28 '17 at 22:52
  • @Remy Lebeau I just recreate the string using json delphi library. It makes no difference. The string created is the same I had before. No changes. I have the next error in chrome when I call my ajax: SyntaxError: Unexpected token in JSON at position 1017 at JSON.parse () at n.parseJSON (jquery.min.js:4) at Xb (jquery.min.js:4) at y (jquery.min.js:4) at XMLHttpRequest.c (jquery.min.js:4) – Luiz Alves Feb 02 '17 at 03:34
  • Is valid I have "\" into a json string? I am using Jquery datatables and I have this error when I load my data. – Luiz Alves Feb 02 '17 at 03:36
  • Maybe a problem with javascript parse? – Luiz Alves Feb 02 '17 at 03:56
  • "\" is a reserved character in JSON, it must be escaped. I find it hard to believe that any JSON library would not do that. Can you please edit your question to show the code you tried? – Remy Lebeau Feb 02 '17 at 05:50
  • @ Remy Lebeau I just posted the code. – Luiz Alves Feb 02 '17 at 13:42
  • I just see that http://qc.embarcadero.com/wc/qcmain.aspx?d=119779. The problem is really on toString conversion. I do it to return data to my ajax function. I had to use toJSon and the problem was solved. – Luiz Alves Feb 02 '17 at 14:17

1 Answers1

-2

from svn https://svn.code.sf.net/p/alcinoe/code/ (you can find inside the unicode string implementation also but i prefere to gave here the ansiString as reference)

{******************************************************************************************}
// https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals
function  ALJavascriptEncode(const Src: AnsiString; const useNumericReference: boolean = True): AnsiString;
var i, l: integer;
    Buf, P: PAnsiChar;
    ch: Integer;
begin
  Result := '';
  L := Length(src);
  if L = 0 then exit;
  if useNumericReference then GetMem(Buf, L * 6) // to be on the *very* safe side
  else GetMem(Buf, L * 2); // to be on the *very* safe side
  try
    P := Buf;
    for i := low(Src) to high(Src) do begin
      ch := Ord(src[i]);
      case ch of
        8: begin // Backspace
             if useNumericReference then begin
               ALStrMove('\u0008', P, 6);
               Inc(P, 6);
             end
             else begin
               ALStrMove('\b', P, 2);
               Inc(P, 2);
             end;
           end;
        9: begin // Tab
             if useNumericReference then begin
               ALStrMove('\u0009', P, 6);
               Inc(P, 6);
             end
             else begin
               ALStrMove('\t', P, 2);
               Inc(P, 2);
             end;
           end;
        10: begin // New line
              if useNumericReference then begin
                ALStrMove('\u000A', P, 6);
                Inc(P, 6);
              end
              else begin
                ALStrMove('\n', P, 2);
                Inc(P, 2);
              end;
            end;
        11: begin // Vertical tab
              if useNumericReference then begin
                ALStrMove('\u000B', P, 6);
                Inc(P, 6);
              end
              else begin
                ALStrMove('\v', P, 2);
                Inc(P, 2);
              end;
            end;
        12: begin // Form feed
              if useNumericReference then begin
                ALStrMove('\u000C', P, 6);
                Inc(P, 6);
              end
              else begin
                ALStrMove('\f', P, 2);
                Inc(P, 2);
              end;
            end;
        13: begin // Carriage return
              if useNumericReference then begin
                ALStrMove('\u000D', P, 6);
                Inc(P, 6);
              end
              else begin
                ALStrMove('\r', P, 2);
                Inc(P, 2);
              end;
            end;
        34: begin // Double quote
              if useNumericReference then begin
                ALStrMove('\u0022', P, 6);
                Inc(P, 6);
              end
              else begin
                ALStrMove('\"', P, 2);
                Inc(P, 2);
              end;
            end;
        38: begin // & ... we need to encode it because in javascript ' or & will be converted to ' and error unterminated string
              ALStrMove('\u0026', P, 6);
              Inc(P, 6);
            end;
        39: begin // Apostrophe or single quote
              if useNumericReference then begin
                ALStrMove('\u0027', P, 6);
                Inc(P, 6);
              end
              else begin
                ALStrMove('\''', P, 2);
                Inc(P, 2);
              end;
            end;
        60: begin // < ... mostly to hide all </script> tag inside javascript.
                  // http://www.wwco.com/~wls/blog/2007/04/25/using-script-in-a-javascript-literal/
              ALStrMove('\u003C', P, 6);
              Inc(P, 6);
            end;
        62: begin // > ... mostly to hide all HTML tag inside javascript.
              ALStrMove('\u003E', P, 6);
              Inc(P, 6);
            end;
        92: begin // Backslash character (\).
              if useNumericReference then begin
                ALStrMove('\u005C', P, 6);
                Inc(P, 6);
              end
              else begin
                ALStrMove('\\', P, 2);
                Inc(P, 2);
              end;
            end;
        else Begin
          P^:= AnsiChar(ch);
          Inc(P);
        end;
      end;
    end;
    SetString(Result, Buf, P - Buf);
  finally
    FreeMem(Buf);
  end;
end;
zeus
  • 12,173
  • 9
  • 63
  • 184