ajax - Manually sending a post in PHP

663

I have a form that will be validated client side before being submitted via an ajax request to the server for server-side validation. Should the validation fail server side then a postback will need to be made containing all the error messages. Is there some way I can do this?

For example:


UPDATE

213

Answer

--------

Here is the javascript that handles the submission of the form:

$(".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;


        });

And here is the php function that the ajax posts to:

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();
}
976

Answer

Solution:

Your answer will be in two parts:

Pseudo code:

Part1: 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: modify you ajax response to this.

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

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

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

Answer

Solution:

Use json ajax request. In case error exists show the error message. I generally put a flag for success or fail .

$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
));

People are also looking for solutions to the problem: php - Trying to send form data to my email

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.