简体   繁体   English

jQuery-AJAX表单验证

[英]jQuery - AJAX form validation

I am new to jQuery and I try to validate a form. 我是jQuery的新手,我尝试验证表单。 I want to search with ajax and php if title is already in database. 如果标题已经在数据库中,我想用ajax和php搜索。 The code below wrote by me works and returns 1 if title is already in db and 0 if not. 下面由我编写的代码可以正常工作,如果标题已经在db中,则返回1,否则返回0。 After this I want to add a class to title textfield. 之后,我想向标题文本字段添加一个类。 At the end I search if title textfield has that class, if true stop the form, else submit. 最后,我搜索标题文本字段是否具有该类,如果为true,则停止表单,否则提交。

My script keeps submitting the form even if php returns 1. What have I done wrong? 即使php返回1,我的脚本也会不断提交表单。我做错了什么?

// Process PHP file
$.ajax({
beforeSend: function()
{
    // Show loading
    $('#msg_search_load').removeAttr('style');
},
type: "GET",
url: "ajax_actions.php",
data: "action=search_category_add&title="+$("#category_title").val(),
dataType: "json",
cache: false,

success: function(html)
{
    console.log("Category already exists: "+html.category_found);

    if(html.category_found == 1) 
    {
        $('#msg_search_load').css({ 'display': 'none' });

        $('#msg_search_category').removeAttr('style');

        $("#category_title").addClass("already_exists");
    }
},

complete: function()
{
    // Hide loading
    $('#msg_search_load').css({ 'display': 'none' });
}

});




if($("#category_title").hasClass("already_exists")) { return false; }

Here is the HTML form 这是HTML表单

<form name="add_category" id="add_category" action="<?php echo $s_website_url; ?>/category_add.php" method="post">
<input type="hidden" name="action" value="add_category">

<table cellpadding="4" cellspacing="0">
<tr>
<td width="120">
<label for="category_title">Category title:</label>
</td>

<td>

<div class="content_msg" style="display: none;" id="msg_search_load"><img src="<?php echo $s_website_url; ?>/images/icons/loading.gif" class="content_msg_icon" alt="Warning"> Searching if category already exists.</div>

<div class="content_msg" style="display: none;" id="msg_search_category"><img src="<?php echo $s_website_url; ?>/images/icons/warning.png" class="content_msg_icon" alt="Warning"> Category already exists.</div>


<input type="text" name="category_title" id="category_title" class="form_textfield">

`<div class="content_count_chars" id="count_category_title"><span class="content_count_chars_green">100</span> characters remaining</div>
</td>
</tr>
</table>


<div align="center">

<!-- Fix Opera input focus bug -->
<input type="submit" value="Submit" style="display: none;" id="WorkaroundForOperaInputFocusBorderBug">
<!-- Fix Opera input focus bug -->


<input type="submit" value="Submit" class="form_submit">
</div>


</form>

The PHP code used in AJAX: AJAX中使用的PHP代码:

// If category already exists
if(isset($_GET['action']) && $_GET['action'] == 'search_category_add')
{   
    $search_category = mysql_query("SELECT `id` FROM `categories` WHERE `title` = '".clear_tags($_GET['title'])."'",$db) or die(mysql_error());

    if(mysql_num_rows($search_category) != 0)
    {
        echo json_encode(array('category_found' => '1'));
    }
    else
    {
        echo json_encode(array('category_found' => '0'));
    }
}

I solved the problem. 我解决了问题。 I had to add async: false to AJAX settings. 我必须添加async: false到AJAX设置。

AJAX is asynchronous, which basically means that it does not block the execution of the script (which is good, as your website does not freeze while things load). AJAX是异步的,这基本上意味着它不会阻止脚本的执行(这很好,因为您的网站在加载时不会冻结)。

The working code looks like this now: 现在的工作代码如下所示:

$.ajax({
       url: "ajax_actions.php",
       type: "GET",
       data: { action: "search_category_add", title: $("#category_title").val() },
       dataType: "json",
       async: false,
       success: function(result)
       {
            // console.log("Category already exists: "+result.category_found);

            if(result.category_found == 1) 
            {
                // console.log("Category already exists: Inside if");

                $('#msg_search_category').removeAttr('style');

                validationErrors++;
            }
        }
});





if(validationErrors > 0) { return false; }

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

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