简体   繁体   中英

How to fetch value of a drop-down and a text box after btn click?

I have a form wherein I have a drop down which is being populated from the database also I have an input box right beneath it. I want to fetch the value of both the fields via Ajax using jQuery and insert them into the database .

Problem: Value of the text field is getting inserted successfully but the value of drop down is not getting inserted.

I know I will have to fetch the value of the drop down separately and then add it to the data in ajax but I am not able to figure how to do the same.

NOTE: COULD THE DOWN VOTERS BE KIND ENOUGH TO TELL ME WHY I WAS DOWNVOTED SO THAT I COULD IMPROVE UPON THINGS.

sub_category_add.php

<form method="post">

          <select id="cat_sub_cat">     

          <?php
          $data=mysqli_query($con,"SELECT * FROM category");
          while($row=mysqli_fetch_array($data))
          {
              echo "<option value=".$row['cid'].">".$row['category']."</option>";  
          }

          ?>      

          </select><br><br>     

          <h3>Add Sub Categories</h3><br>    

          <input type="text" name="sub_cat"><br><br>
          <input type="submit" name="submit" value="Insert" id="sub_cat_btn"> 
 </form>

Ajax File:

$(document).on('click','#sub_cat_btn', function(event){
    event.preventDefault();

    $.ajax({
        url:"sub_cat_add_back.php",
        method:"post",
        data:$('form').serialize(),
        dataType:"html",
        success:function(strMsg){
            $("#cat_sub_msg").html(strMsg);

            }

        })

sub_cat_add_back.php

<?php

include "../includes/config.php";


$name=$_POST['sub_cat'];
$cid=$_POST['cat_sub_cat'];


$data=mysqli_query($con,"INSERT INTO subcategory (name,cid) VALUES ('$name','$cid')");
if($data=="true")
{
    echo "Successfully Inserted";   
}
else
{
    echo "Error";   
}


?>

你的问题是 select 标签没有 Name 属性

 <select id="cat_sub_cat" name="cat_sub_cat"> 

If you want to get values on click instead of form serialize. add id in input

 <input type="text" name="sub_cat" id="custom">

    $("#cat_sub_cat option:selected");
    $("#custom").val();

and if you want to do that with form serialize then add name in your select

<select id="cat_sub_cat" name="your_select_name">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM