-1

I am using this javascript fetch code to get data from php

 async sendRequest(selectValue=this.selectValue){

    const fetchResponse = await fetch('/server/getLastWords.php?select='+selectValue);
    const fetchJSON = await fetchResponse.json();
    await console.log(fetchJSON);
}

this is php code which communicates with MYSQL and sends data to javascript

<?php 
 header('Content-Type: application/json');
include 'db/db_connection.php';
$mysqli = new mysqli('localhost','root','','worddb');
if(connectDB($mysqli)){
    $mysqliQuery = "SELECT * FROM wordlist ORDER BY wordIndex DESC LIMIT ?";
    $stmt = $mysqli->stmt_init();
    if(!$stmt->prepare($mysqliQuery)){
        print "Failed to prepare statement\n";
    }else{
        $stmt->bind_param("i", $_GET['select']);
        $stmt->execute();
        $result = $stmt->get_result();
        $resultJSON;
        foreach($result as $resultArray){
            $resultJSON = json_encode($resultArray);
            echo $resultJSON;
        }
    }
}
?>

and this php returns

{"wordIndex":94,"english":"seemingly","korean":"\uc678\uacac\uc0c1\uc73c\ub85c, 
\uac89\ubcf4\uae30\uc5d0\ub294","swedish":"till synes","synonyms":"apparently","example":"Seemingly, 
he borrowed the money from the bank"}
{"wordIndex":93,"english":"evade","korean":"\ud53c\ud558\ub2e4, 
\ud68c\ud53c\ud558\ub2e4","swedish":"undvika","synonyms":"elude, evoid","example":"He is using the 
same tactics of distract and evade as the Chancellor used during his speech"} 
{"wordIndex":92,"english":"eclipse","korean":"\uac00\ub9ac\ub2e4, \ube5b\uc744 
\uc783\uc74c","swedish":"f\u00f6rm\u00f6rka","synonyms":"blocking, beating","example":"Her work was 
in eclipse for most of the 20th century"}
{"wordIndex":91,"english":"impede","korean":"\uc9c0\uc5f0\uc2dc\ud0a4\ub2e4",
"swedish":"f\u00f6rhindra","synonyms":"delay, hinder","example":"This will impede learning, 
 essentially causing more problems than solutions"} 
 {"wordIndex":90,"english":"exposure","korean":"\uc704\ud5d8\uc5d0 \ub178\ucd9c, 
 \ud3ed\ub85c","swedish":"exponering","synonyms":"subjection, uncovering","example":"God knows you 
  probably saved my life, at least from exposure or pneumonia"}

I know it shows unexpected token { because php is returning multiple json object because

when I did echo just one json object it works fine.

        $resultJSON;
        foreach($result as $resultArray){
            $resultJSON =json_encode($resultArray);
        }
        echo($resultJSON);

but my php needs to send all items ,but I don't know how to do that because console shows unexpected token {}

I read this post before posting my question Why am I getting unexpected '}'? but solution in this post was to add semicolon, but I have semicolons in my code..

game lover
  • 114
  • 2
  • 7
  • Just use an array... – Andreas Jul 24 '20 at 13:50
  • Show us the php code where the json is created. It looks like you output json after json after json. First collect ALL the data, then turn it into json and output. – Michel Jul 24 '20 at 14:04
  • Why not just do `echo json_encode( $result );` instead of looping on each result (which creates the invalid json output problem)? – IncredibleHat Jul 24 '20 at 14:05
  • @Michel I did not create any json, php just picks data from MYSQL and just returning it to javascript as json format – game lover Jul 24 '20 at 14:12
  • @IncredibleHat I tried that too, but that returns {current_field: null field_count: null lengths: null num_rows: null type: null} – game lover Jul 24 '20 at 14:14
  • @Andreas excuse me, can you be more specific? Do you mean to create an array and then insert these objects to it? – game lover Jul 24 '20 at 14:14
  • What? `{current_field: null field_count: null lengths: null num_rows: null type: null}` ... where is that even in the code you have presented? Unless I'm blind. ... oh, sorry. I didn't mean literal `$result` (the pdo statement object)... my bad. – IncredibleHat Jul 24 '20 at 14:20
  • https://stackoverflow.com/questions/383631/json-encode-mysql-results – Andreas Jul 24 '20 at 15:36

2 Answers2

0

It goes wrong here:

$resultJSON;
foreach($result as $resultArray){
    $resultJSON = json_encode($resultArray);
    echo $resultJSON;
    }

You output:

echo json1;  
echo json2;
echo json3;

However, on the clientside the output is collected and treated as one json. So javascript will work with json1json2json3. And that's not a valid json.

If you don't have to do anything else then sending the result back

echo json_encode($result);

would do.

Michel
  • 4,076
  • 4
  • 34
  • 52
0

Transform your results in an array :

$resultJSON = array();
foreach($result as $resultArray){
    $resultJSON[] = $resultArray;
}

Then output the array :

echo json_encode($resultJSON);
iguypouf
  • 770
  • 4
  • 15