Pass HTML select value to PHP with ajax

4
(ESTO ESTÁ EN UN SCRIPT APARTE EN WORDPRESS, QUE LO RECONOCE PERO GENERA ERROR)

(function($){
var d= document.getElementById("lista").value;
$.post(document.location.pathname , { variable: d } );

} (jQuery))

<div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  (AQUI SE RECIBE EL VALUE DEL SELECT)
  <div>
    Seleccione periodo: 
    <select onchange="test()" name="name" id="lista">
        <option value="0" selected>Haga clic aquí</option>
        <option value="1" <?php if($_POST['name']=='1') echo 'selected="selected" ';?>> ENERO</option>
        <option value="2"  <?php if($_POST['name']=='2') echo 'selected="selected" ';?>>FEBRERO</option>
        <option value="3"  <?php if($_POST['name']=='3') echo 'selected="selected" ';?>>MARZO</option>
        <option value="4"  <?php if($_POST['name']=='4') echo 'selected="selected" ';?>>ABRIL</option>
        <option value="5"  <?php if($_POST['name']=='5') echo 'selected="selected" ';?>>MAYO</option>
        <option value="6"  <?php if($_POST['name']=='6') echo 'selected="selected" ';?>>JUNIO</option>
        <option value="7"  <?php if($_POST['name']=='7') echo 'selected="selected" ';?>>JULIO</option>
        <option value="8"  <?php if($_POST['name']=='8') echo 'selected="selected" ';?>>AGOSTO</option>
        <option value="9"  <?php if($_POST['name']=='9') echo 'selected="selected" ';?>>SEPTIEMBRE</option>
        <option value="10"  <?php if($_POST['name']=='10') echo 'selected="selected" ';?>>OCTUBRE</option>
        <option value="11"  <?php if($_POST['name']=='11') echo 'selected="selected" ';?>>NOVIEMBRE</option>
        <option value="12"  <?php if($_POST['name']=='12') echo 'selected="selected" ';?>>DICIEMBRE</option>
    </select>
    <input type="submit" name="submit" value="Consultar">
    <input type="button" onclick=" generateexcel('testTable') " value="Exportar a Excel">
  </div>
</form>
</div>

<?php
(AQUÍ DEBERÍA LLEGAR EL VALOR O LA VARIABLE DESDE AJAXXX)
if(isset($_POST['d']))
{  
  $name = $_POST['d'];
}
echo "No encontrado";
?>

What I want to do is take the value of select and pass it to PHP by ajax .

Error showing in the browser:

    
asked by reymagnus 22.02.2017 в 21:38
source

4 answers

2

There are several things that can improve in your code. Let's go to it:

I see that you want to use the $ .post for that you need jQuery, that error that you have to 'post' of undefined, means that the $ or jQuery is not defined. Remember that you should always add the link to jQuery:

https://code.jquery.com/jquery-3.1.1.min.js

Also to add events to the DOM you must make sure that the document is ready, you can use:

$('body').ready

What is inside of this .ready will be executed when the body is ready. Although I have not finished loading everything yet. or

$(window).load

What is inside the .load will be executed when the window has loaded, that is to say that the DOM may be ready but there are still images loading, this is executed until everything ends.

Now to make your code look cleaner I would make a function in js to select a select option. Something similar to:

function selectOption (value_to_select) {
 $('#select-id').val(value_to_select);
}

This way you would do:

$('body').ready(function () {
  var option_to_select = 2;

  selectOption(option_to_select);
});

And now when the DOM loads, you will have the option you want selected without mixing both the php and the html.

Now to send the data to the server, you can do several things, the easiest is to listen to the "submit" event of the form and execute the $ .ajax, since if you have require or email fields, the validation by the of the browser is going to be done before launching the "submit". It would be something like this:

$('#form-id').on('submit', function () {
  var valueToSend = $('#select-id').val();
  $.ajax({
    method: 'POST',
    url: 'myPage.php',
    data: {
       myVal: valueToSend
    },
    success: function (data) {
       console.log('Success: ' + data); // Este callback se lanza cuando la url 'myPage' responde con status 200.
    },
    error: function (data) {
       console.log('Error: ' + data); // Este callback que se lanzara si la url 'myPage.php' responde con status de error, e.g. 400, 404, 500, etc...
    }
  });
});

With this a call is sent $ .ajax to the page 'myPage.php', in that parameter you will put the page where you want to send the request. I leave the documentation: link

And to grab the value with PHP, you lock it with the variable $ _POST:

$_POST['myVal']; // OJO: cuando lo mandas en el data, se cacha con el nombre que le diste al parámetro: myVal: valueToSend.
    
answered by 25.02.2017 в 20:57
0

With JQuery it would be something like this:

var value = $("#lista").val();

$.ajax({
  url:'consulta.php?value='+value ,
  method: 'post',
  data: {},

});
    
answered by 22.02.2017 в 23:27
-1
 $(function(){
    $("#lista[name='name']").change(function () {
       var tu_variable_seleccionada = $(this).val();
       $.ajax({
         type: "POST",
         //Se omite la url por que es la misma página
         //url: "tu_url",
         //Variable envíada por ajax que recibe php
         data: {selected: tu_variable_seleccionada},
         success: function(data) {
           // Si todo sale bien, puedes agregar algo
         },
         error: function(data) {
           // Si fue error, recibes el error 
         }
    });
   });
  });
    
answered by 22.02.2017 в 23:30
-1
$("#cbo_cargos").change(function(){
   cargoValue=$(this).val();
});       
    
answered by 27.06.2017 в 19:35