Link to home
Start Free TrialLog in
Avatar of jpschreibman
jpschreibman

asked on

Javascript/AJAX/Prototype.js need help encoding/decoding special chars in var

I am using prototype.js to pass a variable to a PHP script.

This variable is big and ugly- a YouTube embed code. It looks like this:

<object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/b_OjZyQ6LGE&rel=1"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/b_OjZyQ6LGE&rel=1" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></embed></object>

I need:

1. Some way to encode this var in javascript so it passes over to PHP

2. Some way to decode it on the PHP script once it gets there

My AJAX function is below:
function AddNewVideo() {
		new Ajax.Request("./ajax/add_video.php", 
		{ 
			method: 'post', 
			postBody: 'video='+ $F('new_video'),
			onCreate: showWorkingMessage,
			onComplete: showResponseForm
			});
		}
		function showWorkingMessage(req){$('AddNewVideo').innerHTML = '--loader gif --';}
		function showResponseForm(req){$('AddNewVideo').innerHTML= req.responseText;}

Open in new window

Avatar of hielo
hielo
Flag of Wallis and Futuna image

Just "pass" the string to string through encodeURIComponent().
Refer to:
http://xkr.us/articles/javascript/encode-compare/

Not sure where you are getting your <object>....</object> from but the idea is this:
var data ='<object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/b_OjZyQ6LGE&rel=1"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/b_OjZyQ6LGE&rel=1" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></embed></object>';
var encodedValue = encodeURIComponent(data);

...
postBody:'video=' + encodedValue,

From what you posted my guess is that $F('new_video') contains all the <object>...</object> code. If so, then you can encode it directly without having to save it to a variable. So, it would be:
postBody:'video='+encodeURIComponent( $F('new_video') );

On the server, you just retrieve the video parameter as if nothing was encoded. You should be OK.
Avatar of jpschreibman
jpschreibman

ASKER

hielo:

You are correct: $F('new_video') contains the "object" code. This comes from YouTube by the way.

I am able to get the data to the PHP script, but something is getting messed up in transition. The video preview won't play.

Because I am using AJAX, I can't "view source" to see what is going on.

Please advise.

Josh
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Firebug rules. Sorry to be such a n00b.
>>Firebug rules.
Welcome to the club

>>Sorry to be such a n00b.
Everyone is n00b at some point. No need to be apologetic about it. Have fun!