【问题标题】:server side validation for jQuery ajax submissionjQuery ajax 提交的服务器端验证
【发布时间】:2012-11-19 05:47:39
【问题描述】:

我正在使用 jQuery ajax 提交表单。我在另一个文件中编写了 php 代码,以将表单数据插入数据库表中。如何进行服务器端验证并显示相应的错误消息(例如,此字段不能为空)?我不知道如何解决这个问题。执行提交的jQuery函数如下

$('#form-add-button').click(function () {
   $.ajax({
      type: "POST",
      url: 'addemployee.php',
      data: $("#employee-form").serialize(),
      success: function (response) {
          showEmployeesData();
          initInputValues();
      },
      error: function (response) {
          alert('Error:' + response);
      }
  });
  return false;
});

【问题讨论】:

    标签: php jquery


    【解决方案1】:

    在将数据插入数据库之前,使用 php 验证数据,如果您在验证中遇到错误,您可以将错误消息编码为 json 并返回到 ajax 函数并显示消息

    AJAX FUNCTION
    
    $.ajax({
        type: 'post',
        url: 'lettersubscribe/subscribe',
        dataType: 'html',
        data:$("#subscribenewsletter").serialize(),
        success: function (html) {
            var result = jQuery.parseJSON(html);
            if(result.success == true){
                $("#subscribeBox").html('<span id="blacktext">TACK / THANKS FOR</span><span id="bluetext"> SIGNING UP!</span>');
            }else{
                $("#subscribe_result").html(result.error);
            }
        }
    });
    
    //PHP FUNCTION
    function subscribe(){
    
        $msg = array();
        $msg['success'] = TRUE;
    
        if($_POST['emailid']){
            // Validate email id
        }else{
            $msg['email'] ="Invalid Email";
            $msg['success'] = false;
        }
    
        echo json_encode($msg);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-08
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 1970-01-01
      相关资源
      最近更新 更多