0

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?

kaoscify
  • 1,743
  • 7
  • 37
  • 74
  • If I got your point this may help http://stackoverflow.com/questions/4343596/parsing-json-file-with-php – Mohamed-Yousef Nov 26 '15 at 17:40
  • @Mohamed-Yousef Thanks for the link but I'm not using PHP. Bascially what I'm trying to do is that the database should return the 4 without "quotes". Like this: `{"rating":4}` – kaoscify Nov 26 '15 at 17:42
  • @mapr "The database" is server side, which has nothing to do with the data you're *sending*, and we couldn't help with your back end anyway since you provide zero information about it. – Dave Newton Nov 26 '15 at 17:48

1 Answers1

1

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)
})
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Thank you. This helps. I did not know that `values` are string, but knew the problem was somewhere on the client side. That's why I did not talk too much about the server side. – kaoscify Nov 26 '15 at 17:52