Reputation: 1763
I'm trying to store numeric data (integers) using a simple AJAX request:
function sendRating(rating) {
var userRating = rating.value;
$.ajax({
url: '/rating',
type: 'POST',
data: JSON.stringify({
"rating": userRating
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: (...)
});
}
This function is attached to buttons that have values (1,2,3,4,5). Because I'm using JSON.stringify
, the numbers get converted to a string when I check the records in the database. When I return the results in the database, they look like this: { "rating": "4" }
How can I avoid this?
Upvotes: 0
Views: 674
Reputation: 160251
Form values are strings. You're telling it to send a string.
JSON.stringify
doesn't convert numbers to strings (and running it in the console to test your assumptions would show that immediately).
There are many options, but here's one of them:
data: JSON.stringify({
rating: parseInt(userRating, 10)
})
Upvotes: 1