validate empty fields

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ajaxbegins
    New Member
    • Jan 2012
    • 5

    validate empty fields

    I have a form that populates data from database upon clicking on a fetch button and fills the other fields.
    It works fine fine with the exception that it should display an error message if it retrieves nothing. Can someone help me write the failure function.i.e if the form returns nothing when u click on the fetch button,it should display some kind of error message.

    Here is my code for form:
    Code:
    <input type="text" name="username" id="username"> 
    <div id="formResponse"></div>
    <button id="fetchFields">fetch</button>
    <label for="posts">Posts: </label>
    <input type="text" size="20" name="posts" id="posts">
    <label for="joindate">Joindate: </label>
    <input type="text" size="20" name="joindate" id="joindate">
    
    
    
    <p><input type="submit" value="Submit" name="submitBtn"></p>
    
    </fieldset>
    </form>
    
    <script type="text/javascript">
    $(document).ready(function() {
        function myrequest(e) {
            var name = $('#username').val();
            $.ajax({
                 method: "GET",
                url: "autofill.php",
    			dataType: 'json',
    			cache: false,
                data: {
                    username: name
                },
                success: function( responseObject ) {
                    alert('success');
                    $('#posts').val( responseObject.posts );
                    $('#joindate').val(responseObject.joindate);
                    /*
                    once you've gotten your ajax to work, then go through and replace these dummy vals with responseObject.whatever
                    */
                },
    			failure: function() 
    			{
                    alert('fail');
                }
            });
        }
        
        $('#fetchFields').click(function(e) {
            e.preventDefault();
            myrequest();
        });
    });
    here is my autofill.php
    Code:
    <?
    $name = stripslashes($_GET['username']);
    
    
       $return = mysql_query("SELECT posts,joindate FROM user WHERE username = '$name' LIMIT 1");
       if(mysql_num_rows($return) > 0)
       {
          $rows = mysql_fetch_assoc($return);
          $formattedData = json_encode($rows);
          echo	$formattedData;  
       }
      
    ?>
    [/quote]
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    rename failure to error.

    but that won’t help you since no content is not a failure (it is, so-to-speak, only an empty string). to properly deal with that issue you could use HTTP headers. there is for instance "HTTP\1.1 204 No Content" which you can intercept with the statusCode property.

    Comment

    Working...