简体   繁体   中英

Ajax GET request with data variables

I'm trying to do a GET request with ajax to a Laravel function. This request has the following parameters: $id, $date, $service_time. In the Laravel function I want to convert the date to a Carbon date. Is there a solution to convert the right java-script date format to this Carbon format? I only need the date not the time. When I use below code I get a Unix time-stamp and when I select 05-10-2017 I get the result 04-10-2017.

var date = document.getElementById("startdate").value;
var newDate = new Date(date);
newDate.format("mm/dd/yy");

One other question I send the parameters through a URL in ajax. Is there a better way to do this?

var base_url = "{{ url('/') }}";
        $.ajax({
            type: "GET",
            url : base_url+"/company/available/1/18-10-2017/30",
            //data: {id : 1, date: "2017/10/18", service_time: service_time},
            success : function(data){
                $.each($(data), function(key, value) {
                    if(value.availity == 1) {
                        console.log(value.availity);
                      $('#available').append($("<div class='beschikbaar-style'></div>").text(value.time));
                    }
              });
            }
        });
    });

This is the route that calls the function:

Route::get('company/available/{id}/{date}/{service_time}', 'AppointmentsController@get_available_times')->name('companies.getAvailableTimes');

This is the function that is called:

function get_available_times($company_id, $date, $service_time = false)
{
     // $company_id = 1; 
    //$date = "2017-10-18";
    // $service_time = 30;

     $day = new Carbon($date);

Try this

     $date = "2017-10-18";
     $newDate = Carbon::parse($date)->now()->format('Y-m-d H:i:s');
     dd($newDate); // 2017-10-05 15:52:17

您可以使用createFromFormat函数,如下所示:

$day = \Carbon\Carbon::createFromFormat('mm-dd-yy', $date);

I had same problem with sending javascript date to Laravel and it is because of timezone part of Date object.

Maybe this function can help to convert Date to SQL formated string. It's not best javascript but will help :)

function sqlDate (date) {
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  var d = date.getDate();
  var s = y.toString() + '-';
  if (m < 10) {
    s += '0' + m.toString() + '-';
  } else {
    s += m.toString() + '-';
  }
  if (d < 10) {
    s += '0' + d.toString();
  } else {
    s += d.toString();
  }
  return s;
}

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