-1

I want to send a variable to php file select.php using AJAX to populate a table based on an specific date, this date is on take from an input field.

On my AJAX script I have this for getting the value of the date once I click on a button, check if date is not empty string (if yes send a bootstrap alert to warn the user) and then try to use the POST to send variable to my select.php which fetch the table based on the date that should be arriving via POST


$(document).on('click', '.b-request', function(){  
        var fecha = $(".datetimepicker-input").val();
        if(fecha == "")
        {
            $("#msj-alerta").html('<div class="alert alert-danger alert-dismissible"><button type="button" class="close">×</button><b>Heeeeeey</b><br>Date can\'t be blank!</div>');
            $('.alert .close').on("click", function(e){
                $(this).parent().fadeTo(500, 0).slideUp(500);
             });
        }
        else
        {
            $.ajax({   
                url:"select.php", 
                method:"POST",  
                data:fecha,   
                success:function(data)
                {  
                    //alert("Date entered: "+ fecha);
                    $('#live_data').html(data);    
                }  
            }); 

        }

This is the PHP file select.php (header only):

f(isset($_POST["fecha"]))
{
    $my_fecha = $_POST["fecha"];
    $connect = mysqli_connect($servername, $username, $password, $dbname);  
     $output = '';  
    $sql = "SELECT id, name, type FROM ms_resources.exceptions_new WHERE fecha = '".$my_fecha."';";

When running both codes together I got the error:

Notice: Undefined variable: my_fecha 

Not sure why variable is not reaching php, any idea?

Thanks

1 Answers1

2

POST values are key/value pairs. You're sending a value, but not a key:

data:fecha

The name of this variable may matter in this context when using the value, but once the variable is resolved and the value is used the name is no longer important and PHP has no knowledge of it. You need to assign a key to the value. For example:

data: { fecha: fecha }

Then you use the key in PHP to get the value:

$_POST["fecha"]

(It's by coincidence alone that the key and the client-side variable are the same in this case. That's not necessary at all.)


Unrelated, but important, your server-side code is also wide open to SQL injection. To learn more about what that is and how to prevent it, this is a great place to start.

David
  • 208,112
  • 36
  • 198
  • 279