Ajax onclick button not populating a textbox

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • neelsfer
    Contributor
    • Oct 2010
    • 547

    Ajax onclick button not populating a textbox

    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?


    Code:
    HTML <td><input type="text" name="categories" id="categories" placeholder="categories" /></td>  
    (The textboxes below are populated from localstorage)   
     <td><input type="text" name="gender" id="gender" placeholder="gender" /></td>  
    <td><input type="text" name="age" id="age" placeholder="age" /></td>  
    <td><input type="text" name="racecode" id="racecode" placeholder="racecode" /></td> 
    
    <button id="but" font size="2" style ="color:red" >Add Category </button>
    Ajax
    Code:
    <script type="text/javascript">
    	  
    		$(document).ready(function(){
    			$("#but").click(function(){
    			var vargender = $("#gender").val();
    			var varracecode = $("#racecode").val();	
    			var varage = $("#age").val();	
    		$.ajax({
    			method: "post",
    			url: "category2.php",
    			data: {gender:vargender,racecode:varracecode,age:varage}
    		})
    		.done(function(data){
    			$("#categories").val(data);
    			
    		   });
    		  });
    	    });
    	 
    </script>
    Category2.php
    Code:
    <?php
    include("connection.php");
    $gender = $_POST['gender'];
    $racecode = $_POST['racecode'];
    $age = $_POST['age'];
    $query = ("SELECT * FROM tblcategories WHERE '$age' >= age_from AND '$age' <= age_to AND '$racecode' = racecode AND '$gender' = gender");
    $result = mysqli_query($connection, $query);
    $output = '';
    while($row = mysqli_fetch_assoc($result))
    {
     $output = $row["category_name"];
    
    echo($output);
    
    }
    ?>
  • neelsfer
    Contributor
    • Oct 2010
    • 547

    #2
    I seem to have fixed it by adding "e.preventDefau lt();" below button click. Hope this code helps somebody else also

    Comment

    Working...