1

I have an app that sends some information via POST to a php script in a server. It uses Asynchttpclient. How can I also receive a reply back from the server (via json?)? Please help.

This is my php script

if($_POST["mode"]=="newuser"){
            //$gcmRegID  = $_GET["shareRegId"]; 
            $gcmRegID  = $_POST["regID"]; 
            $gcmUserName  = $_POST["userName"]; 
            $gcmFolderName = $_POST["folderName"];

            $gcmDate = date("d/m/y");

            $conn = new mysqli($servername, $username, $password, $dbname);
            if($conn->connect_error){
                die("Connection failed: " . $conn->connect_error);
            }
            $in_user = "user";
            $in_password = "NULL";
            $in_email = "NULL";
            $in_dob = "NULL";
            $in_role = "user";
            $in_datejoined = "0000-00-00";
            $foldername = "NULL";

            $sql = "INSERT INTO user(password,regid,name,email,phone,dob,role,datejoined,foldername) VALUES('$in_password','$gcmRegID','$gcmUserName','$in_email','$in_phone','$in_dob','$in_role','$gcmDate','$foldername')";

            $substringtitle = substr($gcmRegID,-7);
            $combined = $gcmUserName."_".$substringtitle;
            if($conn->query($sql)===TRUE){
                    mkdir("./users/".$gcmFolderName);
                    $newfoldername = "./users/".$gcmFolderName;
                    $updatequery = "UPDATE user SET foldername='$newfoldername' WHERE name='$gcmUserName'";


                     $returnfield = array(
                        'foldername' => $newfoldername
                    );
                    header('Content-type: application/json');
                    echo json_encode(array('returnfield'=>$returnfield));


                    if($conn->query($updatequery)===TRUE){
                        echo "folder updated";
                    }
                    //echo "Folder created!";
                //}
                echo "New record created successfully";

            }else{
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
            $conn->close();

            echo "Done!";
            exit;
        }

Android code

 //store in the file server (PHP)
private void storeREG(final String registerID,String userName,String folderName){

    pg.show();
    params.put("regID", registerID);
    params.put("userName",userName);
    params.put("folderName", folderName);
    params.put("mode","newuser");
    Log.d("STORE","STORE");
    //Make RESTful webservice call

    AsyncHttpClient client = new AsyncHttpClient();
    client.post(AppConstants.SERVER_URL, params, new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(String content) {
            pg.hide();
            if (pg != null) {
                pg.dismiss();
            }


            Toast.makeText(applicationCtx, "ID sharing successful", Toast.LENGTH_LONG).show();
            Intent home = new Intent(applicationCtx, HomeActivity.class);
            home.putExtra("regID", registerID);
            Log.d("REGID", registerID);
            startActivity(home);
            finish();
        }

        @Override
        public void onFailure(int statusCode, Throwable error, String content) {
            pg.hide();
            if (pg != null) {
                pg.dismiss();
            }
            Log.d("ERRORTHROW", error.toString());
            if (statusCode == 404) {
                Toast.makeText(applicationCtx, "Requested resource not found", Toast.LENGTH_LONG).show();
            } else if (statusCode == 500) {
                Toast.makeText(applicationCtx, "Something went wrong at the server", Toast.LENGTH_LONG).show();
            } else {
                Log.d("SHOWME", String.valueOf(statusCode));
                Toast.makeText(applicationCtx, "Unexpected error occurred", Toast.LENGTH_LONG).show();
            }
        }


    });

}

Hopefully I can get help with this.

2
  • Did you realize that $in_phone was not defined anywhere in your PHP Script? This is just an observation.... At the least, you could nullify it like you did with E-Mail & Password... Commented May 11, 2016 at 21:52
  • Thanks! will change that Commented May 11, 2016 at 22:20

2 Answers 2

1

You may try to revise your PHP Code. Below is a well-commented sample code to get you started:

    <?php
        // EXPLICITLY INSTRUCT THE HEADER ABOUT THE CONTENT TYPE. HERE - JSON 
        header('Content-type: application/json');

        if($_POST["mode"]=="newuser"){
            $gcmRegID       = htmlspecialchars(trim($_POST["regID"]));
            $gcmUserName    = htmlspecialchars(trim($_POST["userName"]));
            $gcmFolderName  = htmlspecialchars(trim($_POST["folderName"]));
            $gcmDate        = date("d/m/y");

            // I WOULD STRONGLY SUGGEST YOU USE PDO FOR YOUR DATABASE TRANSACTIONS:
            // HERE'S HOW:

            //DATABASE CONNECTION CONFIGURATION:
            defined("HOST")     or define("HOST",   "localhost");           //REPLACE WITH YOUR DB-HOST
            defined("DBASE")    or define("DBASE",  "database");            //REPLACE WITH YOUR DB NAME
            defined("USER")     or define("USER",   "root");                //REPLACE WITH YOUR DB-USER
            defined("PASS")     or define("PASS",   "root");                //REPLACE WITH YOUR DB-PASS

            // ESTABLISH A CONNECTION AND DO YOUR WORK WITHIN A TRY-CATCH BLOCK...
            try {
                $dbh        = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
                $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                // HERE: ALL YOUR BUSINESS LOGIC...
                $in_user        = "user";
                $in_password    = "NULL";
                $in_email       = "NULL";
                $in_phone       = "NULL";
                $in_dob         = "NULL";
                $in_role        = "user";
                $in_dateJoined  = "0000-00-00";
                $folderName     = "NULL";

                $insertSQL      = "INSERT INTO user(`password`, `regid`, `name`, `email`, `phone`, `dob`, `role`, `datejoined`, `foldername`) ";
                $insertSQL     .= " VALUES(:inPassword, :gcmRegID, :gcmUserName, :inEmail, :inPhone, :inDOB, :inRole, :gcmDate, :folderName)";

                $arrInsertData  = array(
                    'inPassword'    => $in_password,
                    'gcmRegID'      => $gcmRegID,
                    'gcmUserName'   => $gcmUserName,
                    'inEmail'       => $in_email,
                    'inPhone'       => $in_phone,
                    'inDOB'         => $in_dob,
                    'inRole'        => $in_role,
                    'gcmDate'       => $gcmDate,
                    'folderName'    => $folderName
                );

                // PREPARE THE INSERT QUERY:
                $insertStmt = $dbh->prepare($insertSQL);

                // INSERT THE NEW ROW:
                $insertStmt->execute($arrInsertData);

                // OBTAIN THE ID OF THE INSERTED ROW TO BE USED AS SUFFIX FOR YOUR USER FOLDER
                $id         = $dbh->lastInsertId();

                // WHAT HAPPENS WHEN 2 USERS HAVE THE SAME USERNAME??? DID YOU THINK ABOUT THAT?
                // TO CIRCUMVENT THIS ISSUE; I WOULD SUGGEST FIRST TO INSERT THE DATA TO THE DATABASE...
                // THEN USE THE ID AS A SUFFIX TO MAKE EACH USER DIRECTORY UNIQUE & THAT IS THE APPROACH TAKEN HERE THOUGH...

                // NOW YOU CAN CREATE YOUR FOLDER USING THIS ID: $id
                // LIKE THIS; 2 USERS WITH USERNAME "android_user" CAN HAVE 2 DIFFERENT FOLDERS LIKE SO: "android_user_97" & "android_user_102"
                $userDirectory  = "./users/" . $gcmFolderName . "_" . $id;
                mkdir($userDirectory);

                // DID IT OCCUR TO YOU THAT 2 USERS MIGHT HAVE THE SAME USERNAME IN WHICH CASE MYSQL (INSTEAD OF YOU) HAS TO DECIDE WHICH USER TO UPDATE?
                // THAT IS WHY DATABASE TABLES ARE DESIGNED TO HAVE UNIQUE IDENTIFIERS LIKE UUID OR ID OR UID OR ANY TOKEN TO MAKE EACH ROW UNIQUE...
                // WE ARE ADOPTING THIS APPROACH IN THE UPDATE QUERY... THAT IS: WE UPDATE THE ROW USING THE ID ABOVE... ASSUMING THAT IS A UNIQUE COLUMN THOUGH.
                $updateSQL      = "UPDATE user SET foldername=:newDirName WHERE id=:ID";

                // NOW UPDATE THE ROW TO TAKE INTO ACCOUNT THE UNIQUE USER-DIRECTORY (USING THE ID AS THE KEY)
                $arrUpdateData  = array(
                    'newDirName'    => $userDirectory,
                    'ID'            => $id      // THIS ASSUMES THAT THE PRIMARY KEY OF YOUR TABLE IS CALLED id OTHERWISE USE THE APPROPRIATE KEY NAME: EG: reg_id OR WHATEVER
                );

                // PREPARE THE UPDATE QUERY:
                $insertStmt = $dbh->prepare($updateSQL);

                // UPDATE THE NEWLY CREATED ROW:
                $insertStmt->execute($arrUpdateData);

                // BUILD THE RESPONSE JSON DATA
                $arrResponse    = array(
                    'folderName'    => $userDirectory,
                    'id'            => $id,
                );

                // SEND THE RESPONSE AS JSON IF ALL WORKS FINE TILL HERE... 
                // THAT MEANS: SEND THE DATA IN $arrResponse AND TERMINATE THE SCRIPT - THE JOB IS DONE.
                // NO NEED FOR ALL THOSE ECHO STATEMENTS AS THE YOU ARE EXPLICITLY SENDING BACK JSON DATA.
                die( json_encode($arrResponse) );

            }catch(PDOException $e){
                // IF THERE WAS ANY KIND OF PDO ERROR, SEND IT BACK ANYWAYS - BUT ALSO AS JSON:             
                $arrResponse    = array(
                    'error'     => $e->getMessage()
                );
                die( json_encode($arrResponse) );
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

1

I can't test the code right now (sorry), but I think it should be something like this:

try {
    RequestParams rParams = new RequestParams();
    rParams.put("example", "example"); // POST
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(pageURL, rParams, new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(JSONArray jsonArray) {
            super.onSuccess(jsonArray);

            //process JSON Array

        }

        @Override
        public void onFailure(Throwable throwable, JSONArray jsonArray) {
            super.onFailure(throwable, jsonArray);
            Log.d(TAG, "error", throwable);
        }

    });
} catch (Exception e) {
    Log.d(TAG, "exception", e);
}

Otherwise I made a very light WebClient, you may want to give it a shot:

https://github.com/omaflak/WebClient

This is a short sample:

WebClient client = new WebClient();
client.setOnRequestListener(new OnRequestListener() {
        @Override
        public void onRequest(String response, int requestID) {
            Log.e(TAG, response);
        }

        @Override
        public void onError(int error_code, String message) {
            Log.e(TAG, message);
        }
});

Pair p = new Pair("field1", "value1");
Pair p2 = new Pair("field2", "value2");
client.requestAsync("http://your-api.com", WebClient.POST, Arrays.asList(p, p2), 1);

//  requestAsync(String url, String method, List<Pair<String, String>> postData, int requestID)

To use it, simply add to your dependencies:

compile 'me.aflak.libraries:webclient:1.0'

2 Comments

Thanks! Will try it out. Is my php script okay though?
i'm not a PHP expert, but I think your variables will be only considered as text in the INSERT INTO command

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.