简体   繁体   English

jQuery发布并获取表单数据

[英]jQuery Post and Get Form data

When a form is submitted, I can get its field values with $_POST. 提交表单后,我可以使用$ _POST获得其字段值。 However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if theres no any blank field. 但是,我试图使用基本的jQuery(不带任何插件)来检查任何字段是否为空白,我只想在没有任何空白字段的情况下发布表单内容。

I am trying following code, and I got the success with jQuery, but the only problem is that I am unable to post the form after checking with jQuery. 我正在尝试遵循代码,并且使用jQuery成功,但是唯一的问题是在使用jQuery检查后无法发布表单。 It does not get to the $_POST after the jQuery. jQuery之后不会到达$ _POST。

Also, how can I get the server response back in the jQuery (to check if there was any server error or not). 另外,如何获取jQuery中的服务器响应(以检查是否有服务器错误)。 Here's what I'm trying: 这是我正在尝试的:

HTML: HTML:

<form action="" id="basicform" method="post">
    <p><label>Name</label><input type="text" name="name" /></p>
    <p><label>Email</label><input type="text" name="email" /></p>  

    <input type="submit" name="submit" value="Submit"/>
</form>

jQuery: jQuery的:

jQuery('form#basicform').submit(function() {
    //code
    var hasError = false;

    if(!hasError) {
            var formInput = jQuery(this).serialize();
            jQuery.post(jQuery(this).attr('action'),formInput, function(data){

            //this does not post data
            jQuery('form#basicform').slideUp("fast", function() {
                    //how to check if there was no server error.
                });
            });
        }               
    return false;


});

PHP: PHP:

if(isset($_POST['submit'])){
    $name = trim($_POST['name'];
    $email = trim($_POST['email'];  

    //no any error
    return true;
}

There are two ways of doing that 有两种方法可以做到这一点

Way 1: 方法1:

As per your implementation, you are using input[type="submit"] Its default behavior is to submit the form. 根据您的实现,您正在使用input[type="submit"]它的默认行为是提交表单。 So if you want to do your validation prior to form submission, you must preventDefault() its behaviour 因此,如果要在提交表单之前进行验证,则必须preventDefault()的行为

    jQuery('form#basicform').submit(function(e) {
        //code
e.preventDefault();
        var hasError = false;

        if(!hasError) {
                var formInput = jQuery(this).serialize();
                jQuery.post(jQuery(this).attr('action'),formInput, function(data){

                //this does not post data
                jQuery('form#basicform').slideUp("fast", function() {
                        //how to check if there was no server error.
                    });
                });
            }        
$(this).submit();       
        return false;


    });

Way 2: 方式2:

Or simply replace your submit button with simple button, and submit your form manually. 或者只需将您的提交按钮替换为简单按钮,然后手动提交表单。 With $("yourFormSelector").submit(); 使用$("yourFormSelector").submit();

Change your submit button to simple button 将您的提交按钮更改为简单按钮

ie Change 即改变

<input type="submit" name="submit" value="Submit"/>

To

<input id="frmSubmit" type="button" name="submit" value="Submit"/>

And your jQuery code will be 而且您的jQuery代码将是

jQuery('input#frmSubmit').on('click',function(e) {
        //code
        var hasError = false;

        if(!hasError) {
                var formInput = jQuery(this).serialize();
                jQuery.post(jQuery(this).attr('action'),formInput, function(data){

                //this does not post data
                jQuery('form#basicform').slideUp("fast", function() {
                        //how to check if there was no server error.
                    });
                });
            }        
$("form#basicform").submit();       
        return false;


    });

To get the response from the server, you have to echo your response. 要从服务器获取响应,您必须echo您的响应。

Suppose, if all the variables are set, then echo 1; 假设,如果所有变量都已设置,则echo 1;否则, echo 1; else echo 0 . 否则echo 0

   if(isset($_POST['submit'])){
        $name = trim($_POST['name'];
        $email = trim($_POST['email'];  
        echo 1;
    } else {
        echo 0;
    }

And in your success callback function of $.post() handle it like $.post()成功回调函数中,它像

jQuery.post(jQuery(this).attr('action'),formInput, function(data){
                //this does not post data
                jQuery('form#basicform').slideUp("fast",{err:data}, function(e) {
                        if(e.data.err==1){
                             alert("no error");
                        } else {
                             alert("error are there");
                    });
                });

You could return something like {"error": "1"} or {"error": "0"} from the server instead (meaning, put something more readable into a JSON response). 您可以从服务器返回类似{"error": "1"}{"error": "0"}的内容(这意味着将更易读的内容放入JSON响应中)。 This makes the check easier since you have something in data . 因为您有data这使检查变得容易。

PHP: PHP:

if(isset($_POST['submit'])){
    $name = trim($_POST['name'];
    $email = trim($_POST['email'];  

    //no any error
    return json_encode(array("error" => 0));
} else {
    return json_encode(array("error" => 1));
}

JavaScript: JavaScript:

jQuery('input#frmSubmit').submit(function(e) {
        //code
        var hasError = false;

        if(!hasError) {
                var formInput = jQuery(this).serialize();
                jQuery.post(jQuery(this).attr('action'),formInput, function(data){
                var myData = data;

                if(myDate.error == 1) {//or "1"
                //do something here
                } else {
                //do something else here when error = 0
                }

                });
            }        
$("form#basicform").submit();       
        return false;


    });

To be very specific to the question: 具体而言:

How can I get the server response back in the jQuery (to check if there was any server error or not). 我如何才能在jQuery中获取服务器响应(以检查是否有服务器错误)。 Here's what I'm trying: 这是我正在尝试的:

Sound like you're talking about Server-Side validation via jQuery-Ajax. 听起来您正在谈论通过jQuery-Ajax进行服务器端验证。

Well, then you need: 好吧,那么您需要:

  • Send JavaScript values of the variables to PHP 将变量的JavaScript值发送到PHP
  • Check if there any error occurred 检查是否发生任何错误
  • Send result back to JavaScript 将结果发送回JavaScript

So you're saying, 所以你说

However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if there's no any blank field. 但是,我试图使用基本的jQuery(不带任何插件)来检查任何字段是否为空白,我只想在没有任何空白字段的情况下发布表单内容。

JavaScript/jQuery code: JavaScript / jQuery代码:

Take a look at this example: 看一下这个例子:

<script>
$(function()) {
    $("#submit").click(function() {
        $.post('your_php_script.php', {
             //JS Var   //These are is going to be pushed into $_POST
             "name"   : $("#your_name_field").val(),
             "email"  : $("#your_email_f").val()
        }, function(respond) {
           try {
               //If this falls, then respond isn't JSON 
               var result = JSON.parse(respond);

               if ( result.success ) { alert('No errors. OK')  }
           } catch(e) {
               //So we got simple plain text (or even HTML) from server
               //This will be your error "message" 
               $("#some_div").html(respond);
           }
       });
   });
}
</script>

Well, not it's time to look at php one: 好吧,不是时候看一下PHP了:

<?php

/**
 * Since you're talking about error handling
 * we would keep error messages in some array
 */

$errors = array();

function add_error($msg){
  //@another readers 
  //s, please don't tell me that "global" keyword makes code hard to maintain
  global $errors;
  array_push($errors, $msg);
}

/**
 * Show errors if we have any
 * 
 */
function show_errs(){
   global $errors;
   if ( !empty($errors) ){

     foreach($errors as $error){
        print "<p><li>{$error}</li></p>";
     }
     //indicate that we do have some errors:
     return false;
   }
  //indicate somehow that we don't have errors
  return true;
}



function validate_name($name){
  if ( empty($name) ){
     add_error('Name is empty');   
  }

  //And so on... you can also check the length, regex and so on
  return true;
}


//Now we are going to send back to JavaScript via JSON 

if ( show_errs() ){
   //means no error occured

   $respond = array();
   $respond['success'] = true;
   //Now it's going to evaluate as valid JSON object in javaScript
   die( json_encode($respond) );

} //otherwise some errors will be displayed (as html)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM