How to solve invalid data format?

Hi Team

I am debugging my client side and back end, while doing so i am getting “0
:
{productId: 10, productName: ‘Golf T-Shirt’, productPrice: 200, productImage: ‘img/wishlist-img/SecondWishlist.jpg’, quantity: 1}
length
:
1
[[Prototype]]
:
Array(0)
(index):1188 Error adding item to the wishlist: Invalid data format”

How do i resolve this issue?

// back end

<?php
// Enable error reporting for debugging purposes
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the raw JSON data from the request
    $json = file_get_contents('php://input');
    $wishlistData = json_decode($json, true);

    if ($wishlistData !== null && is_array($wishlistData)) {
        // Check if the wishlist key exists
        if (isset($wishlistData['wishlist']) && is_array($wishlistData['wishlist'])) {
            $wishlistItems = $wishlistData['wishlist'];

            // Database connection parameters
            $hostname = 'localhost';
            $username = 'username';
            $password = 'password';
            $database = '***';

            try {
                // Create a PDO connection to the database
                $pdo = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                // You need to adapt this part to your database schema
                // Assuming you have a 'wishlist' table with fields: id, user_id, product_id, product_name, product_price
                // Here, we'll use prepared statements to insert wishlist items
                $userId = 1; // Replace with your actual user_id retrieval logic

                $stmt = $pdo->prepare("INSERT INTO wishlist (user_id, product_id, product_name, product_image, product_price) VALUES (:user_id, :product_id, :product_name, :product_image, :product_price)");

                $success = true;

                foreach ($wishlistItems as $item) {
                    $productId = $item['product_id'];
                    $productName = $item['product_name'];
                    $productImage = $item['product_image'];
                    $productPrice = $item['product_price'];

                    // Bind parameters
                    $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
                    $stmt->bindParam(':product_id', $productId, PDO::PARAM_INT);
                    $stmt->bindParam(':product_name', $productName, PDO::PARAM_STR);
                    $stmt->bindParam(':product_image', $productImage, PDO::PARAM_STR);
                    $stmt->bindParam(':product_price', $productPrice, PDO::PARAM_STR);

                    if (!$stmt->execute()) {
                        // Error occurred while adding the item to the database
                        $success = false;
                        break;
                    }
                }

                // Close the PDO connection
                $stmt = null;
                $pdo = null;

                if ($success) {
                    // Return a success JSON response
                    $response = ['success' => true];
                } else {
                    // Return a failure JSON response
                    $response = ['success' => false, 'message' => 'Error adding item to the database'];
                }

                header('Content-Type: application/json');
                echo json_encode($response);
            } catch (PDOException $e) {
                // Handle any database connection or query errors
                $response = ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
                header('Content-Type: application/json');
                echo json_encode($response);
            }
        } else {
            // Handle invalid data format
            $response = ['success' => false, 'message' => 'Invalid data format'];
            header('Content-Type: application/json');
            echo json_encode($response);
        }
    } else {
        // Handle empty or invalid JSON data
        $response = ['success' => false, 'message' => 'Invalid JSON data received'];
        header('Content-Type: application/json');
        echo json_encode($response);
    }
}
?>
<script>
var loggedIn = false; // Initialize loggedIn as false by default

// Load wishlist items from session storage or initialize an empty array
var wishlistItems = JSON.parse(sessionStorage.getItem('wishlist')) || [];

$(document).ready(function() {
    // Function to update the wishlist badge
    function updateWishlistBadge() {
        var totalQuantity = wishlistItems.reduce((acc, item) => acc + item.quantity, 0);
        $('#wishlist-badge').text(totalQuantity);
    }
        $('.add-to-wishlist-btn').click(function() {
    var productId = $(this).data('product-id');
    var productName = $(this).data('product-name');
    var productPrice = $(this).data('product-price');
    var productImage = $(this).data('product-image');

    // Construct the wishlist item
    var wishlistItem = {
        productId: productId,
        productName: productName,
        productPrice: productPrice,
        productImage: productImage,
        quantity: 1
    };
console.log(wishlistItems);
    // Check if the item is already in the wishlist
    var existingItem = wishlistItems.find(item => item.productId === productId);

    if (existingItem) {
        // Item is already in the wishlist, increment its quantity
        existingItem.quantity++;
    } else {
        // Item is not in the wishlist, add it
        wishlistItems.push(wishlistItem);
    }

    updateWishlistBadge();
});

function addToWishlist(productId, productName, productPrice, productImage) {
    $.ajax({
        type: "POST",
        url: "add-to-wishlist.php",
        data: JSON.stringify({
            productId: productId,
            productName: productName,
            productPrice: productPrice,
            productImage: productImage
        }),
        contentType: "application/json",
        success: function(response) {
            if (response.success) {
                // Item added to the wishlist, now update the client-side wishlist and badge
                var existingItem = wishlistItems.find(item => item.productId === productId);
                if (existingItem) {
                    existingItem.quantity++;
                } else {
                    wishlistItems.push({
                        productId: productId,
                        productName: productName,
                        productPrice: productPrice,
                        productImage: productImage,
                        quantity: 1
                    });
                }
                updateWishlistBadge();
            } else {
                // Handle addition failure
                console.error("Error adding item to the wishlist: " + response.message);
            }
        },
        error: function(error) {
            // Handle AJAX error
            console.error("AJAX Error: " + JSON.stringify(error));
        }
    });
}



       // Attach click event handler to add-to-wishlist buttons
    $('.add-to-wishlist-btn').click(function() {
        var productId = $(this).data('product-id');
        var productName = $(this).data('product-name');
        var productPrice = $(this).data('product-price');
        var productImage = $(this).data('product-image');

        // Add the item to the wishlist via the new function
        addToWishlist(productId, productName, productPrice, productImage);
    });

    $('#wishlist-badge').click(function() {
        // Show the login modal
        $('#wishlistLoginModal').modal('show');
    });

    // When the login form is submitted
    $('#loginFormWishlist').submit(function(e) {
        e.preventDefault(); // Prevent the form submission
        var username = $('#username-wishlist').val();
        var password = $('#passwd').val();

        // Your login validation logic here
        // If login is successful, set loggedIn to true
        loggedIn = true;

        if (loggedIn) {
            // User is logged in, send the wishlist to the server
            $.ajax({
        type: "POST",
        url: "save-wishlist.php",
        data: JSON.stringify({ wishlist: wishlistItems }), // Convert to JSON string
        contentType: "application/json", // Set the content type to JSON
        success: function(response) {
            console.log("Success:", response);
        // Redirect to the wishlist page
        window.location.href = 'get-wishlist-product.php';
    },
    error: function(error) {
        // Handle the error if saving the wishlist fails
        console.error("Error saving wishlist: " + error);
    }
});

        }
    });
});

How will that if statement ever be true?

Also it looks like the backend is awaiting an array but you give an object

The true part of json_decode will return an associative array.

What you saying im saying incorrect values to the back end? How can improve this so can amend

I’m saying you’re checking for the existence of a ‘wishlist’ element of what you’re sending to the backend, and then not sending it.

You should know what you’re sending to your backend, and handle it as such, because you coded both ends of the communication, right?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.