[jquery] Jquery Ajax Posting json to webservice

I am trying to post a JSON object to a asp.net webservice.

My json looks like this:

var markers = { "markers": [
  { "position": "128.3657142857143", "markerPosition": "7" },
  { "position": "235.1944023323615", "markerPosition": "19" },
  { "position": "42.5978231292517", "markerPosition": "-3" }
]};

I am using the json2.js to stringyfy my json object.

and i am using jquery to post it to my webservice.

  $.ajax({
        type: "POST",
        url: "/webservices/PodcastService.asmx/CreateMarkers",
        data: markers,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){alert(data);},
        failure: function(errMsg) {
            alert(errMsg);
        }
  });

I am getting the following error:

"Invalid JSON primitive:

I have found a bunch of posts relating to this and it seems to be a really common problem but nothing i try fixes the issue.

When firebug what is being posted to the server it looks like this:

markers%5B0%5D%5Bposition%5D=128.3657142857143&markers%5B0%5D%5BmarkerPosition%5D=7&markers%5B1%5D%5Bposition%5D=235.1944023323615&markers%5B1%5D%5BmarkerPosition%5D=19&markers%5B2%5D%5Bposition%5D=42.5978231292517&markers%5B2%5D%5BmarkerPosition%5D=-3

My webservice function that is being called is:

[WebMethod]
public string CreateMarkers(string markerArray)
{
    return "received markers";
}

This question is related to jquery ajax web-services json

The answer is


I tried Dave Ward's solution. The data part was not being sent from the browser in the payload part of the post request as the contentType is set to "application/json". Once I removed this line everything worked great.

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },

               { "position": "235.1944023323615", "markerPosition": "19" },

               { "position": "42.5978231292517", "markerPosition": "-3" }];

$.ajax({

    type: "POST",
    url: "/webservices/PodcastService.asmx/CreateMarkers",
    // The key needs to match your method's input parameter (case-sensitive).
    data: JSON.stringify({ Markers: markers }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    failure: function(errMsg) {
        alert(errMsg);
    }
});

Please follow this to by ajax call to webservice of java var param = { feildName: feildValue }; JSON.stringify({data : param})

$.ajax({
            dataType    : 'json',
            type        : 'POST',
            contentType : 'application/json',
            url         : '<%=request.getContextPath()%>/rest/priceGroups',
            data        : JSON.stringify({data : param}),
            success     : function(res) {
                if(res.success == true){
                    $('#alertMessage').html('Successfully price group created.').addClass('alert alert-success fade in');
                    $('#alertMessage').removeClass('alert-danger alert-info');
                    initPriceGroupsList();
                    priceGroupId = 0;
                    resetForm();                                                                    
                }else{                          
                    $('#alertMessage').html(res.message).addClass('alert alert-danger fade in');
                }
                $('#alertMessage').alert();         
                window.setTimeout(function() { 
                    $('#alertMessage').removeClass('in');
                    document.getElementById('message').style.display = 'none';
                }, 5000);
            }
        });

I have query,

$("#login-button").click(function(e){ alert("hiii");

        var username = $("#username-field").val();
        var password = $("#username-field").val();

        alert(username);
        alert("password" + password);



        var markers = { "userName" : "admin","password" : "admin123"};
        $.ajax({
            type: "POST",
            url: url,
            // The key needs to match your method's input parameter (case-sensitive).
            data: JSON.stringify(markers),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){alert("got the data"+data);},
            failure: function(errMsg) {
                alert(errMsg);
            }
        });

    });

I'm posting the the login details in json and getting a string as "Success",but I'm not getting the response.


  1. markers is not a JSON object. It is a normal JavaScript object.
  2. Read about the data: option:

    Data to be sent to the server. It is converted to a query string, if not already a string.

If you want to send the data as JSON, you have to encode it first:

data: {markers: JSON.stringify(markers)}

jQuery does not convert objects or arrays to JSON automatically.


But I assume the error message comes from interpreting the response of the service. The text you send back is not JSON. JSON strings have to be enclosed in double quotes. So you'd have to do:

return "\"received markers\"";

I'm not sure if your actual problem is sending or receiving the data.


I have encountered this one too and this is my solution.

If you are encountering an invalid json object exception when parsing data, even though you know that your json string is correct, stringify the data you received in your ajax code before parsing it to JSON:

$.post(CONTEXT+"servlet/capture",{
        yesTransactionId : yesTransactionId, 
        productOfferId : productOfferId
        },
        function(data){
            try{
                var trimData = $.trim(JSON.stringify(data));
                var obj      = $.parseJSON(trimData);
                if(obj.success == 'true'){ 
                    //some codes ...

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?