Ad

October CMS - API Generator - How To Create And Update Data In Database

- 1 answer

I try to send data to the database using AJAX and plugin in October CMS called "API Generator".
I can't find in its documentation or in Google anything that will help me.

The code I have is this:

$data = [{'room_id': {{room.id}}, 'amount': amount, 'arrival': '2018-04-01', 'departure': '2018-04-03,', 'reservation_type': 'owner'}]

$.ajax({
  url: '/api/v1/booking/create',
  data: $data,
  type: "post"
})
.done(function() {
  console.log('Success')
})
.fail(function() {
  console.warn('Something went wrong');
});

I don't get any error, in fact, I get 'Success' message in console, but data is not added to the database.

What am I doing wrong? Please help.

Thanks.

Ad

Answer

Actually you are doing it little wrong [ You are firing Ajax request at wrong end-point] that Api Plugin is based on https://laravel.com/docs/5.6/controllers#resource-controllersResource Controller

So, To create an item you need to fire only POST request to Created Api-End Point. You don't need to send Array just send simple plain Object

Refactored your code ( this should work ):

// Plaing object no array
$data = {'room_id': {{room.id}}, 'amount': amount, 'arrival': '2018-04-01',
       'departure': '2018-04-03,', 'reservation_type': 'owner'};

$.ajax({
    url: '/api/v1/booking', // <- just your Api-End [no create/store]
    data: $data,
    type: "post" // <- this post request indicates that you want to create/insert
})
.done(function(response) {
    // this will always fire when status code is 200
    console.log('Success', response); 
})
.fail(function() {
    // when status code is not 200 this will execute
    console.warn('Something went wrong');
});

Why you get success although its not Creating Record ?

Because according to Resource Controller there is no method create in api generator controller so October CMS is treating /api/v1/booking/create [POST] request as 404 page not found and its serving [200] status code with 404 page not found as ajax response.

And 404 page is having 200 status code so it fall in to success category and Ajax thinks it's a successful request and prints success message in console.

if any doubts please comment.

Ad
source: stackoverflow.com
Ad