Home > Software design >  Select field serialize not working via ajax
Select field serialize not working via ajax

Time:05-19

I have 3 select menus. I need to send the values over ajax as an array which I'm attempting to do using serialize(). The problem is that it's only sending 1 value instead of all 3. Any ideas what's going on?

var menu = $('select[name^="menu"]').serialize();
console.log(menu);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select name="menu[]">
  <option value="test">test</option>
</select>
<select name="menu[]">
  <option value="test1">test1</option>
</select>
<select name="menu[]">
  <option value="test2">test2</option>
</select>

var menu = $('select[name^="menu"]').serialize();
$.ajax({
    type:"POST",
    url:"www.example.com/submit.php",
    dataType: 'html',
    data: 'menudata=' menu '&name=bob',
    success: function(data) {
         alert(data);
    },error: function() {
       alert('error occurred')
    }
})

CodePudding user response:

The issue is with how you are sending the querystring to the server in your AJAX request, not with how serialize() is formatting the output.

To fix the issue remove the menudata= property name from the querystring you manually create:

data: menu   '&name=bob',
  • Related