views:

22

answers:

4

Hey,

I am working on submitting values into a database through AJAX. It currently uses JQuery Ajax object.My Ajax code basically looks like this:

enter code here

var genre = form.new_album_genre.value; form.new_album_genre.value="";

$.ajax({
    type: "POST",
    data: "genre="+genre+"&app="+app,
    url: 'apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php',
    success: function(data) {
    $('#'+divID).html(data);

} });

In short, it gets a value from a form and then submits the data through a post. Where it fails if the genre is something like R&B. The & symbol is not sumbitting and only the R is. So how do I submit values through AJAX including &, + and = ?

+1  A: 

You need to encodeURIComponent to deal with characters which have special meaning in URIs.

(Or pass an object containing key/value pairs to jQuery instead of the query string String you have now)

David Dorward
Thanks, that worked quicky and easily
Devin Dixon
for extensibility and maintenance purposes, however, you are better off using the data: { //insert object key : value pairs here } approach. Otherwise you'll have to remember to encodeURIComponent() every time. Plus, passing around giant query strings is so 2002...
Visionary Software Solutions
A: 

Use

$.ajax({
    type: "POST",
    data: "genre="+encodeURIComponent(genre)+"&app="+encodeURIComponent(app),
    url: 'apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php',
    success: function(data) {
    $('#'+divID).html(data);

Because of the & it is interpreted as a new parameter.
In your case data will look like genre=R&B&app=somethig -> this means 3 parameters: genre, B and app.

Parkyprg
Don't use `escape`, it doesn't work properly and has been deprecated!
David Dorward
@David Dorward: you are right. I modified the answer.
Parkyprg
A: 

I've never had a problem with special chars using

$.post('apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php', {
    'genre' : genre,
    'app' : app
},
function(data) {
    $('#'+divID).html(data);
});
methodin
A: 

Piggybacking off David Dorward's answer

 $.ajax({
            type: 'POST',
            url: 'apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php',
            data: { genre : form.new_album_genre.value, app: form.app.value },
            success: function (data, textStatus) {
                $('#'+divID).html(data);

            }
        });
Visionary Software Solutions