Я новичок в jQuery, и я пытаюсь проверить форму. Я хочу искать с помощью ajax и php, если заголовок уже находится в базе данных. Приведенный мной код работает и возвращает 1, если заголовок уже находится в db и 0, если нет. После этого я хочу добавить класс в текстовое поле заголовка. В конце я ищу, если текстовое поле заголовка имеет этот класс, если true, остановите форму, иначе отправьте.jQuery - проверка формы AJAX
Мой скрипт продолжает отправлять форму, даже если 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; }
Вот 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>
РНР код, используемый в AJAX:
// 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'));
}
}
, что делает 'console.log (HTML)' шоу? вы проверили, что серверный скрипт работает правильно? –
Если вы используете 'console.log (html.toSource())' внутри функции 'success', что вы получаете? – EmCo
@MarcB 'console.log (html)' показывает мне '[object Object]' Сценарий на стороне сервера без ошибок. – sorinu26