php_begins Posted January 30, 2012 Share Posted January 30, 2012 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; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/256074-help-with-failure-function/ Share on other sites More sharing options...
Pikachu2000 Posted January 30, 2012 Share Posted January 30, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/256074-help-with-failure-function/#findComment-1312780 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.