I have been working on a shopping cart that the user can add/remove order items as they please and am returning an updated sub-total via a webservice using jQuery $.ajax
Here is how I am calling the webservice and setting the sub-total with the response.
//perform the ajax call
$.ajax({
url: p,
data: '{' + s + '}',
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#cartRow" + orderID).find(".subTotal").text(sTotal);
},
failure: function() {
//if the orer was not saved
//console.log('Error: Order not deleted');
}
});
The response I am getting seems perfectly fine:
{"d":"128.00"}
When I display the total on the page it displays as 128 rather than 128.00
I am fully sure it is something very simple and silly but I am so deep into it now I need someone with a fresh brain to help me out!!
Cheers 🙂
EDIT
I am also using $.ajaxSetup to set the correct contentType:
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data) {
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
});
I don’t see anywhere in this code where you access thedproperty of the response.Perhaps you mean to do this?
EDIT
Ok, I see the problem. You’re returning JSON but not defining a dataType in the
$.ajax()call. This means that jQuery sees yourapplication/jsonmimetype and interprets the response as JSON.128.00in JSON is a Number, not a String. However,"128.00"would be a String.In order to keep this working, You need to format the response before printing it (as others have suggested), or adjust your endpoint to return a valid JSON string.
Here’s my test to prove the solution
and test.php
Output
But when I change test.php to be this
The expected output is generated
Or, you could alternatively tell jQuery to treat the response as text by specifying a dataType parameter, for example
EDIT 2
Ok, after messing with this some more, I see what’s going on. The dataFilter handler you defined converts the response into JSON itself, and in this case, returns the string
128.00. However, jQuery still applies the intellgent-guessed dataType (which is JSON) to this value before sending it to the success handler.There are a multitude of ways to fix this, all of which depend on what other AJAX calls your application relies on this setup for. The quick-fix I applied in my test was to do this
But that may not work across the board for you