Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

80
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda