Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX POST sends numbers as string

I my AJAX POST request is sending my numeric data to my server as string for some reason... Here are my data and the AJAX request:

var data = {
        projectId: $("#projectId").val(),
        startDate: $("#startDate").val(),
        endDate: $("#endDate").val(),
        num_auto_tests: Number($("#num_auto_tests").val()),
        num_manual_tests: Number($("#num_manual_tests").val()),
        num_passed_tests: Number($("#num_passed_tests").val()),
        num_failed_tests: Number($("#num_failed_tests").val()),
        num_unran_tests: Number($("#num_unran_tests").val()),
        test: 3
    };

AJAX query:

$.ajax({
        type: "POST",
        dataType: "json",
        url: "/addreport/+ data.projectId",
        data: data,
        success: function() {
            console.log('success');
        }
    });

console.log(typeof(data.num_auto_tests)); //returns `number`

The server side returns:

{ projectId: 'FDIC-88445',
  startDate: '',
  endDate: '',
  num_auto_tests: '3',
  num_manual_tests: '3',
  num_passed_tests: '3',
  num_failed_tests: '3',
  num_unran_tests: '3',
  test: '3' } 

As you can see, the values that should be numeric are all strings on the server side...

Does anyone know what's going on?

Thanks in advance!

like image 782
Trung Tran Avatar asked Dec 24 '22 11:12

Trung Tran


2 Answers

I used JSON.stringify to solve this. PFB my ajax call:

var settings = {
  "url": "http://localhost:12345/docker/scale",
  "type": "POST",
  "headers": {
    "Content-Type": "application/json"
  },
  "data": JSON.stringify({ "scale": { "desired-instances": 123 } })
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

By doing this value was passed as an integer only thus no change required in the server-side code.

like image 198
vaibhavatul47 Avatar answered Jan 08 '23 00:01

vaibhavatul47


Your server receives the post in HTTP protocol, it is no wonder your server-side receives a string, as the operation you are executing is not type-secure. This is actually the expected behavior and if you want the elements to become numeric, then convert the parameters to numbers, the exact methodology depends on the server-side language/framework you are using.

EDIT: You can do two things to solve your issue:

  1. You can create a numeric handler/converter, like this:

    function detectNumeric(obj) { for (var index in obj) { if (!isNaN(obj[index])) { obj[index] = Number(obj[index]); } else if (typeof obj === "object") { detectNumeric(obj[index]); } } }

and call this function for any object you want to handle in such a way, or

  1. Pass the parameters as JSON and decode on server.

var my_object = {

  position: 1,
  id: "500",
  text: "hello world",
  greeting: "100, good day to you",
  book: "nineteen eighty four"

};


// iterates over an object's properties 
// and converts numbers as strings to numbers
function detectNumeric(obj) {
  for (var index in obj) {
    // if object property value *is* a number, like 1 or "500"
    if (!isNaN(obj[index])) {
      // convert it to 1 or 500
      obj[index] = Number(obj[index]);
    }
    // to do: explain what this does
    // else if (typeof obj === "object") {
    //  detectNumeric(obj[index]);
    // }
  }

  console.log(my_object)
}

// call function
detectNumeric(my_object);
like image 23
Lajos Arpad Avatar answered Jan 08 '23 00:01

Lajos Arpad