CasualCoder3 CasualCoder3 - 2 months ago 8
Ajax Question

Is there a way to send a form data that has integers and strings?

Often when sending a forms using ajax and jQuery, the method

$(this).serialize()
or
$(this).serializeArray()
is used to transform the form into a JSON object. The problem is that all the values in the JSON are of type string.I have a form with inputs that have numbers:

<label for="name">name:</label>
<input class="w-input input" id="name" name="name" placeholder="Enter your name" type="text" required>

<label for="age">Age</label>
<input class=input" id="age" name="age" placeholder="Enter your age" type="number" required>


is there a way to still transform the form into a JSON but keep the types as it is required in the form, meaning still having my input that suppose to be numbers be numbers in the JSON.

Answer

If you want this behavior please use the following custom code:

JS

function serialize(form_id) {
    var inputs = document.getElementById(form_id).getElementsByTagName("input");
    var result = []
    for (var i = 0; i < inputs.length; i++) {
        var value = inputs[i].type == "number" ? inputs[i].value * 1 : inputs[i].type;

        var obj = {
            "value": value
        };
        if (inputs[i].name)
            obj["name"] = inputs[i].name;
        result.push(obj);
    }
    return result;
}

and the same HTML code:

<form id="myform" name="myform">
    <label for="name">name:</label>
    <input class="w-input input" id="name" name="name" placeholder="Enter your name" value="Amr" type="text" required>

    <label for="age">Age</label>
    <input class="input" id="age" name="age" placeholder="Enter your age" value="19" type="number" required>
</form>

and test using:

serialize("myform");