Posting special characters in javascript

Discussion in 'JavaScript' started by Silver89, Aug 11, 2010.

  1. #1
    I'm using ajax as a form control which posts a value from a form to a php script to be checked etc before placing into a database.

    However the content can contain characters such as '&, $, £', how can I ask escape these using javascript so that errors don't occur when bad characters are input?

    Thanks
     
    Silver89, Aug 11, 2010 IP
  2. nagarajang

    nagarajang Peon

    Messages:
    20
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You can use var str=@"your string here"; instead.
     
    nagarajang, Aug 11, 2010 IP
  3. Silver89

    Silver89 Notable Member

    Messages:
    2,243
    Likes Received:
    72
    Best Answers:
    0
    Trophy Points:
    205
    #3
    Well the problem is it's in a post manner so:

    variable1=content or post&variable2=second contest of post

    Works okay untill= something like:

    variable1=content or & post&variable2=second contest | of post
     
    Silver89, Aug 12, 2010 IP
  4. siothach

    siothach Active Member

    Messages:
    656
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    60
    #4
    encodeURI & encodeURIComponent method is good to use for this case
     
    siothach, Aug 12, 2010 IP
  5. nagarajang

    nagarajang Peon

    Messages:
    20
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    you can use escape('Your string') function in javascript.... so all your special characters will be converted to '%2%3F' like that to get back what you send you use unescape('received querystring')
     
    nagarajang, Aug 12, 2010 IP
  6. Silver89

    Silver89 Notable Member

    Messages:
    2,243
    Likes Received:
    72
    Best Answers:
    0
    Trophy Points:
    205
    #6
    So sending the post in javascript would be:

    
    var safeTest = escape(test);
    
    xmlhttp.open("POST","insertTest.php",true);
    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("testPost=" + safeTest);
    
    Code (markup):
    Then in php to recover:

    
    $test = urldecode($_POST['testPost']);
    
    PHP:
    (The code is then checked to ensure it is safe before being inserted into a database)
     
    Silver89, Aug 12, 2010 IP