B
B
bilyaev822021-07-22 19:34:26
AJAX
bilyaev82, 2021-07-22 19:34:26

Why is the AJAX request not coming?

Hello.
There is such a link

Стоимость:{$rsProduct['price']}
<a id="addCart_{$rsProduct['id']}" href="" alt = "добавить в корзину" onclick="addToCart({$rsProduct['id']});return false;";>Добавить в корзину</a>
By clicking on it, the addToCart() function is called.
function addToCart(itemId){
    console.log('js - addtocart()');
    $.ajax({
        type:'POST',
        async:true,
        url:"/www/cart/addtocart/" + itemId + "/",
        dataType:'json',
        success:function(data){
            if(data['success']){
                $('#cartCntItems').html(data['cntItems']);
                $('#addCart_' + itemId).hide();
                $('#removeCart_' + itemId).show();
            }
        },
        error: function(){
           console.log('failure');
          }
    })
}


Accordingly, the url key contains the page where the corresponding controller is written to add the product to the cart.

<?php
//контроллер работы с корзиной
include_once '../models/CategoriesModel.php';
include_once '../models/ProductsModel.php';

// добавление продуктв в корзину

function addtocartAction(){
    $itemId = isset($_GET['id']) ? intval($_GET['id']) : null;
    d($itemId);
    if(!$itemId) return false;
    $resData = array();
   
    //если значение не найдено,то добавляем

    if(isset($_SESSION['cart']) && array_search($itemId,$_SESSION['cart']) === false){
        $_SESSION['cart'][] = $itemId;
        $resData['cntItems'] = count($_SESSION['cart']);
        $resData['success'] = 1;
    }else{
        $resData['success'] = 0;
    }
    echo json_encode($resData);
}
?>


However, the request fails. Displays "failure";There are no errors in the console.
Index.php and htaccess are located in the www folder. I guess he doesn't like the url, but there is no 404 post error...
Request URL: http://myshop.local/www/cart/addtocart/12/
Request Method: POST
Status Code: 200 OK

Here is the cnc from htaccess:

RewriteEngine On

RewriteRule ^([a-z]+)/([a-z]+)/([0-9]+)$ index.php?controller=$1&action=$2&id=$3 [L,QSA]
RewriteRule ^([a-z]+)/([a-z]+)$ index.php?controller=$1&action=$2 [L,QSA]
RewriteRule ^([a-z]+)/([0-9]+)$ index.php?controller=$1&id=$2 [L,QSA]
RewriteRule ^([a-z]+)$ index.php?controller=$1 [L,QSA]

RewriteRule ^([a-z]+)/([a-z]+)/([0-9]+)/$ index.php?controller=$1&action=$2&id=$3 [L,QSA]
RewriteRule ^([a-z]+)/([a-z]+)/$ index.php?controller=$1&action=$2 [L,QSA]
RewriteRule ^([a-z]+)/([0-9]+)/$ index.php?controller=$1&id=$2 [L,QSA]
RewriteRule ^([a-z]+)/$ index.php?controller=$1 [L,QSA]

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question