weixin_33720452 2019-05-01 16:21 采纳率: 0%
浏览 16

Ajax发布表单元素

I need your help a bit.

I am trying to 'POST' form elements with ajax. When i get all elements by name i see the result on console of the browser and also it send the datas to databases. But the problem is. it sends checkbox values wrong. it always send "on" value even if i not checked.Select part is working corretly by the way.

Here is my form part

<div class="right-side" id="right-side-id">
  <form action="criterias.inc.php" id="ajax" method="POST" class="ajax">
    <br>
    <center>
      <h>Customize Your Experience</h>
    </center>
    <div class="right-side-options">
      People interested in Friendship<input type="checkbox" class="checkmark" name="friendshipcheck"><br>
      People interested in Practice<input type="checkbox" class="checkmark" name="practicecheck"><br><br>
      Subject of Conversation
      <select name="subjectName" class="select">
        <option value="science">Science</option>
        <option value="love">Love</option>
        <option value="depressive">Deppressive</option>
        <option value="anything">Anything</option>
      </select><br><br>
      Language
      <select name="languageName" class="select">
        <?php
          include('connection.php');
          $sql   = "SELECT* FROM languages";
          $query = mysqli_query($conn, $sql);
          while ($result = mysqli_fetch_assoc($query)) {
            $language = $result["language_name"];
            echo "<option>" . $language . "</option>";
          }
        ?>
      </select>
      <input type="submit" class="searchbutton" id="search-button-id" value="Search" onclick="showPartner();">
    </div>
  </form>
</div>

And here is my Javascript code.

$('form.ajax').on('submit',function(){
  var that = $(this),
    url=that.attr('action'),
    type = that.attr('method'),
    data = {};

  that.find('[name]').each(function(index, value){
    var that = $(this),
      name=that.attr('name'),
      value = that.val();

    data[name] = value;
  });

  $.ajax({
    url:url,
    type:type,
    data:data,
    success:function(response){
      console.log(response);
    }
  });
  return false;
});

  • 写回答

3条回答 默认 最新

  • 7*4 2019-05-01 16:42
    关注

    This is the default behaviour in jQuery. What you need to do is explicitly handle the checkbox values to determine if its checked or not. Change your ajax method as follows. We'll modify the loop so it checks the checkbox value:

    that.find('[name]').each(function(index, value){
       var that = $(this),
           name= that.attr('name'),
           value = that.val();
    
    
           if (that.attr('type') === 'checkbox') {
             data[name] = that.is(':checked') // this will set the value to true or false
           } else {
              data[name] = value;
           }
    
    });
    
    评论

报告相同问题?