1

Looking for an explanation rather than an answer here :)
I have this php script that is called with jquery's AJAX

$query = 'SELECT MONTH(PRSD#) as "Monat", CAST(AVG(GASVBR) as DECIMAL(10,3)) as "Gas", CAST(AVG(OLVBR) as DECIMAL(10, 3)) as "Öl", CAST(AVG(STROVBR) as DECIMAL(10,3)) as "Strom" FROM swind.gwenergy GROUP BY YEAR(PRSD#), MONTH(PRSD#) ORDER BY MONTH(PRSD#)';
    
    $dbReturn = $database->execute($query, array());
    
    $jsonArray = array();
    
    while ($row = db2_fetch_assoc($dbReturn)) {´
        echo json_encode($jsonArray);
    }

When I call in the JS side of things:

let parsedData = JSON.parse(jsonData);
I am returned with this:
{Monat: 2, Gas: '13750.607', Öl: '1447.432', Strom: '3901.051'}
How come the Monat value is not in quotes?
I thought that maybe because the $query in the php script was returning DECIMAL(10,3) but when I replace it with FLOOR(... the JSON.parse still wrapped the value in quotes.
Is this related to the $query response, or is this a JSON.parse action?
Look forward to hearing other ideas :) Thanks! -Boogabooga

4
  • 2
    What is stored in the database for Monat? Or is it just an Integer you put in? Commented Mar 23, 2022 at 10:16
  • thanks for the quick reply :) Monat is a textfield, but only numbers are being stored in it in the Y-mm-dd format, the other fields are also textfields in the MYSQL DB but only numbers are being stored in them too. The inputs on the html side are also textfields, with regex's to allow only numbers written in them Commented Mar 23, 2022 at 10:23
  • 1
    "Is this related to the $query response" - well find out, do a var_dump($row); and see what you get ... Commented Mar 23, 2022 at 11:40
  • @CBroe I var_dumped it and yes it indeed was returning my values as strings even though I was calling Decimal() on them, just curious as to why that was, because when I call the Month() it returned it as an integer Commented Mar 23, 2022 at 12:44

1 Answer 1

2

I've faced a similar problem. You can check the data type on PHP with gettype()

Note that since PHP 5.3.3, there is a flag for auto-convert numerical numbers when using json_encode.

echo json_encode( $jsonArray, JSON_NUMERIC_CHECK );

This should do the work for you.

Sign up to request clarification or add additional context in comments.

2 Comments

good answer! thumbs up
My current fix was to just parseINT() in my JS when pushing into my array BUT this is a great solution as it skips needing to do that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.