开发者

NULL values jQuery Ajax from Seralize

I have a issue with Ajax From Submission and NULL values with php/mysql.

First I have a simple form.

<form mehod="post" action="">
  Name: <input type=text" name="person[name]" value="" /><br />
  Age: <input type="text开发者_StackOverflow" name="person[age]" value="" /><br />
  Salary: <input type="text" name="person[salary]" value="" />
  <a href="process.php" class="add-person">Submit</a>
</form>

Ok now ill post the data to php via ajax pretty simple

$(".add-person").live('click', function(eve){
    eve.preventDefault();
    var url = $(this).attr('href');
    var data = $(this).closest('form').serialize();
    $.ajax({
        global: false,
        type: "POST",
        url: url,
        data: data,
        dataType: 'json',
        success: function(msg){
            alert(msg);
        }
    }); 
})

Ok now here comes the problem. For this table the salary field is a float.

If I submit the form with a blank value for salary it is not null. So I am getting 0.00 being added to my data.

I can easy test for an empty string before adding the data but with lots of fields being like this it becomes bloated. i,e

if(empty($person['salary']):
  $person['salary'] = NULL;
endif;

Any idea why jQuery is making the values no null.

Hope you can help.


The value of an empty input field is an empty string, not null. That's just how it is.

If you have a lot of fields, stop writing each validation by hand and instead define a schema for them (an array is enough if you don't have a better way of defining constraints for your data), loop through it and validate each field according to it.

(And tbh anyone using endif has no business calling code "bloated"...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜