简体   繁体   中英

Pass value of multiple input fields in jQuery ajax?

I have multiple input fields, like

  <p>Filter by gender</p>
  <select class="filter-users">
     <option value="female">Female</option>
     <option value="male">Male</option>
   </select>
   <p>Filter by city</p>
      <input class="filter-users" type="text" name="city">

How to create GET request url with these one or all of these inputs

$.ajax({
  url: "/users/filter",
  type: "get", 
  data: { 
    city: city, 
    gender: gender
  },
  success: function(response) {

  }
});

How to make ajax request every time on of the filter inputs changed? For example send new request when on option change, or text input was entered? So what I am trying to explain is, there is no submit button. Requests needs to be made everytime one of these fields changes

You can use serializeArray , like this:

$.ajax({
  url: "/users/filter",
  type: "get", 
  data: $("form").serializeArray(),
  success: function(response) {
  }
});

Or you also can use serialize in case you don't need JSON but URL-encoded parameters.

for this "How to make ajax request every time on of the filter inputs changed"-

$('input.filter-users').on('change', function(){
   $.ajax({
     url: "/users/filter",
     type: "get", 
    data: $("form").serializeArray(),
    success: function(response) {
       }
   });
});

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