简体   繁体   中英

AJAX post value is received as empty in PHP

I'm trying to post values to another page and do some mysql operations but the values are posting as empty objects. This is my scripting part of the index.php file:

$(document).ready(function() {
    $("#picker").datepick();
    $('#picker').datepick('setDate', 'today');

    $('#submit').click(function() {
        var name = $("#name").val();
        event.preventDefault();

        $.ajax({
            type: "POST",
            url: "new_prob_submit.php", 
            data: { 
                'date': $('#picker').val(), 
                'name': $('#name').val() 
            },
            success: function()    {
                alert("success");
            }
        }); 
    });
});

This is the PHP page where my posted values should be handled, new_prob_submit.php:

$rep_date = $_POST['date'];
$date = date("yyyy-mm-dd",strtotime($rep_date));
$name = $_POST['name'];
$sql = mysql_query("SELECT * FROM infra.prob_report WHERE prob_rept_name = '$name'");
$rows = array();
while($row = mysql_fetch_array($sql)) {
    $nestedData=array(); 
    $nestedData[] = $row["rep_id"];
    $nestedData[] = $row["prob_rept_date"];
    $nestedData[] = $row["prob_equip_name"];
    $nestedData[] = $row["prob_rept_name"];
    $nestedData[] = $row["prob_desc"];
    $data[] = $nestedData;
}
echo json_encode($data);

Problem is you have not used

dataType:"json" in your ajax .

 $.ajax({
            type: "POST",
            url: "new_prob_submit.php", 
            //added type
            dataType:"json",
            data: { 
                'date': $('#picker').val(), 
                'name': $('#name').val() 
            },
            success: function()    {
                alert("success");
            }
        });

Please check Ajax

 $.ajax({
                type:"POST",
                url: "new_prob_submit.php", 
                data: { 
                    'date': $('#picker').val(), 
                    'name': $('#name').val() 
                },
                dataType: "json",
                success:function(data){
                     alert(data);
                }
            });

You are using type: 'POST' which is not correct, it must be method: 'POST' in your $.ajax object. make sure console.log($('#picker').val(), $('#name').val() ) getting values in console.

Read more here

Add this to you script processData: true, like

  $.ajax({url: "submit.php",
       data: values,
       method: 'POST',
       processData: true,
       success: function (data) {
       alert(data);}});

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