1

I am new to jQuery and I try to validate a form. I want to search with ajax and php if title is already in database. The code below wrote by me works and returns 1 if title is already in db and 0 if not. 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.

My script keeps submitting the form even if php returns 1. What have I done wrong?

// 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

<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:

// 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'));
    }
}
6
  • what does console.log(html) show? have you verified that the server-side script is working properly? Commented Mar 8, 2013 at 16:52
  • If you do a console.log(html.toSource()) inside the success function, what do you get? Commented Mar 8, 2013 at 16:54
  • @MarcB console.log(html) shows me [object Object] The server side script is errorless. Commented Mar 8, 2013 at 17:31
  • where are you handling the form submit event Commented Mar 8, 2013 at 17:54
  • Chances are you have a submit button in the form without a false return on the submit event, and you've probably attached the click handler to this function. What is this function bound to? A button? Any form event? Post your form code. Commented Mar 8, 2013 at 18:03

1 Answer 1

1

I solved the problem. I had to add async: false to AJAX settings.

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).

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; }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.