SyntaxError: Unexpected token in JSON at position 576 at JSON.parse

Good morning everybody!
I’m new to the web development area and I’m having a hard time trying to display mysql data on the ionic html page…I’m getting the following error:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost/phpp/entra.php/", ok: false, …}
error: {error: SyntaxError: Unexpected token in JSON at position 576 at JSON.parse (<anonymous>) at XMLH…, text: "[{\"codigo\": \"25\",\"tituloEvento\": \"Aviso\",\"conteudo…\"07:46:56\",\"dataCriacao\": \"2021-07-09 19:47:09\"}]"}
headers: HttpHeaders
lazyInit: () => {…}
lazyUpdate: null
normalizedNames: Map(0) {}
__proto__: Object
message: "Http failure during parsing for http://localhost/phpp/entra.php/"
name: "HttpErrorResponse"

Any help is welcome to me.

?php
header(“Access-Control-Allow-Origin:*”);
header(“Content-Type: text/html; charset=utf-8”);
$host = “mysql:host=localhost;dbname=eventosonline”;
$usuario = “root”;
$senha = “”;
try {
$conexao = new PDO($host, $usuario, $senha);

$sql = $conexao->prepare('SELECT * FROM `eventos`');

    $sql->execute();

    $dados = "[";

    while($lista = $sql->fetch()){
        if ($dados != "[") {
            $dados .= ",";
        }
        $dados .= '{"codigo": "'.$lista["id-evento"].'",';
        $dados .= '"tituloEvento": "'.$lista["titulo"].'",';
        $dados .= '"conteudoEvento": "'.$lista["conteudo"].'",';
        $dados .= '"diaEvento": "'.$lista["dia"].'",';
        $dados .= '"termina": "'.$lista["termoDoEvento"].'",';
        $dados .= '"dataCriacao": "'.$lista["criadoEm"].'"}';
    }
    $dados .= "]";
    echo $dados;

} catch (Exception $ex) {
echo "erro ao listar: ". $ex->getMessage();
};


*HTML*

Eventos Criados ![](upload://syKx20enxACbxdDs8kgX10RAO5E.jpeg)
{{evento.tituloEvento}}
Dia {{evento.diaEvento}}
Fim {{evento.termina}}
{{evento.conteudoEvento}}
```

page.ts

import { AccessProviders } from '../providers/access-providers';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-evento-criado',
  templateUrl: './evento-criado.page.html',
  styleUrls: ['./evento-criado.page.scss'],
})
export class EventoCriadoPage implements OnInit {
eventos: any;
  constructor(public servidor: AccessProviders) {
    this.buscar();
  }
ngOnInit() {
  }
buscar(){
this.servidor.getPegar().subscribe(data => this.eventos = data,
  err => console.log(err));
  }
}

And this is the provider:

import {
  Injectable
} from '@angular/core';
import {
  HttpClient,
  HttpHeaders
} from '@angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
import {
  AlertController
} from '@ionic/angular';
import {
  map
} from 'rxjs/operators';

@Injectable()
export class AccessProviders {
  server: string = 'http://localhost/phpp/select.php/';
  server1: string = 'http://localhost/phpp/entra.php/';
  constructor(
      public http: HttpClient,
      public allertCrtl: AlertController,
  ) {}

  postDate(body, file) {

      let headers = new HttpHeaders({
          'Content-Type': 'application/json; charset=UTF-8'
      });
      let options = {
          headers: headers
      }
      return this.http.post(this.server + file, JSON.stringify(body),
          options).timeout(59000).map(res => res);

First, on the Ionic side, there is a bunch of pointless junk in postDate. You don’t need or want custom headers, manual stringifying, or a NOP map.

return this.http.post(this.server + file, body);

Angular’s HttpClient is smart enough to handle the wiring of body and sending the appropriate Content-Type header.

Now, onto the server. I despise PHP, so I can’t give you any concrete suggestions as to what library to use to produce JSON, but there must be several. Find one and use it. Don’t manually concoct JSON using string concatenation. You’ve probably got a failure to escape something or format something properly that is absolutely not worth spending a single second further investigating, because there will be another, and another, and another.

Secondly, it seems that your server process is lying. It’s returning JSON, but declaring that it’s returning HTML. That’s also going to be a problem eventually.

Finally, as a general rule, always do everything using the least amount of privilege needed to achieve the task. That means never give a middleware process like this root access to the database. Make a MySQL user that has the necessary access to the tables needed to do its job, but no more.

Is your echo response have
json_encode(response)
function?

Good morning everybody. Thanks for the help you gave me, but my problem was in the database (I changed columns in a table and left the previous records saved in other columns not changed). After updating, inserting new data or the same ones again and with the table already altered, the problem was solved.

A sexta, 16 de jul de 2021, 06:28, Mani0011 via Ionic Forum <ionicframework@discoursemail.com> escreveu:

Hate to burst your bubble, but I strongly doubt that.

What I think is actually happening is that your homegrown JSON production algorithm is buggy, and the bug is triggered by the presence of certain characters in the data. Especially if the data in that database can be modified by forces outside your control, if I’m right, you have a remote DoS bomb ticking away.

After changing the table I just re-insert the data into the database and it works fine so far. My JSON doesn’t have any more problems.

A sexta, 16 de jul de 2021, 20:41, Robert Coie via Ionic Forum <ionicframework@discoursemail.com> escreveu: