3

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>
    )
  }
}
4
  • 1
    can you show your react code where you actually checking the output of the php script. Commented Oct 27, 2017 at 11:28
  • adding it right now ! :) Commented Oct 27, 2017 at 11:54
  • Danger: You are vulnerable to SQL injection attacks that you need to defend yourself from. Commented Oct 27, 2017 at 12:01
  • I am aware of that, but being a beginner in php, I wanted to get the primal code to work first ^^. Commented Oct 27, 2017 at 12:07

3 Answers 3

1

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.

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

1 Comment

I now only return JSON statements, as expected by my app's code
0

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.

Comments

0

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);

Comments

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.