0

Using Volley library in Android, I send the data to the server using POST method.

private void registerNewUser(final String name, final String email, final String password) {
    final String TAG_REGISTER = "New user registration";

    String tag_string_req = "req_register";

    final ProgressDialog pDialog = new ProgressDialog(getActivity());
    pDialog.setCancelable(true);

    pDialog.setMessage("Registering..");
    pDialog.show();

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.POST, ServerURL.URL_REGISTER, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d(TAG_REGISTER, "Register Response: " + response.toString());
            pDialog.dismiss();

            try {
                JSONObject jObj = new JSONObject(response.toString());
                boolean error = jObj.getBoolean("error");
                if (!error) {
                    // User successfully stored in MySQL
                    // Now store the user in sqlite
                    String uid = jObj.getString("uid");

                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user
                            .getString("created_at");

                    // Inserting row in users table
                    db.addUserIntoSQLite(name, email, uid, created_at);

                    Toast.makeText(getActivity(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();

                    // Launch login activity
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivity(intent);

                } else {

                    // Error occurred in registration. Get the error
                    // message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG_REGISTER, "Registration Error: " + error.getMessage());
            Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
            pDialog.dismiss();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "register");
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };
    ApplicationController.getInstance().addToRequestQueue(jsonObjectRequest, tag_string_req);
}

And this is the PHP part that takes the POST data.

<?php

if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // get tag
    $tag = $_POST['tag'];

    // include db handler
    require_once 'mysql/DB_Functions.php';
    $db = new DB_Functions();

    // response Array
    $response = array("tag" => $tag, "error" => FALSE);

    // check for tag type
    if ($tag == 'register') {
        // Request type is Register new user
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = TRUE;
            $response["error_msg"] = "User already exists";
            echo json_encode($response);
        } else {
            // store user
            $user = $db->storeUser($name, $email, $password);
            if ($user) {
                // user stored successfully
                $response["error"] = FALSE;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = TRUE;
                $response["error_msg"] = "Error occured in Registartion";
                echo json_encode($response);
            }
        }
    } else {
        // user failed to store
        $response["error"] = TRUE;
        $response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'";
        echo json_encode($response);
    }
} else {
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameter 'tag' is missing!";
    echo json_encode($response);
}
?>

Now, when I run the registerNewUser() method here, it shows the toast message that the tag is missing. As you can see in the PHP code, the error message "Required parameter 'tag' is missing!" is shown if the tag is not set or empty.

Why am I getting that message even though I properly included the tag variable in the Android code?

edited:

I just downloaded the .htaccess file from the web server. I'm currently using 000webhost.com as the web hosting, and it was like this inside the file.

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php

These are the ones I have absolutely no clue of.. Does this part have an error that hinders the POST request in PHP? If so, how should I fix it?

MarshallLee
  • 1,290
  • 4
  • 23
  • 42
  • did you check that you're actually sending (and receiving) that data? `var_dump($_SERVER['REQUEST_METHOD'], $_POST)` and see what's arriving. – Marc B Nov 12 '15 at 17:53
  • @MarcB Hey thanks, but how do I implement that code? Actually I only learned Android so far and this is the first time to use PHP. I'm using the web hosting service called 000webhost.com, and I haven't learned it before. – MarshallLee Nov 12 '15 at 17:57
  • @MarcB Now I understood where to put that code and now I see this - {"error":true,"error_msg":"Operation failed due to the missing tag!"}string(3) "GET" array(0) { } – MarshallLee Nov 12 '15 at 22:18
  • so it's a get request, meaning that whatever received the post caused a redirect. – Marc B Nov 13 '15 at 14:14
  • @MarcB Hmm that's very strange, because I didn't mention any GETs either on the PHP or the Android side. – MarshallLee Nov 13 '15 at 14:15
  • @MarcB Could you tell me how and why this happens? – MarshallLee Nov 13 '15 at 14:16
  • probably something in apache (.htaccess/.conf), or a script that handles the php redirecting elsewhere. bypass android entirely, fake up an html form that submits the same data, and use your browser console to see what's happening. – Marc B Nov 13 '15 at 15:05
  • @MarcB I added the .htaccess file above. Can you check this out? – MarshallLee Nov 13 '15 at 15:33

0 Answers0