General Baguettson
General Baguettson

Reputation: 163

JSON parse error : unable to parse JSON string when trying to return error message

I am trying to return an error message for my react native register screen. The .php script called is :

<?php

include 'DBConfig.php';

// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
if ($con == false) {
  $ShitMSG = "Can't connect to database" ;
  $ShitJson = json_encode($ShitMSG);
  echo $ShitJson ;
}

// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);

// Populate User name from JSON $obj array and store into $name.
$name = $obj['name'];
// Populate User email from JSON $obj array and store into $email.
$email = $obj['email'];

//Checking Email is already exist or not using SQL query.
$CheckSQL = "SELECT * FROM UserRegistrationTable WHERE email='$email'";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)) {
  $EmailExistMSG = "L'E-mail est déja utilisé !";
  $EmailExistJson = json_encode($EmailExistMSG);
  echo $EmailExistJson ;
}
else {
  // Creating SQL query and insert the record into MySQL database table.
  $Sql_Query = "insert into UserRegistrationTable (name,email) values ('$name','$email')";
  if(mysqli_query($con,$Sql_Query)) {
    $MSG = 'Utilisateur enregistré !' ;
    $json = json_encode($MSG);
    echo $json ;
  }
  else {
    echo 'Réessayez';
  }
}
mysqli_close($con);

?>

When called, it receives a body looking like

body: JSON.stringify({
        name: UserName,
        email: UserEmail
      })

Consisting of inputs for my user's name and email. DBconfig.php is another PHP file where my db's ids are, to connect to it.

My script is launched by my react native app, from this function :

class LoginScreen extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      UserName: '',
      UserEmail: ''
    }
  }

  UserRegistrationFunction () {
    const { UserName } = this.state
    const { UserEmail } = this.state

    fetch('http://c2isante.fr/appsante/login.php', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: UserName,
        email: UserEmail
      })

    }).then((response) => response.json())
      .then((responseJson) => {
        Alert.alert(responseJson)
      }).catch((error) => {
        console.error(error)
      })
  }

  render () {
    return (
      <View style={styles.MainContainer}>
        <Text style={{ fontSize: 20, color: '#000', textAlign: 'center', marginBottom: 15 }}>User Registration Form</Text>
        <TextInput
          placeholder='Entrez votre nom'
          onChangeText={UserName => this.setState({...this.state, UserName})}
          underlineColorAndroid='transparent'
        />
        <TextInput
          placeholder='Entrez votre E-mail'
          onChangeText={UserEmail => this.setState({...this.state, UserEmail})}
          underlineColorAndroid='transparent'
        />
        <Button title="M'enregistrer" onPress={this.UserRegistrationFunction.bind(this)} color='#2196F3' />
      </View>
    )
  }
}

Upvotes: 3

Views: 2418

Answers (3)

Quentin
Quentin

Reputation: 944474

There are three possible outcomes of your PHP:

A JSON encoded string:

$EmailExistMSG = "L'E-mail est déja utilisé !";
$EmailExistJson = json_encode($EmailExistMSG);
echo $EmailExistJson ;

A JSON encoded string:

$MSG = 'Utilisateur enregistré !' ;
$json = json_encode($MSG);
echo $json ;

A plain text string:

echo 'Réessayez';

You should be consistent: always encode the output as JSON or never encode the output as JSON.

Either:

  1. Change the third case to encode the result as JSON like the others or
  2. Change the first two to output plain text and change the JavaScript so it doesn't try to parse it as JSON

Aside: you don't specify header("Content-Type: something"), so no matter which if plain text or JSON you output, you are claiming to output HTML (PHP's default). You should fix that.

Upvotes: 1

Viraj Amarasinghe
Viraj Amarasinghe

Reputation: 941

What is the point of encoding a string in to json string. echo the string directly or create a response array and encode it.

$x= array(
  "error_code": "404",
  "message": "not found"
);
echo json_encode($x);

Upvotes: 0

RamaKrishna
RamaKrishna

Reputation: 217

In you php script you directly json_encode the string which in return a string only.

So in your javascript code receives the string from the php file and you can't JSON.parse on a string. So it giving you error.

Upvotes: 0

Related Questions