I have a form which has drop-down when I try to save the form to database using PHP
the other fields are storing in the database but the select drop-down menu is not storing in the database it throws the below error:
Notice: Undefined index: branch in D:xampphtdocsforminsert.php on line 8 Message Saved
I have the below code:
<!DOCTYPE html> <html> <head> <title></title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> </head> <body> <br /><br /> <div class="container" style="width:500px;"> <form id="submit_form"> <label>Name</label> <input type="text" name="name" id="name" class="form-control" /> <br /> <label>Select branch</label> <select name="branch" id="branch" class="form-control"> <option selected hidden value="">Select Branch</option> <option value="kalyan">kalyan</option> <option value="mysuru">mysuru</option> <option value="begur">begur</option> </select> <label>Message</label> <textarea name="message" id="message" class="form-control"></textarea> <br /> <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" /> <span id="error_message" class="text-danger"></span> <span id="success_message" class="text-success"></span> </form> </div> </body> </html> <script> $(document).ready(function(){ $('#submit').click(function(){ var name = $('#name').val(); var message = $('#message').val(); var branch = $('#branch').val(); if(name == '' || message == '' || branch == '') { $('#error_message').html("All Fields are required"); } else { $('#error_message').html(''); $.ajax({ url:"insert.php", method:"POST", data:{name:name, message:message}, success:function(data){ $("form").trigger("reset"); $('#success_message').fadeIn().html(data); setTimeout(function(){ $('#success_message').fadeOut("Slow"); }, 2000); } }); } }); }); </script>
This is the PHP
code:
<?php //insert.php $connect = mysqli_connect("localhost", "root", "", "rcis"); if(isset($_POST["name"])) { $name = mysqli_real_escape_string($connect, $_POST["name"]); $message = mysqli_real_escape_string($connect, $_POST["message"]); $branch = mysqli_real_escape_string($connect, $_POST["branch"]); $sql = "INSERT INTO tbl_form(name, message,branch) VALUES ('".$name."', '".$message."', '".$branch."')"; if(mysqli_query($connect, $sql)) { echo "Message Saved"; } } ?>
This is the table:
What am I doing wrong?
Advertisement
Answer
You are not passing the branch
inside ajax function under data
data:{name:name, message:message},
Should be
data:{name:name, message:message, branch : branch},