获取从php到ajax成功响应的多个数据库查询

时间:2018-03-06 14:19:55

标签: javascript php jquery ajax laravel

我正在尝试将两个变量传递给我的ajax成功响应,以便我可以在一些html中使用它们来显示在页面上。正如你所看到的,我已经尝试将它们作为一个数组传递但它最终是空的。如何在我的ajax成功调用中传递两个php变量并访问它们?

//show datpicker calendar set function on select
$( "#datepicker" ).datepicker({
    numberOfMonths: 1,
    showButtonPanel: true,
    dateFormat: "yy-mm-dd",
    onSelect: getDate
});

function getDate(response){
    var selectedDate = $('#datepicker').val();
    var values = {'selectedDate': selectedDate };

    $.ajax({
        url: '/reservations/admin/dateRequest',
        type: 'POST',
        data: values,
        dataType: 'json',
        success: function (response) {

          .....use response data here....

        } //end success
    });//end ajax call

    return false;
}

我的PHP

public function differentDate() {
    //get selected date from datepicker selection   
    $selectedDate = $_POST['selectedDate'];
    //convert the selected date to carbon element
    $ConvertedSelectedDate =  new Carbon($selectedDate);
    //find day of week based on selection/conversion
    $dayOfWeek = $ConvertedSelectedDate->dayOfWeek;

    $times = ReservationTimeSlot::where('day_of_week', '=', $dayOfWeek)->get();
    $parties = Party::where('date', '=', $ConvertedSelectedDate)->get();

    $response = ['times' => $times, 'parties' => $parties];

    return $response;
}

所有这些都给了我空数组

 {"times":{},"parties":{}}

1 个答案:

答案 0 :(得分:0)

这应该有效

$.ajax({
 url: '/reservations/admin/dateRequest',
 type: 'POST',
 data: {
    'selectedDate': selectedDate,
    'otherVariable' : 1
 }
 dataType: 'json'
}).success(function(response){
   console.log(response.times);
   console.log(response.parties);
});

由于你确实标记了laravel,你可以在控制器中处理这样的请求。,

// Make sure you have this line in the begining of the file 
// use Illuminate\Support\Facades\Input;
public function differentDate() {


 $selectedDate = Input::get('selectedDate'); // No need to access $_POST
 $ConvertedSelectedDate =  new Carbon($selectedDate);
 $dayOfWeek = $ConvertedSelectedDate->dayOfWeek;

 $times = ReservationTimeSlot::where('day_of_week', '=', $dayOfWeek)->get();
 $parties = Party::where('date', '=', $ConvertedSelectedDate)->get();



return response()->json([
   'times' => $times,
   'parties' => $parties
]);