Ahmed Nader Ahmed Nader - 6 months ago 19
JSON Question

i cant parse the json data

here this code was working and then suddenly after another test it didtn work and said that the json contains html elements like
and i cant make it work again i need help

<?php

include("config.php");

if(isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"])){
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
}

$con = mysqli_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME);

$response = array();

$statement = mysqli_prepare($con, "SELECT * FROM accounts WHERE email = ? OR username = ?");
mysqli_stmt_bind_param($statement, "ss", $email, $username);
$result = mysqli_stmt_execute($statement);
$rows = $result->num_rows;

if($rows > 0){
$response["success"] = false;
$response["message"] = "Email or Username already exists.";
}else{
mysqli_stmt_close($statement);
$statement2 = mysqli_prepare($con, "INSERT INTO accounts (email, username, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement2, "sss", $email, $username, $password);
$result2 = mysqli_stmt_execute($statement2);
$rows2 = $result2->affected_rows;

if($rows2 > 0){
$response["success"] = true;
$response["message"] = "Account created successfuly.";
}else{
$response["success"] = false;
$response["message"] = "Creation error.";
}
}

echo json_encode($response);

mysqli_close($con);

?>


when i parse it in andoid it says to me that it contains a something thas is no a string .. and this is my android code for parsing the json

private void register() {
Response.Listener<String> responselistener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonresponse = new JSONObject(response);
boolean success = jsonresponse.getBoolean("success");
String message = jsonresponse.get("message").toString();
if(success){
Intent gotoContinueRegisterActivityIntent = new Intent(RegisterActivity.this, ContinueRegisterActivity.class);
startActivity(gotoContinueRegisterActivityIntent);
}else {
error.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error2) {
error2.printStackTrace();
}
};
RegisterRequest registerRequest = new RegisterRequest(s_email, s_username, s_password, responselistener, errorListener);
RequestQueue requestQueue = Volley.newRequestQueue(getBaseContext());
requestQueue.add(registerRequest);
}

Answer

You're best to actually send headers to let your android app know that it's receiving json as it probably thinks it's getting the Content Type: text/html.

Try placing this header at the top of your PHP script:

<?php
header("Content-Type: application/json");
Comments