dongmozhui3805 2013-07-18 17:14
浏览 61

在包含PHP的页面中进行jquery验证后无法使用PHP进行验证

Could someone please help me figure out how to get my form to submit to php after jquery validation.

I found a tutorial "Build a Neat HTML5 Powered Contact Form" and if I build the form so that it is one complete page with head and body it validates. However my site is designed so the header and footer are the same for all pages and I include different content in the centre for example:

[http://mysite/index.php?page=contact]

This is the JS script:

`$(function(){
        $("#refreshimg").click(function(){
            $.post('newsession.php');
            $("#captchaimage").load('image_req.php');
            return false;
        });

        $("#contact_form").validate({
            rules: {
                    name: {
                    required: true,
                    minlength: 2
                  },
                  //telephone, email & message rules removed

                captcha: {
                    required: true,
                    remote: "process.php"
                }
            },
            //messages removed

            errorContainer: $('#errors'),
            errorLabelContainer: $('#errors ul'),
            wrapper: 'li',

            var dataString = 'name='+ name + '&email=' + email + '&telephone=' + telephone + '&message=' + message;
              //alert (dataString);return false;
              submitHandler: function(form) {
              $(form).ajaxSubmit({
                type: "POST",
                url: "pages/processC.php",
                data: dataString,
                success: function() {
                  $('#contactForm').html("<div id='message'></div>");
                  $('#message').html("<h2>Contact Form Submitted!</h2>")
                  .append("<p>We will be in touch soon.</p>")
                  .hide()
                  .fadeIn(1500, function() {
                    $('#message').append("<img id='checkmark' src='images/check.png' />");
                  });
                }
              });
              }
            return false;

            onkeyup: false
        }); `

The tutorial I followed came with the following submitHandler:

` /*submitHandler: function() {
            alert("Correct captcha!");
        },
        success: function(label) {
            label.addClass("valid").text("Valid captcha!")
        },*/`

Which I commented out and the form submits when it is one complete page.

I found the above ajaxSubmit in another tutorial but when I click submit the it navigates to my index page.

Here is my PHP file:

` ?>

<?php
if( isset($_POST) ){
    //form validation vars
    $formok = true;
    $p_errors = array();

    //sumbission data
    $ipaddress = $_SERVER['REMOTE_ADDR'];
    $date = date('d/m/Y');
    $time = date('H:i:s');

    //form data
    $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $telephone = filter_var($_POST['telephone'], FILTER_SANITIZE_NUMBER_INT);
    $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
    $captcha = filter_var($_POST['captcha'], FILTER_SANITIZE_STRING);

    //validate form data

    //validate name is not empty
    if(empty($name)){
        $formok = false;
        $errors[] = "You have not entered a name";
    }   

    //validate telephone is numbers 
    if(empty($telephone)){
        $formok = true;
    }

    //validate email address is not empty
    if(empty($email)){
        $formok = false;
        $errors[] = "You have not entered an email address";
    //validate email address is valid
    }

    //validate message is not empty
    if(empty($message)){
        $formok = false;
        $errors[] = "You have not entered a message";
    }

    //validate captcha is not empty
    session_start();
    if(empty($captcha)){
        $formok = false;
        $errors[] = "Please answer captcha question";
    }
    elseif(strtoupper($_POST['captcha']) == $_SESSION['captcha_id'])
    {
    //Do your stuff
    unset ($_SESSION["captcha_id"]);
    }
    else
    {
    $formok = false;
    $errors[] = "Wrong code entered";
    }

    //send email if all is ok --REMOVED


    //what we need to return back to our form
    $returndata = array(
        'posted_form_data' => array(
            'name' => $name,
            'email' => $email,
            'telephone' => $telephone,
            'message' => $message
        ),
        'form_ok' => $formok,
        'errors' => $errors
    );

    //if this is not an ajax request
    if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
        //set session variables
        session_start();
        $_SESSION['cf_returndata'] = $returndata;

        //redirect back to form
        header('location: ' . $_SERVER['HTTP_REFERER']);
    }
}`  

I hope I have not put too much code but my knowledge of PHP and Jquery is very limited but I really need to solve this so any suggestions would be very much appreciated.

Thanks in advance, James

  • 写回答

1条回答 默认 最新

  • duandaoji3992 2013-07-18 17:20
    关注

    Don't try building your post body by hand. There is a lot of encoding issues that be be introduced using your method.

    Instead of:

    var dataString = 'name='+ name + '&email=' + email + '&telephone=' + telephone + '&message=' + message; 
    

    just

    var dataObj = {"name":name, "email":email, "telephone":telephone};
    

    then on your ajax call change

    data: dataString,
    

    to

    data: dataObj;
    

    This will dodge a lot of corner cases and encoding issues.

    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler