send select data by ajax

2

I have a form that when selecting a 'select' is sent automatically by AJAX, the call works well. Now when passing the variables of the form it says Notice: Undefined index:

In the index.php file I have

function enviar(theForm) {
 $.ajax({
   type: "POST",
   url: "a.php",
   data: $(this).serialize(),
   success: function(data) {
     $('#a').html(data);
   }
 });
 event.preventDefault();
};
<form role="form" name="nD" id="nD" method="post">
  <select name="d" onchange="enviar(this.form)">
    <option value="" disabled selected>Selecciona</option>
    <option value="1">Uno</option>
    <option value="2">Dos</option>
    <option value="3">Tres</option>
  </select>
</form>

<div id="a"></div>

In the a.php file I have

<h1>prueba</h1>
<?php echo $_POST['d'] ?>

Removing 'onchange="send (this.form)"' and placing a 'submit' works fine, but it is necessary that the form be sent when a 'select' option is selected. Thanks

    
asked by Johan Solano Contreras 30.09.2018 в 09:40
source

2 answers

2

You just have to replace:

$(this).serialize()

By:

$(theForm).serialize()

This way you make sure to reference the form and not another thing when serializing the data.

function enviar(theForm) {
 $.ajax({
   type: "POST",
   url: "a.php",
   data: $(theForm).serialize(),
   success: function(data) {
     $('#a').html(data);
   }
 });
 event.preventDefault();
};
<form role="form" name="nD" id="nD" method="post">
  <select name="d" onchange="enviar(this.form)">
    <option value="" disabled selected>Selecciona</option>
    <option value="1">Uno</option>
    <option value="2">Dos</option>
    <option value="3">Tres</option>
  </select>
</form>

<div id="a"></div>
    
answered by 30.09.2018 / 10:16
source
2

Another solution is to declare a change event with jquery to the select: option and change how you pass the serealize from $(this).serialize() to $("#nD").serialize() :

$("select[name='d']").on("change", () => {
  enviar();
});

function enviar() {

 $.ajax({
   type: "POST",
   url: "a.php",
   data: $("#nD").serialize(),
   success: function(data) {
     $('#a').html(data);
   }
 });
 
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form role="form" name="nD" id="nD" method="post">
  <select name="d">
    <option value="" disabled selected>Selecciona</option>
    <option value="1">Uno</option>
    <option value="2">Dos</option>
    <option value="3">Tres</option>
  </select>
</form>
    
answered by 30.09.2018 в 12:36