skip to Main Content

I’m busy with a Client Management System which also keeps track of Client Orders. I’ve set up a CRUD API that handles the back-end database data reading and writing, but when I try to POST the cart data to the database I get the following errors.

quote Error parsing JSON from response: SyntaxError: Unexpected token ‘<‘, " is not valid JSON

Receiving the following instead of valid JSON: <!– ErrorException: Undefined array key
"name" in file
C:UsersmjverOneDriveDocumentsCodingclient-apiroutesapi.php on
line 238

I’ve checked the input data into the $data["name"] array on the client-side and I cannot see any errors. I’ve checked for typos and spelling errors and all the and I’m hoping a few fresh pair of eyes could help out.

My code snippets on the front-end and back-end are as follows:

calling the API call function in api.js:

async sendOrder(){
            console.log(this.cart);
            
            const order = await APIController.CreateOrder(this.cart.name, this.cart.qty, this.cart.option, this.cart.price, this.orderNum, this.cart.fee, this.cart.date, this.id);
            if(order){
                store.dispatch('clearCart');
            }
        },

The API call in the api.js file:

CreateOrder: (name, qty, option, price, orderNo, fee, date, userId) => {
        let responseClone;
        const csrfToken = document.cookie.match(/XSRF-TOKEN=([^;]+)/)[1];
        if(
            name == "" ||
            qty == "" ||
            option == "" ||
            price == "" ||
            orderNo == "" ||
            date == "" ||
            userId == ""
        ) {
            return false;
        } else {

            return fetch(API_BASE + "/orders/create", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": csrfToken
                },
                body: JSON.stringify({ name, qty, option, price, orderNo, fee, date, userId })
            }).then((response) => {
                responseClone = response.clone();
                return response.json()
            })
            .then(data => {
                if(data.success){
                    alert("Order created successfully!")
                    return true;
                } else {
                    throw data.response.error;
                }
            }, (rejectionReason) => {
                console.log('Error parsing JSON from response: ', rejectionReason, responseClone);
                responseClone.text()
                .then((bodyText) => {
                    console.log('Receiving the following instead of valid JSON: ', bodyText);
                });
            }).catch(err => {
                alert(err);
            });
        }
    },

The php route in api.php file:

Route::post('/orders/create', function(Request $request){
    $data = $request->all();

    if(!Orders::where('orderNo', '=', $data['orderNo'])->exists()){
        $order = Orders::create([
            "name" => $data["name"],
            "qty" => $data["qty"],
            "option" => $data["option"],
            "orderNo" => $data["orderNo"],
            "userId" => $data["userId"],
            "price" => $data["price"],
            "fee" => $data["fee"],
            "date" => $data["date"],
        ]);

        if(empty($order->id)){
            return [
                "success" => false,
                "response" => [
                    "error" => "An unusual error has occured"
                ]
            ];
        } else {
            return [
                "success" => true,
                "response" => [
                    "order" => $order
                ]
            ];
        }
    } else {
        return [
            "success" => false,
            "response" => [
                "error" => "The inventory item already exists"
            ]
        ];
    }
});

My Orders Models file:

class Orders extends Model
{
    use HasFactory;

    protected $fillable = [
        'product',
        'qty',
        'option',
        'orderNo',
        'userId',
        'price',
        'fee',
        'date',
    ];

    public function product (){
        return $this->hasMany(Product::class);
    }
}

I would appreciate any help with this problem as I’ve been struggling with this for a while.

2

Answers


  1. try this in your php route in api.php file
    because in the query you are calling "name" column instead of "product"

     Route::post('/orders/create', function(Request $request){
        $data = $request->all();
    
        if(!Orders::where('orderNo', '=', $data['orderNo'])->exists()){
            $order = Orders::create([
                "product" => $data["name"],
                "qty" => $data["qty"],
                "option" => $data["option"],
                "orderNo" => $data["orderNo"],
                "userId" => $data["userId"],
                "price" => $data["price"],
                "fee" => $data["fee"],
                "date" => $data["date"],
            ]);
    
            if(empty($order->id)){
                return [
                    "success" => false,
                    "response" => [
                        "error" => "An unusual error has occured"
                    ]
                ];
            } else {
                return [
                    "success" => true,
                    "response" => [
                        "order" => $order
                    ]
                ];
            }
        } else {
            return [
                "success" => false,
                "response" => [
                    "error" => "The inventory item already exists"
                ]
            ];
        }
    });
    
    Login or Signup to reply.
  2. May I suggest to check this https://www.youtube.com/watch?v=YuL9nTBfyls&t=57s. Use dd() for check where does the error.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search