By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,988 Members | 1,074 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,988 IT Pros & Developers. It's quick & easy.

Ajax onclick button not populating a textbox

100+
P: 547
I have this Ajax with PHP that determines my value correctly from a php sql query, on my "test page".

When adding the code to my main page, the button adds the correct data for a half second, and then removes it, leaving the "categories" input textbox empty.

The rest of the page is populated onload from local storage, before i press this button to populate the "categories" textbox. Any suggestions please?


Expand|Select|Wrap|Line Numbers
  1. HTML <td><input type="text" name="categories" id="categories" placeholder="categories" /></td>  
  2. (The textboxes below are populated from localstorage)   
  3.  <td><input type="text" name="gender" id="gender" placeholder="gender" /></td>  
  4. <td><input type="text" name="age" id="age" placeholder="age" /></td>  
  5. <td><input type="text" name="racecode" id="racecode" placeholder="racecode" /></td> 
  6.  
  7. <button id="but" font size="2" style ="color:red" >Add Category </button>
Ajax
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.  
  3.         $(document).ready(function(){
  4.             $("#but").click(function(){
  5.             var vargender = $("#gender").val();
  6.             var varracecode = $("#racecode").val();    
  7.             var varage = $("#age").val();    
  8.         $.ajax({
  9.             method: "post",
  10.             url: "category2.php",
  11.             data: {gender:vargender,racecode:varracecode,age:varage}
  12.         })
  13.         .done(function(data){
  14.             $("#categories").val(data);
  15.  
  16.            });
  17.           });
  18.         });
  19.  
  20. </script>
Category2.php
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. include("connection.php");
  3. $gender = $_POST['gender'];
  4. $racecode = $_POST['racecode'];
  5. $age = $_POST['age'];
  6. $query = ("SELECT * FROM tblcategories WHERE '$age' >= age_from AND '$age' <= age_to AND '$racecode' = racecode AND '$gender' = gender");
  7. $result = mysqli_query($connection, $query);
  8. $output = '';
  9. while($row = mysqli_fetch_assoc($result))
  10. {
  11.  $output = $row["category_name"];
  12.  
  13. echo($output);
  14.  
  15. }
  16. ?>
Jul 6 '17 #1
Share this Question
Share on Google+
1 Reply


100+
P: 547
I seem to have fixed it by adding "e.preventDefault();" below button click. Hope this code helps somebody else also
Jul 6 '17 #2

Post your reply

Sign in to post your reply or Sign up for a free account.