TheNone TheNone - 2 months ago 7
jQuery Question

URL in AJAX POST

I want to post these variables via AJAX:

<div class="vIn" id="star">
<div id="inner">
<span id="1" class="disabled"></span>
<span id="2" class="disabled"></span>
<span id="3" class="disabled"></span>
<span id="4" class="disabled"></span>
<span id="5" class="disabled"></span>
<input type="hidden" id="<?php echo $_GET['cID']?>" />
</div>
</div>


With this script:

$(document).ready(function(){
$('#inner span').click(function(){
$(this).prevAll().andSelf().addClass('enabled');
var a = $(this).attr("id");
var cID = $("#inner input").attr("id");
$.ajax({
type: "POST",
url: "ajax/rating.php",
data: "value=+a+&cID=+cID+",
success: function(msg){
alert(data);
}
});
});});


On the click event, there is no alert. Am I using the right data in $.ajax?
Thanks in advance.

Answer

I would strongly recommend allowing jQuery to worry about properly encoding the string:

var a = $(this).attr("id");
var cID = $("#inner input").attr("id");
$.ajax({
    type: "POST",
    url: "ajax/rating.php",
    data: {value: a, cID: cID},   // <== change is here
    success: function(msg){
        alert(msg);
    }
});

Note that I'm passing data into $.ajax as an object, not as a string. jQuery will correctly encode it for you. See the docs for details.

If you really, really want to do the encoding yourself, you have to do it explicitly:

data: "value=" + encodeURIComponent(a) + "&cID=" + encodeURIComponent(cID)

Also note that I'm alerting msg, not data, as that's what you've called the response argument to success.