Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

79
Views
AJAX Javscript - PHP

I learn MVC and make some AJAX interaction. So I've routes file with

'cart/addProductAjax' => 'cart/addProductAjax',

CartController with actionAddProductAjax:

<?php

class CartController
{

    public function actionIndex() {

    }

    public function actionAdd($productId) {

        Cart::addProduct($productId);

        $referer = '/';

        if (isset($_SERVER['HTTP_REFERER'])) {
            $referer = $_SERVER['HTTP_REFERER'];
        }
        header("Location: $referer");
    }

    public function actionAddProductAjax() {

        $productId = $_POST['productId'];

        print_r($_POST);
        exit;

        Cart::addProduct($productId);
        $itemsAmount = Cart::countItems();

        exit(json_encode($itemsAmount));

    }

}

And JS piece of code that send request and receive response from the server:

document.body.addEventListener('click', event => {
    if(event.target.classList.contains('add-to-cart')) {

        event.preventDefault();

        let productId = event.target.dataset.id;
        let response = fetch("/cart/addProductAjax/", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json;charset=utf-8'
            },
            body: JSON.stringify(productId),
        })
            .then(response => response.json())
            .then(response => console.log(response));
    }
});

And nothing works. I think there is an error somewhere in PHP method. What shoul I do to make it work?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!