How can i send data attribute from html with ajax to some.php page, on click?

Viewed 52

In this case, i'm getting product id from database and placing it into data-idproduct:

<a class="cart" href="" data-idproduct="<?php echo $itemArtikal['id_product'] ?>">Add to Cart</a>

Clicking on that "Add to cart" button i'm getting that stored data-idproduct and trying to send it to cart-process.php page.

Here is my main.js code:

$(document).ready(function (){
$('.cart').click(function (e) {
    e.preventDefault();
    let dataIdArtikla = $(this).data('idproduct');

    $.ajax({
        method: "post",
        url: "models/cart-process.php",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            "idProd" : dataIdArtikla
        }),
        success: function (response) {
            alert(response);
        },
        error: function (xhr, textStatus) {
            alert("oh no: "+ " " + xhr.status+ " " +textStatus.responseText);
        }
    })
});

})

And here is the basic cart-process.php code:

$idProduct = $_POST['idProd'];

header('Content-type: application/json');
echo json_encode([
    'id_product' => $idProduct
]);

It always returns the error and the response of JSON is always null Response from 'Network' tab:

<br />
<b>Warning</b>:  Undefined array key "idProd" in <b>C:\xampp\htdocs\freshshop01\models\cart-process.php</b> on line <b>5</b><br />
{"id_artika":null}

Generally the idea behind this is adding the products into the cart when user click "Add to cart" button. I'm trying to pass the id of clicked product and after that in cart-process.php display whole product info with the same id.

I have no idea how to fix it, can anyone help?

Edit:

Here is my new cart-process.php file:

<?php
$idArtikla = $_POST['idProd'];

if(isset($idArtikla)) {

require_once "../config/connection.php";
session_start();

$_SESSION['idArtikla'] = $idArtikla;

$queryCart = $conn -> prepare('SELECT * FROM artikal WHERE id_artikal = :idArtikal');
$queryCart->bindParam(":idArtikal", $idArtikla);

try {
    $queryCart->execute();
    $resultCart = $queryCart->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $exception) {
    echo json_encode(['error' => $exception->getMessage()]);
}
header('Content-type: application/json');
echo json_encode($resultCart);

}

And new main.js file:

$(document).ready(function (){
$('.cart').click(function (e) {
    e.preventDefault();
    let dataIdArtikla = $(this).data('idartikla');

    $.ajax({
        method: "post",
        url: "models/cart-process.php",
        dataType: 'json',
        data: {
            "idProd" : dataIdArtikla
        },
        success: function (response) {
            console.log("Success message: " + response);
        },
        error: function (xhr, textStatus) {
            alert("oh no: "+ " " + xhr.status+ " " +textStatus.responseText);
        }
    })
});

})

Response now returns whole object, but it wont proceed to success. It enters error. I suspect there is something wrong with object to json conversion or vice versa, but not sure what exactly could be wrong here? Here is how response and request look like exactly:

Request

Response

Post is a little bit to long, i appriciate the help.

1 Answers

When passing data you have to add a key to your JSON. Instead of the contentType use dataType:'json' to tell jQuery what to expect.

$.ajax({
    method: "post",
    url: "models/cart-process.php",
    dataType: 'json',
    data: {'json':JSON.stringify({"idProd" : dataIdArtikla})},
    success: function (response) {
        alert(response);
    },
    error: function (xhr, textStatus) {
        alert("oh no: "+ " " + xhr.status+ " " +textStatus.responseText);
    }
})

And in the php you can access the element like so:

echo (json_decode($_POST['json'])->idProd);

A simpler way would be to just pass the data without serialization

$.ajax({
    method: "post",
    url: "models/cart-process.php",
    data: {"idProd" : dataIdArtikla},
    success: function (response) {
        alert(response);
    },
    error: function (xhr, textStatus) {
        alert("oh no: "+ " " + xhr.status+ " " +textStatus.responseText);
    }
})

Then you can access the idProd directly via $_POST:

echo ($_POST['idProd']);
Related