Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling different php responses after a javascript http post request

I am developing an android application that uses the PHP/MySQL to send data from app to server in order to register/login users. I already wrote the Javascript and PHP files to send and receive JSON data an insert it into MySQL database. The problem I have is how to handle different responses from PHP.

Exemple:

<?php

   //decode json object
   $json = file_get_contents('php://input');
   $obj = json_decode($json);

   //variables
   $user_firstname = $obj->{'user_firstname'};
   $user_lastname = $obj->{'user_lastname'};
   $user_email = $obj->{'user_email'};
   $user_password = $obj->{'user_password'};

   if([variables] != null){
      //check for an existing email in db
      mysql_query("Check if email exists");

      if(email exist){
         //pass a response to java file
         return user_exists;
         die();
      }else{
         //success
         return success;
      }
   }

?>

All I want is to handle those different return values in order to interact with the user inside the android app.

like image 200
Andrei Stalbe Avatar asked Jun 30 '26 22:06

Andrei Stalbe


2 Answers

I think you should user HTTP response codes for this. For example, your php script will return HTTP 200 - OK when user successfully created and HTTP 409 Conflict when user already exists. This is how RESTfull APIs usually works this. On Android you'll have to check the status code and decide what to do.

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpget = new HttpPost("http://www.google.com/");

HttpResponse response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
like image 56
AlexV Avatar answered Jul 03 '26 13:07

AlexV


You can craft a json response by creating an associative array and passing it to json_encode() which will return a string that you can echo to the java client. Don't forget to set the appropriate Content-Type header using the header() function. It's also a good idea to set the HTTP response code appropriately. I'm picturing something like this:

$responseArray = array('response' => 'success'); // or 'user_exists'
$responseJson = json_encode($responseArray);
header('HTTP/1.1 200 OK'); // or 4xx FAIL_TEXT on failure
header('Content-Type: application/json');
echo $responseJson;

You'll then have to parse this response on the java client.

like image 20
Asaph Avatar answered Jul 03 '26 13:07

Asaph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!