Jump to content

help with failure function


php_begins

Recommended Posts

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:

<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

<?
$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;  
   }
  
?>

Link to comment
https://forums.phpfreaks.com/topic/256074-help-with-failure-function/
Share on other sites

All you seem to need is an else{} for your if(mysql_num_rows($return) > 0) {} conditional to echo that no records were returned. How to integrate that into the existing AJAX code, I don't know.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.