用PHP手动发送帖子

时间:2014-04-05 11:09:09

标签: php ajax

我有一个表单,在通过ajax请求提交给服务器进行服务器端验证之前,将验证客户端。如果验证服务器端失败,则需要进行包含所有错误消息的回发。我有办法做到这一点吗?

例如:

if ((!empty($nameError) && (!empty($emailError)) {

    $_POST['nameError'] = $nameError;
    $_POST['emailError'] = $emailError;
    // send postback with values
}
else {

    echo 'No errors';
}

更新---------------------------------------------- -

以下是处理表单提交的javascript:

$(".button").click(function() {

            $(".error").hide();

            var name = $(":input.name").val();
            if ((name == "") || (name.length < 4)){

                $("label#nameErr").show();
                $(":input.name").focus();
                return false;
            }

            var email = $(":input.email").val();
            if (email == "") {

                $("label#emailErr").show();
                $(":input.email").focus();
                return false;
            }


            var phone = $(":input.phone").val();
            if (phone == "") {

                $("label#phoneErr").show();
                $(":input.phone").focus();
                return false;
            }

            var comment = $.trim($("#comments").val());
            if ((!comment) || (comment.length > 100)) {

                $("label#commentErr").show();
                $("#comments").focus();
                alert("hello");
                return false;
            }

            var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
            var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
            alert(info);

            jQuery.ajax({

                type:"post",
                dataType:"json",
                url: myAjax.ajaxurl,
                data: {action: 'submit_data', info: info},
                success: function(response) {
                    if (response.type == "success") {

                        alert("success");
                    }
                    else {

                        alert("fail");
                    }
                }
            });

            $(":input").val('');
            return false;


        });

这是ajax发布的php函数:

function submit_data() {

    $nameErr = $emailErr = $phoneErr = $commentErr = "";
    $full = explode("&", $_POST["info"]);
    $fname = explode(":", $full[0]);
    $name = $fname[1];
    $femail = explode(":", $full[1]);
    $email = $femail[1];
    $fphone = explode(":", $full[2]);
    $phone = $fphone[1];
    $fcomment = explode(":", $full[3]);
    $comment = $fcomment[1];

    if ((empty($name)) || (strlen($name) < 4)){

        $nameErr = "Please enter a name";
    }
    else if (!preg_match("/^[a-zA-Z ]*$/", $name)) {

        $nameErr = "Please ensure you have entered your name and surname";
    }


    if (empty($email)) {

        $emailErr = "Please enter an email address";
    }
    else if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) {

        $emailErr = "Please ensure you have entered a valid email address";
    }


    if (empty($phone)) {

        $phoneErr = "Please enter a phone number";
    }
    else if (!preg_match("/(?:\(?\+\d{2}\)?\s*)?\d+(?:[ -]*\d+)*$/",$phone)) {

        $phoneErr = "Please ensure you have entered a valid phone number";
    }


    if ((empty($nameErr)) && (empty($emailErr)) && (empty($phoneErr)) && (empty($commentErr))) {

        $conn = mysqli_connect("localhost", "John", "Change9", "plugindatadb");
        mysqli_query($conn, "INSERT INTO data (Name, Email, Phone, Comment) VALUES ('$name', '$email', '$phone', '$comment')");
    }
    else {

        // display error messages
    }

    die();
}

2 个答案:

答案 0 :(得分:0)

您的答案将分为两部分:

伪代码:

第1部分:PHP

if ($error) {
    $reply["status"]=false;
    $reply["message"]="Fail message"; //Here you have to put your own message, maybe use a variable from the validation you just did before this line: $reply["message"] = $fail_message.
}
else {    
    $reply["status"]=true;
    $reply["message"]="Success message"//$reply["message"] = $success_message;
}

echo json_encode($reply);//something like {"status":true, "message":"Success message"}

Part2 AJAX:修改你对此的ajax响应。

                success: function(response) {
                    if (response.status == true) {

                        alert("success: "+response.message);
                    }
                    else {

                        alert("fail: " + response.message);
                    }
                }

答案 1 :(得分:-1)

使用json ajax请求。如果存在错误,则显示错误消息。我通常会成功或失败。

$message='';
if ((!empty($nameError) && (!empty($emailError)) {

     $errorArray=array();
    $errorArray['nameError'] = $nameError;
    $errorArray['emailError'] = $emailError;
    // send postback with values
}
else {

    $message='No errors';
}

echo json_encode(array(
"message"=>$message,
"errors"=>$errorArray
));