MattP
MattP

Reputation: 2863

JQuery AJAX POST request with Special Characters

I have an issue with an admin page that sends data using JQuery AJAX, but it doesn't handle & or ", and the reason is obvious (they break the data string/url).

What is the correct way to send this data using Javascript that will allow these characters? Using an array of data may solve for & but would it solve for "?

Example input that must be acceptable: Do this & press "enter"

function SaveCombinations() {
    var priority = 0;
    $("#sort li").each(function() {
        $.ajax({"url": "lib/sc-save.php", "data": "id="+this.id+"&name="+$(this).find("input").val()+"&priority="+priority, "type": "POST",
        "success": function() {}});
        priority++;
    });
}

Upvotes: 2

Views: 6829

Answers (1)

PlantTheIdea
PlantTheIdea

Reputation: 16359

Pass your data as an object, and it will be taken care of for you:

function SaveCombinations() {
    var p = 0;

    $('#sort li').each(function(){
        var $id = this.id,
            $name = $(this).find('input').val(),
            $priority = p, // you don't really need to do this, its just a maintainability thing in case it changes in the future
            $data = {id:$id,name:$name,priority:$priority};

        $.ajax({
            type:'POST',
            url:'lib/sc-save.php',
            data:$data  
        }).done(function(){
            p++;
        });
    });
}

Something along these lines should both solve your problem, and be a hell of a lot easier to read / maintain.

EDIT

As someone pointed out, the index is already handled for you by the .each() function.

function SaveCombinations() {
    $('#sort li').each(function(i){
        var $id = this.id,
            $name = $(this).find('input').val(),
            $priority = i,
            $data = {id:$id,name:$name,priority:$priority};

        $.ajax({
            type:'POST',
            url:'lib/sc-save.php',
            data:$data                
        });
    });
}

This would also work just fine for the implementation.

Upvotes: 3

Related Questions