12

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!

Dan Lew
  • 85,990
  • 32
  • 182
  • 176
Nick
  • 19,198
  • 51
  • 185
  • 312

10 Answers10

19

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);
        console.log(result);
    }
});
Dexter
  • 18,213
  • 4
  • 44
  • 54
Jose Basilio
  • 50,714
  • 13
  • 121
  • 117
  • 1
    I am trying to hit an ajax request via postman. The ajax request is sending dataType:` json` and data: {loginId: "appletest@somedomain.com", client: "698983"}. While going into the postman, I am trying to send body parameters as JSON with all the above info and Content-Type: application/json in headers but it fails with 500. Any help ? – nr5 Oct 03 '19 at 07:57
9

Complete ajax syntax

var data="abc";
       $.ajax({
            type: "GET",
            url: "XYZ",
            data: {
                "data":data,
            },
            dataType: "json",

            //if received a response from the server
            success: function( datas, textStatus, jqXHR) {

            },

            //If there was no resonse from the server
            error: function(jqXHR, textStatus, errorThrown){

            },

            //capture the request before it was sent to server
            beforeSend: function(jqXHR, settings){

            },

            //this is called after the response or error functions are finished
            //so that we can take some action
            complete: function(jqXHR, textStatus){

            }

        }); 
Kumar Mangalam
  • 748
  • 7
  • 12
6

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
  • 480,997
  • 81
  • 517
  • 436
3

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
  • 68,817
  • 22
  • 142
  • 198
1

Though not a direct answer to your question, following is the common function approach used in one of our projects for jquery calls

$.proxy() Method

The Proxy method takes an existing function and returns a new one with a particular context.

Syntaxes

$(selector).proxy(function,context)
$(selector).proxy(context,name)  

CODE

dpInvokeAsync: function (serviceRequest, input, requestType, successCallBack) {
        var url = BASE_URL + serviceRequest;
        $.ajax({
            type: requestType,
            url: url,
            async: true,
            data: input,
            dataType: 'json',
            success: $.proxy(successCallBack, this),
            error:  $.proxy(this.handleFailure, this)
        });
    }


   this.dpInvokeAsync('App/ShowParts', searchCriteria, 'Post',
                      function (result) { alert(result);}
                      );

REFERENCES

  1. $(this) inside of AJAX success not working
  2. jQuery Cross-Domain AJAX Request methods
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418
1

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
  • 1,504
  • 12
  • 16
0

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);
    }
j0k
  • 22,600
  • 28
  • 79
  • 90
khushwant
  • 1
  • 1
  • 3
0

$(document).ready(function(){ getdata(); });

function getdata(){
    $.ajax({
    url:'sample.html',
    type:'get',
    dataType:'text',
    success: succesfun,
    error: errorfun,
    complete:function(xhr, status){
        console.log("your function is success");
    }
});
}
function succesfun(hello){
    console.log("Success");
    $('#result').append(hello);
}
function errorfun(){
    console.log("Error");
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 02 '22 at 12:59
0
  $(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);
         }
  });
});
Srikar Doddi
  • 15,499
  • 15
  • 65
  • 106
0

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}
Alfred
  • 21,058
  • 61
  • 167
  • 249
Chad Grant
  • 44,326
  • 9
  • 65
  • 80