duanfu2562 2012-11-19 05:47
浏览 55
已采纳

jQuery ajax提交的服务器端验证

I am using jQuery ajax to submit a form. I have written php code in a different file to insert the form-data into a database table. How can I do the server side validation and show corresponding error message (e.g. this field cannot be empty)? I have no idea about how to solve this problem. jQuery function that does the submission is as follows

$('#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;
});
  • 写回答

1条回答 默认 最新

  • doupaoyan6083 2012-11-19 05:52
    关注

    Before inserting the data into the database validate the data using php if you have errors in validation you can encode the error message as json and return back to the ajax function and show the message

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?