如果使用ajax在表单中输入字段为空,如何显示错误

时间:2017-01-07 06:51:51

标签: javascript php jquery ajax forms

请帮忙。我现在已经被困在同一个问题上大约两个星期了。所以我从Github下载了高级登录主脚本并对其进行了一些定制。

Advanced login script

在创建Post类并尝试将ajax表单添加到" views / logged_in.php"之前,一切都很顺利。文件。表单验证错误消息已停止正确显示。在通过Ajax提交表单之前,我试图检查表单的输入字段是否为空。我不习惯这个脚本的设置方式。索引文件似乎调用了类。但是当我尝试添加ajax时,它会完全抛弃我。

有人可以告诉我在" views / Logged in.php"中添加一个简单的ajax表单到这个脚本的正确方法。如果输入字段为空,则在显示错误消息时显示文件?

P.S。我想显示PHP错误,而不是Javascript错误。在我的Post类中,我有一个错误和消息数组。

这是我的javascript ajax代码。

$('form.ajax').on('submit', function() {
var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};

that.find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();

    data[name] = value;
});

$.ajax({
    url: url,
    type: type,
    data: data,
    success: function(response) {
        $("form.ajax")[0].reset();
        console.log(response);
    }
});

return false;
});

website.com/views/logged_in.php

<form action="<?php echo BASE_URL; ?>contact.php"` method="post" class="ajax">
                    <div class="new_post_header">
                        <div class="new_post_avatar"><img src="img/profile_pic_1.png" style="width:40px; height:40px;" /></div>
                        <textarea name="post_text" id="message" class="new_post_textarea" placeholder="Give a tip"></textarea>
                    </div><!--.new_post_header-->

                    <div id="new_post_options">
                        <div class="icon-camera post_options_icon"></div>
                        <div class="icon-camcorder post_options_icon"></div>
                        <div class="icon-tag post_options_icon"></div>

                        <button name="submit" type="submit" class="post_post_button">Post</button>

                        <a class="privacy_post_option" id="post_privacy_toggle">
                            <div class="icon-earth-grid privacy_option_icon"></div>
                                Public
                            <div class="icon-more-arrow privacy_option_arrow"></div>
                        </a>
                    </div><!--#new_post_options-->
                </form><!--.ajax-->

website.com/classes/Post.php class

    <?php
class Post
{
    /**
     * @var object $db_connection The database connection
     */
    private $db_connection      = null;
    /**
     * @var string $logged_in_user_id the poster's id variable
     */
    public $logged_in_user_id   = null;
    /**
 * @var string $post_text The post text variable
 */
public $post_text           = "";
/**
 * @var array collection of error messages
 */
public  $errors             = array();
/**
 * @var array collection of success / neutral messages
 */
public  $messages           = array();

/**
 * Checks if database connection is opened and open it if not
 */
private function databaseConnection()
{
    // connection already opened
    if ($this->db_connection != null) {
        return true;
    } else {
        // create a database connection, using the constants from config/config.php
        try {
            // Generate a database connection, using the PDO connector
            // @see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
            // Also important: We include the charset, as leaving it out seems to be a security issue:
            // @see http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Connecting_to_MySQL says:
            // "Adding the charset to the DSN is very important for security reasons,
            // most examples you'll see around leave it out. MAKE SURE TO INCLUDE THE CHARSET!"
            $this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
            return true;
        // If an error is catched, database connection failed
        } catch (PDOException $e) {
            $this->errors[] = MESSAGE_DATABASE_ERROR;
            return false;
        }
    }
}

/**
 * creates a new post in the databse
 */
public function submitPost($logged_in_user_id, $post_text)
{
    // remove extra space on post text
    $post_text  = trim($post_text);

    // if the post text is empty
    if (empty($post_text)) {
        // show the errors
        $this->errors[] = MESSAGE_USERNAME_EMPTY;
    } else if ($this->databaseConnection()) {
        // write new post data into database
        $query_new_post_insert = $this->db_connection->prepare('INSERT INTO posts (poster_id, post_text, post_date) VALUES(:poster_id, :post_text, NOW())');
        $query_new_post_insert->bindValue(':poster_id', $logged_in_user_id, PDO::PARAM_INT);
        $query_new_post_insert->bindValue(':post_text', $post_text, PDO::PARAM_STR);
        $query_new_post_insert->execute();

        // id of new post
        $post_id = $this->db_connection->lastInsertId();

        // return the id of the last post to be added to database
        return $post_id;
    }
}

/**
 * creates a new post in the databse
 */
public function getPost($logged_in_user_id)
{
    // remove extra space on post text
    $post_text  = trim($post_text);

    if ($this->databaseConnection()) {
        // write new post into database
        $query_new_post_insert = $this->db_connection->prepare('INSERT INTO posts (post_text) VALUES(:post_text)');
        $query_new_post_insert->bindValue(':post_text', $post_text, PDO::PARAM_STR);
        $query_new_post_insert->execute();

        // id of new post
        $post_id = $this->db_connection->lastInsertId();

        // return the id of the new post
        return $post_id;
    }
}
}

website.com/contact.php

  <?php
// start the seesion so that you can access the $_SESSION variable
session_start();

// put the current logged in user's id in a variable
$logged_in_user_id = $_SESSION['user_id'];

// include the config
require_once('config/config.php');

// include the to-be-used language, english by default. feel free to translate your project and include something else
require_once('translations/en.php');

// load the post class
require_once('classes/Post.php');

// create the post object
$post = new Post(

);

if (isset($_POST['post_text'])) {
    // put the post text in a variable
    $post_text = $_POST['post_text'];

    // put the returned id from the submited post into a variable
    $post_id = $post->submitPost($logged_in_user_id, $post_text);
}
?>

2 个答案:

答案 0 :(得分:0)

您好我已经将您的提交按钮设为按钮并且onclick我已调用ajax功能

function test1()
{
var that = $('.ajax'),
    url = 'contact.php',
    type = 'POST',
    data = {};

that.find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();
if(value=='')
  {
    alert("please enter value of " +name);
    }
    data[name] = value;
});

$.ajax({
    url: url,
    type: type,
    data: data,
    success: function(response) {
      if(response==2)
        {
          alert("plaese enter text");
           or
           $('.error').html("plaese enter text");
          
          }
        if(response==1)
          {
        $("form.ajax")[0].reset();
            }
        console.log(response);
    }
});

return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <form  method="post"  class="ajax">
                    <div class="new_post_header">
                        <div class="new_post_avatar"><img src="img/profile_pic_1.png" style="width:40px; height:40px;" /></div>
                        <textarea name="post_text" id="message" class="new_post_textarea" placeholder="Give a tip"></textarea>
                    </div><!--.new_post_header-->

                    <div id="new_post_options">
                        <div class="icon-camera post_options_icon"></div>
                        <div class="icon-camcorder post_options_icon"></div>
                        <div class="icon-tag post_options_icon"></div>

                        <button  type="button" onclick="return test1();" class="post_post_button">Post</button>

                        <a class="privacy_post_option" id="post_privacy_toggle">
                            <div class="icon-earth-grid privacy_option_icon"></div>
                                Public
                            <div class="icon-more-arrow privacy_option_arrow"></div>
                        </a>
                    </div><!--#new_post_options-->
                </form><!--.ajax-->

答案 1 :(得分:0)

这样做的一种非常简单的方法是:

$('form.ajax').on('submit', function() {
    var empty = true;

    $("form.ajax input").each(function(){ // check each input
        var val = $(this).val();

        if(!$.trim(val) == ""){ // if the inputs are not empty
            empty = false; // allow ajax to be submitted
        }
    });

    if(empty){
        alert("Input is empty!"); // alert that an input is empty
    } else {
        // ajax goes here
    }

    return false; // prevent form post
});

注意:如果input包含 JUST 空格(无文字),此程序也有效。我建议在服务器端检查这一点,而不仅仅是客户端(因为这在(潜在的)攻击者中可编辑)浏览器。