Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

78
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda