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:




My webservice function that is being called is:

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


You mentioned using json2.js to stringify your data, but the POSTed data appears to be URLEncoded JSON You may have already seen it, but <a href="http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/" rel="nofollow">this post about the invalid JSON primitive</a> covers why the JSON is being URLEncoded.

I'd <a href="http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/" rel="nofollow">advise <em>against</em> passing a raw, manually-serialized JSON string into your method</a>. ASP.NET is going to automatically JSON deserialize the request's POST data, so if you're manually serializing and sending a JSON string to ASP.NET, you'll actually end up having to JSON serialize your JSON serialized string.

I'd suggest something more along these lines:

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); } });

The key to avoiding the invalid JSON primitive issue is to pass jQuery a JSON string for the data parameter, not a JavaScript object, so that jQuery doesn't attempt to URLEncode your data.

On the server-side, match your method's input parameters to the shape of the data you're passing in:

public class Marker { public decimal position { get; set; } public int markerPosition { get; set; } } [WebMethod] public string CreateMarkers(List<Marker> Markers) { return "Received " + Markers.Count + " markers."; }

You can also accept an array, like Marker[] Markers, if you prefer. The deserializer that ASMX ScriptServices uses (JavaScriptSerializer) is pretty flexible, and will do what it can to convert your input data into the server-side type you specify.


<ol><li>markers is not a JSON object. It is a normal JavaScript object.</li> <li><a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow">Read about the data: option</a>: <blockquote>

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

</blockquote></li> </ol>

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.

<hr />

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 ...


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 <strong>contentType</strong> 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); } });


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.


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); } });


  • How to execute javascript method from server side?
  • Draw Filled Shape from Four Points
  • Check for file existence if Laravel's Blade template
  • AngularJS $http return value
  • The required anti-forgery cookie “__RequestVerificationToken” is not present. MVC 5
  • Django : Model Instance history
  • Best GAC Tutorial/Overview? [closed]
  • Express.js : POST data as KEY of a req.body object instead of VALUE of req.body?
  • Representing intervals or ranges? [closed]
  • Laravel lmutator $this->attributes return 'Undefined index: id'
  • Plotting Route with Multiple Points in iOS
  • How to set an entity field that does not exist on the table but does exists in the raw SQL as an ali
  • How do I check if System::Collections:ArrayList is empty / nullptr / null?
  • Creating a C++ function that calls other Lua function
  • How does the HEXTORAW() function work? What is the algorithm?
  • to implement a spinner in angular2+
  • Count from each distinct date, fill in missing dates with zero
  • What is the undocumented SessionIdInterface in PHP 5.5?
  • File extension of zlib zipped html page?
  • Failed to find version-tag string. File must be updated
  • Alamofire and Reachability.swift not working on xCode8-beta5
  • Using Generics on right hand side in Java 6?
  • How to use function wrapper in mustache.php?
  • How do I display a dialog that asks the user multi-choice questıon using tkInter?
  • how does System.Web.HttpRequest::PathInfo work?
  • CakePHP ACL tutorial initDB function warnings
  • Apache RewriteRule redirection with url encoded
  • Test if a set exists before trying to drop it
  • Chrome doesn't support silverlight anymore? How to solve this?
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • Using variable in a value field in jMeter
  • Fetching methods from BroadcastReceiver to update UI
  • swift auto completion not working in Xcode6-Beta
  • Get object from AWS S3 as a stream
  • Excel - Autoshape get it's name from cell (value)
  • Cross-Platform Protobuf Serialization
  • Validaiting emails with Net.Mail MailAddress
  • Statically linking a C++ library to a C# process using CLI or any other way
  • Do I've to free mysql result after storing it?
  • Numpy divide by zero. Why?