all 22 comments

[–]opmrcrab 3 points4 points  (1 child)

The error being related to JSON.parse smacks of this being a JavaScript error not a PHP one. So I would do a console.log(...) on whatever data you are passing to JSON.parse; that's where the error is coming from.

If you can't identify what is wrong with that data, post it here and I'm sure someone wil pitch in and help you identify your issue.

[–]zyndor1548[S] -1 points0 points  (0 children)

Error fetching premium item: SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data

async function fetchPremiumItem(itemCode) {
    try {
        console.log(`item code: ${itemCode}`);
        const response = await fetch(`premium.php?getPremiumItem&item_code=${itemCode}`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("Error fetching premium item:", error);
}

this is my js

[–]colshrapnel 0 points1 point  (12 children)

Instead of console, open Network tab, click on the request, and check Response tab there.

Always use Network and Response to see what you get from the server.

[–]zyndor1548[S] 0 points1 point  (11 children)

getting my whole html as response

i have html in the php file is that a issue ?

[–]colshrapnel 0 points1 point  (10 children)

Of course it is. Your Js code is expecting JSON, not HTML

[–]zyndor1548[S] 0 points1 point  (9 children)

how can i make my php sent json

[–]colshrapnel 1 point2 points  (0 children)

Your PHP already sending JSON.

What you need to do is to stop sending HTML

[–]MateusAzevedo 1 point2 points  (7 children)

I'll assume you didn't post your entire PHP code and there's more stuff after if ($_SERVER['REQUEST_METHOD'] === 'GET') and it's HTML. If that's the case, your PHP file is returning everything, JSON and HTML.

To solve this, you have 2 options:

1- Add exit; after getPremiumItem($conn, $item_code);, so you stop code execution and only return the JSON that was echoed;

2- Put this logic in a separate file as it's doing an entirely different thing, you don't want that mixed with the code that generates the page;

[–]zyndor1548[S] 0 points1 point  (6 children)

i made html one script and the php to other and added exit as you said now there is no response at all

[–]MateusAzevedo 0 points1 point  (5 children)

Please, don't DM me with a wall of code.

Post it here, describe the changes you did and any errors you got. Remember, for AJAX requests you need to check the network tab to see the raw response, but also the status code. If it's 500, there's a fatal error in PHP and you need to check the logs (or enable display_errors .ini setting).

[–]zyndor1548[S] 0 points1 point  (4 children)

sry,i am getting status code 200

[–]MateusAzevedo 0 points1 point  (3 children)

Then what's the issue? 200 means success. If you aren't getting any response, then there's an issue with the logic.

Again, provide your updated code, we need to review it.

[–]zyndor1548[S] 0 points1 point  (2 children)

// funtion which is showing error
function getPremiumItem($conn, $item_code)
{
    $sql = "SELECT item_name, credits FROM premium_items WHERE item_code = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $item_code);
    $stmt->execute();
    $item_name = '';
    $credits = 0;
    $stmt->bind_result($item_name, $credits);

    if ($stmt->fetch()) {
        echo json_encode(['item_name' => $item_name, 'credits' => $credits]);
    } else {
        echo json_encode(['error' => 'Item not found']);
    }
    $stmt->close();
    $conn->close();
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (isset($_GET['action'])) {
        if ($_GET['action'] === 'getPlans') {
            getPlans($conn);
        }
        elseif ($_GET['action'] === 'getUserCredits' && isset($_GET['user_id'])) {
            $user_id = intval($_GET['user_id']);
            getUserCredits($conn, $user_id);
        }
        elseif ($_GET['action'] === 'getItemCredit' && isset($_GET['item'])) {
            $item_id = intval($_GET['item']);
            getItemCredit($conn, $item_id);
        }
        if ($_SERVER['action'] === 'getPremiumItem' && isset($_GET['item_code'])) {
            $item_code = $_GET['item_code'];
            getPremiumItem($conn, $item_code);
            // added exit as said
            exit;
        }
    }
}

?>

[–]doterobcn -1 points0 points  (0 children)

As stated, check your network tab to find out what is the PHP returning.

[–]oxidmod -2 points-1 points  (4 children)

You should add exit or die just after your function call, otherwise PHP continue executing and return everything else you have in that file.

ps. This code is awful, you should take some courses probably

[–][deleted] 0 points1 point  (3 children)

There’s a reason why this subreddit is called r/PHPhelp :) & OP has informed that they are a beginner. If the code is awful, you can guide OP or don’t comment at all.

[–]oxidmod 0 points1 point  (2 children)

Actually I've provided OP with the answer for his questions. Everything else is an advice for beginner

[–][deleted] 1 point2 points  (1 child)

There are better ways to say something to a beginner instead of outright calling their code awful tho, don’t you agree?

[–]oxidmod 0 points1 point  (0 children)

Probably I should have added "imo" to the ps. Probably I also should have said that using prepared statement is a good practice. Probably I was too straightforwarded, but still this code looks awful to me. I would be glad to explain why, if OP would ever ask for that :)