Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL in AJAX POST

Tags:

jquery

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.

like image 305
TheNone Avatar asked Jan 27 '11 13:01

TheNone


People also ask

What is the URL in AJAX call?

The url parameter is a string containing the URL you want to reach with the Ajax call, while settings is an object literal containing the configuration for the Ajax request. In its first form, this function performs an Ajax request using the url parameter and the options specified in settings .

Does AJAX need a URL?

You need to specify the url because whenever you make a server request (whether it be using AJAX, or synchronous-old fashion way) you need to tell the browser who to send the request to. Almost all the examples I saw in the jQuery documentation page have a specified URL or some sort (url: "test.

What is contentType in AJAX?

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8 , which is the default. dataType is what you're expecting back from the server: json , html , text , etc.


1 Answers

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.

like image 180
T.J. Crowder Avatar answered Oct 18 '22 21:10

T.J. Crowder