How to give value to a data taken from a serializaArray and send it by AJAX?

0

I have a tabla called 'individuos' , it has basic data like (id, no.identificacion, nombre completo, depen_serial(INTEGER)) among others ...
(to avoid any 'wrong' comment, this is how it is stipulated :: ..)

depen_serial NOT a foreigner so the individual pueda que dependa de un numero de serie o no...

Having said that the problem is the following, in my form I have a input number (para digitar el serial) ... if I leave this field empty ajax performs a serializeArray(); but the php throws an error as it is taking a completely empty data and the base of data as you need to receive an integer will not read the empty field ....

From what I deduced was the following, if this individual is not going to have a serial, a data NULL must be sent for the database to read it and insert it correctly.

I hope I have understood and would appreciate your cooperation.

I leave the code to be a little clearer ... since the idea I had was to validate that if the serializeArray (); in the dependen_serial I take an empty value then add a null but I would not know how to send it by ajax...

$('#form_individuo').submit(function(event)
    {
        event.preventDefault();
        var data = $(this).serializeArray();

        if(data[8].value === '')
        {
            var convertir_a_null = data[8].value = null;
        }       
        else
        {
            $.ajax({
                url: 'insert_individuo',
                type: 'POST',
                data: data,
            })
            .done(function(answer)
            {
                var result = $.parseJSON(answer);

                if(result.answer == 'true')
                {
                    alert("SUCCESS");
                }
            })  
            .fail(function() {
                console.log("error");
            });     
        }
    });
});
    
asked by JDavid 07.03.2017 в 16:06
source

2 answers

1

I think that validation should be server-side, because on the client's side anyone could change the value quietly before sending, server side could do something like this:

<br>
$depen_serial = $_POST['depen_serial'] ?? ' ';
<br>
o sino 
<br>
$depen_serial = $_POST['depen_serial'] ?? null;
<br>
    
answered by 07.03.2017 в 18:34
1

If you want to do that validation from the client side, you can do it using this Free library called jquery.serializeJSON is the what else do I use.

Simple to use, let's say for your case:

You declare your Input Number:

<input type="text" name="anumb"   data-value-type="number"  value="1"/>

And then you just do the Submit with the Native Ajax:

var postVar = $('#myForm').serializeJSON();
$.ajax({
    url: 'post.php',
    data: postVar
}).done(function(data, result){
    console.log(data);
});

Good luck!

    
answered by 07.03.2017 в 20:35