views:

1396

answers:

7
+1  Q: 

JQuery AJAX syntax

I am trying to find the correct syntax to pass a varible to my JQuery Post.

var id = empid;

$.ajax({
    type: "POST",
    url: "../Webservices/EmployeeService.asmx/GetEmployeeOrders",
    data: "{empid: empid}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(result) {
        alert(result.d);
    }

I don't think the data: value is quite right. Someone set me straight?

Thanks!

+2  A: 

data can either be a URL encoded string or an object:

data: {empid: empid},

OR

data: "empid=" + empid,

The docs say:

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

Paolo Bergantino
A: 

This should work for you.

$.ajax({
    type: "POST",
    url: "../Webservices/EmployeeService.asmx/GetEmployeeOrders",
    data: {empid: empid},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(result) {
        alert(result.d);
}
Ólafur Waage
A: 
  $(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "Webservices/EmployeeService.asmx/GetEmployeeOrders",
    data: "{'EmployeeId':'empid'}", **<-- see the single quotes**
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
          alert(msg);
         }
  });
});
CodeToGlory
+2  A: 

How about this: var id = empid;

$.ajax({
    type: "POST",
    url: "../Webservices/EmployeeService.asmx/GetEmployeeOrders",
    data: "{empid: " + empid + "}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(result) {
        alert(result.d);
    }
);
Jose Basilio
+1  A: 

It's not. You're passing a string, you should be passing an object literal,e.g.

data: {"empid" : empid}

See the difference? Assuming empid is a variable with some sort of value, that should work fine. Alternatively you can do this

data: "empid="+empid

http://docs.jquery.com/Ajax/jQuery.ajax#options

bdl
A: 

if you want to send a JSON string to the server

data: "{empid: " + empid + "}"

if you want to send querystring params (?empid=123)

data: {empid : empid}

Chad Grant
A: 

hi

you can use the following.

var id = empid;

$.ajax({ type: "POST", url: "../Webservices/EmployeeService.asmx/GetEmployeeOrders", data: "var1=val1&var2=val2&var3=val3&var4=val4&var5=val5", contentType: "application/json; charset=utf-8", dataType: "json", success: function(result) { alert(result.d); }

khushwant