Tom
Tom

Reputation: 2634

escape characters with javascript

I have a function that opens up a browser window:

function startmonitor(camerahash, cameraname, cameraflashquality, cameramotion)
{
    window.open("mydir/file.php?user="+'<?php echo $id_hash; ?>'+"&camera="+camerahash+"&name="+cameraname+"&quality="+cameraflashquality+"&motion="+cameramotion, "Webcam_monitor");
}

cameraname is passed in from a button in html:

<button id="monitor" onclick="startmonitor('<?php echo $result_cameras[$i]["camera_hash"]; ?>', '<?php echo $result_cameras[$i]["camera_name"]; ?>', '<?php echo $camera_quality_flash; ?>', '<?php echo $camera_motion; ?>');">Start Camera</button>

cameraname does take special characters. Such as Al's camera. Because of the special character it messes up the window.open line. Anyone have ideas how I can rewrite the window.open line to accommodate this?

Upvotes: 0

Views: 303

Answers (2)

jeremysawesome
jeremysawesome

Reputation: 7254

You might try encodeUri

function startmonitor(camerahash, cameraname, cameraflashquality, cameramotion)
{
    window.open(encodeUri("file.php?user="+'<?php echo $id_hash; ?>'+"&camera="+camerahash+"&name="+cameraname+"&quality="+cameraflashquality+"&motion="+cameramotion), "Webcam_monitor");
}

Edit: Actually, because you are wanting to encode the apostrophe, you would need to use the escape function around the variables you wish to escape. In this case it would be used around the cameraname variable.

function startmonitor(camerahash, cameraname, cameraflashquality, cameramotion)
{
    window.open("file.php?user="+'<?php echo $id_hash; ?>'+"&camera="+camerahash+"&name="+escape(cameraname)+"&quality="+cameraflashquality+"&motion="+cameramotion, "Webcam_monitor");
}

Edit 2 OK, it looks like, based on your comment below, that you need to escape cameraname before it enters your startmonitor function. So you would actually escape it in your button code and not in your function code.

<button id="monitor" onclick="startmonitor('<?php echo $result_cameras[$i]["camera_hash"]; ?>', escape('<?php echo $result_cameras[$i]["camera_name"]; ?>'), '<?php echo $camera_quality_flash; ?>', '<?php echo $camera_motion; ?>');">Start Camera</button>

Edit 3 Wow - I'm retarded. Just encode with php's urlencode function before outputting to the page.

<button id="monitor" onclick="startmonitor('<?php echo $result_cameras[$i]["camera_hash"]; ?>', <?php echo urlencode($result_cameras[$i]["camera_name"]); ?>, '<?php echo $camera_quality_flash; ?>', '<?php echo $camera_motion; ?>');">Start Camera</button>

Upvotes: 2

Joseph
Joseph

Reputation: 119887

There are 3 ways to escape special characters:

  • escape()
  • encodeURI()
  • encodeURIComponent()

Upvotes: 2

Related Questions