Ampersand in GET, PHP

I have a simple form that generates a new photo gallery, sends the title and description to MySQL, and redirects the user to a page where they can upload photos.

Everything worked fine until the ampersand entered the equation. Information is sent from the jQuery modal dialog to a PHP page, which then sends the record to the database. After the successful completion of Ajax, the user is sent to the download page with the GET URL to tell the page to which album it is being loaded -

$.ajax ({ type: "POST", url: "../../includes/forms/add_gallery.php", data: $("#addGallery form").serialize(), success: function() { $("#addGallery").dialog('close'); window.location.href = 'display_album.php?album=' + title; } }); 

If the title has an ampersand, the "Title" field on the download page does not display correctly. Is there any way to avoid ampersand for GET?

thanks

+6
jquery html ajax php get
source share
2 answers

In general, you'll want a URL encode for anything that is not fully alphanumeric when you pass them as part of your URLs.

In URL encoding, & is replaced with %26 (because 0x26 = 38 = ASCII & code).

To do this in Javascript, you can use the encodeURIComponent function:

 $.ajax ({ type: "POST", url: "../../includes/forms/add_gallery.php", data: $("#addGallery form").serialize(), success: function() { $("#addGallery").dialog('close'); window.location.href = 'display_album.php?album=' + encodeURIComponent(title); } }); 

Note that escape has the disadvantage that + not encoded and will be decoded by the server as space, and therefore ( source ).

If you want to make this server server at the PHP level, you will need to use the urlencode function.

+13
source share
 window.location.href = 'display_album.php?album=' + encodeURIComponent(title); 

The javascript escape function will not encode these characters: * @ - _ +. /. Therefore, if you have a heading like "this + that", the plus sign will be interpreted as a space, and PHP will get a variable like "this."

Using encodeURIComponent will also encode the following characters:, / ?: @ and = + $ #

+1
source share

All Articles