2012-11-19 102 views
3

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

$('#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; 
}); 

回答

6

之前的数据插入到数据库中使用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); 
} 
+0

你能告诉我一个代码示例吗? –

+0

伟大的工作。谢谢。 –