2

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++;
    });
}
MattP
  • 2,798
  • 2
  • 31
  • 42
  • 1
    look at http://stackoverflow.com/questions/332872/how-to-encode-a-url-in-javascript – Barbara Laird Oct 23 '13 at 17:28
  • 1
    If you passed your data as an object, jquery would solve that for you. serialize or serializeArray would work too. Also, your priority var is redundant, $.each already gives you access to the current index. – Kevin B Oct 23 '13 at 17:32

1 Answers1

3

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.

PlantTheIdea
  • 16,061
  • 5
  • 35
  • 40