2

I have a url string like this:

http://www.google.com/cse?cx=017840637368510444960:ny1lmky7r-0&client=google-csbe&output=xml_no_dtd&q=simon+g

I need to send this url from ajax to a php script as a single string variable.

I am having trouble though because it keeps getting split into several vars because of the vars in the url string itself. Make sense? How can I send this as a single string??

Thanks!!!

JD Isaacks
  • 56,088
  • 93
  • 276
  • 422

6 Answers6

6

You need to encode it.

In PHP: urlencode()

$str = urlencode('http://....');

In Javascript: encodeURIComponent

str = encodeURIComponent('http://...');
Greg
  • 316,276
  • 54
  • 369
  • 333
  • 2
    Hmm... if you're passing it though in GET or POST then PHP should decode it for you. – Greg May 22 '09 at 14:54
4

You need to urlencode the url. You will then urldecode on the page that receives it.

So the url would become

http%3A%2F%2Fwww.google.com%2Fcse%3Fcx%3D017840637368510444960%3Any1lmky7r-0%26client%3Dgoogle-csbe%26output%3Dxml_no_dtd%26q%3Dsimon%2Bg%0D%0A
Jab
  • 13,713
  • 2
  • 42
  • 48
1

escape() or encodeURIComponent()

Maciej Łebkowski
  • 3,837
  • 24
  • 32
1

I guess you need to escape() in javascript like this

escape("cx=017840637368510444960:ny1lmky7r-0&client=google-csbe&output=xml_no_dtd&q=simon+g" )

Edit: I just searched and found that encodeURIComponent() is the best solution.

See http://xkr.us/articles/javascript/encode-compare/ for a nice comparison of escape(), encodeURI() and encodeURIComponent()

Tahir Akhtar
  • 11,385
  • 7
  • 42
  • 69
1
<?php 
// In your URL-emitter page
$decoded_url = "http://www.google.com/cse?cx=017840637368510444960:ny1lmky7r-0&client=google-csbe&output=xml_no_dtd&q=simon+g";
$link_addr = "/index.php?encodedurl=".urlencode($decoded_url);

echo '<a href="'.$link_addr.'">Click me</a>';


// in your URL-reciever page (here the same page)
if(array_key_exists("encodedurl",$_GET)) {
    echo 'decoded url='.urldecode($_GET["encodedurl"]);
}
Lau
  • 31
  • 1
  • 7
-1

also, you could try encryption (like base64)

Jake
  • 3,973
  • 24
  • 36
  • Right, not encryption. And... heh.. third-party base64 on JS to encode URL... why? – Jet May 22 '09 at 16:27
  • @Tahir Akthar; you are right, my bad! I read the post all wrong, and added a stupid answer :) – Jake May 25 '09 at 08:05