Home » Php » javascript – Send Patch request from vuejs to PHP backend using AxiosAbstraction

javascript – Send Patch request from vuejs to PHP backend using AxiosAbstraction

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to send a PATCH request to change user (promotor) birthdate from frontend Vuejs to backend PHP. with my code below, the new date of birth doesnt get to the data base, and somehow the date of birth in the data base turns to null when i send the request.

here is my front end code:

      updateDob(){
        let newdob = `${this.dob} 00:00:00`;  
              // newdob will be like this > 1996-02-29 00:00:00
        this.$store.commit('updateRegistration', { key: 'dob', value: newdob });
        console.log('thats what changed    >>>>>>', newdob)
         window.AxiosAbstraction.request('PATCH', 'promotor/changeDob', { data: newdob }, { host: 'legacy' }).then((response) => {
         window.console.log('this is what we sent      >>>>>>>>>', newdob)
         window.console.log('helloooooooooo   rrrresspooooonse >>>>>>>>',response);
         }).catch((error) => {
           window.console.error(error);
           if(error.response.data && error.response.data.errors)
           {
             error.response.data.errors.forEach((error) => {
               alert(error.description);
             });
           }
         });
        this.edit= false;
      },

and here is the endpoint I wrote in PHP :

SimpleRouter::patch('promotor/changeDob', function($promotorID) {
  cors();
  global $promotor;
  $response = new \Response();

  $data = HTTP::data();
   $data->dob;
  $promotor->update([
    'dob' => $data->dob
  ]);
   call promotor update dob
   $promotor->update([
     'dobChanged' => $data->1
   ]);
  \Response::json([
    'success'   => false
  ]);

  \Response::json($response_obj->error());
});

on the database table:
-the date of birth data type is : datetime.
-the dobChanged data type is : tinyInt.

any idea what is wrong or can be done to modify the date of birth correctly?

Thanks!

How to&Answers:

This is because you are trying to update the database without converting the data received from the frontend. The date sent from the Vue is converted during the HTTP transfer onto a string. You should be able to fix the issue by converting the date of birth into an actual date.

SimpleRouter::patch('promotor/changeDob', function($promotorID) {
  cors();
  global $promotor;
  $response = new \Response();
  $data = HTTP::data();
  $dob_time = strtotime($data->dob);

  $dob = date('Y-m-d', $dob_time); // use your preferred format here

  $promotor->update([
    'dob' => $dob
  ]);
   call promotor update dob
   $promotor->update([
     'dobChanged' => $data->1
   ]);
  \Response::json([
    'success'   => false
  ]);

  \Response::json($response_obj->error());
});