This is my java code
public void login() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.0.104/rocket/assign_job.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(1);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
//int smsNum = Integer.parseInt(smsCode.getText().toString());
nameValuePairs.add(new BasicNameValuePair("smsCode", smsCode));// $Edittext_value = $_POST['Edittext_value'];
//nameValuePairs.add(new BasicNameValuePair("userName", rocketName));
Log.d("smsCode ===", smsCode);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
//response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
runOnUiThread(new Runnable() {
public void run() {
Log.d("PHP Response: ", response);
pDialog.dismiss();
}
});
if (response.equalsIgnoreCase("success")) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(UserPage.this, "Job Assigned", Toast.LENGTH_SHORT).show();
}
});
} else {
showAlert();//testing bitbuckettt
}
} catch (Exception e) {
pDialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
This is my PHP Code:
<?php
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
if(isset($_POST['smsCode'])){
$smsCode = $_POST['smsCode'];
$query_search = "SELECT * FROM confirmedrequest WHERE smsCode='".$smsCode."'";
$query_exec = mysqli_query($db->getConnection(),$query_search) or die(mysqli_error($db->getConnection()));
$row = mysqli_num_rows($query_exec);
if($row == 0){
echo "failed";
}else{
echo "success";
$rocketName = mysqli_real_escape_string($db->getConnection(),$_POST["userName"]);
$sql_update = "UPDATE confirmedrequest SET jobTakenBy = '$rocketName' WHERE smsCode = $smsCode ";
$sql_exec = mysqli_query($db->getConnection(),$sql_update) or die(mysqli_error($db->getConnection()));
}
}else{
echo "Empty code";
}
?>
The PHP Response in logcat is always failed even though the code matches. I have tried to debug it for several hours but still cant solve. All I want is to run the code below (response.equalsIgnoreCase("success")) when the code matches.
You have to set the headers in order to the response to be formatted in a correct way:
$db = new DB_CONNECT();
if(isset($_POST['smsCode'])){
$smsCode = $_POST['smsCode'];
$query_search = "SELECT * FROM confirmedrequest WHERE smsCode='".$smsCode."'";
$query_exec = mysqli_query($db->getConnection(),$query_search) or die(mysqli_error($db->getConnection()));
$row = mysqli_num_rows($query_exec);
if($row == 0){
http_response_code(500);
echo "failed";
}else{
http_response_code(200);
echo "success";
$rocketName = mysqli_real_escape_string($db->getConnection(),$_POST["userName"]);
$sql_update = "UPDATE confirmedrequest SET jobTakenBy = '$rocketName' WHERE smsCode = $smsCode ";
$sql_exec = mysqli_query($db->getConnection(),$sql_update) or die(mysqli_error($db->getConnection()));
}
}else{
http_response_code(400);
echo "Empty code";
}
Related
I had search many things but didn't work. So this is my problem.
I have succeed to make login form with responseHandler. This is the code :
public void login()
{
httpClient=new DefaultHttpClient();
httpPost= new HttpPost("http://studentstracking.hol.es/loginDatabase2.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",txtId.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",txtPassword.getText().toString().trim()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(LoginActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(LoginActivity.this, student_activity.class));
}else{
showAlert();
}}
And this is the PHP code :
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from user2 where kode_user2 = '".$username."' AND password = '".$password."'";
$query_exec = mysqli_query($conn, $query_search) or die(mysqli_error($conn));
$rows = mysqli_num_rows($query_exec);
if($rows == 0) {
echo "No Such User Found";
}
else {
echo "User Found";
}
But this time i want to execute the PHP and get the value from it and store it into variable or maybe store it into SQLite.
This is the PHP code :
$query_search1 = "SELECT `schedule`.`kode_schedule`,`schedule`.`kode_matkul`,`matakuliah`.`title`,`schedule`.`ruang`,`kelas`.`latitude`,`kelas`.`longitude`,`kelas`.`lantai`,`schedule`.`hari`,`schedule`.`jam` FROM schedule LEFT JOIN `u466318196_track`.`matakuliah` ON `schedule`.`kode_matkul` = `matakuliah`.`kode_matkul` LEFT JOIN `u466318196_track`.`kelas` ON `schedule`.`ruang` = `kelas`.`ruang` WHERE(( kode_schedule = 'sch0001'))";
$query_exec1 = mysqli_query($conn, $query_search1) or die(mysqli_error($conn));
while ($data2 = mysqli_fetch_assoc($query_exec1))
{
$response['length'][] = $data2;
}
print json_encode($response);
And the result of this json is :
{
"length":
[
{
"kode_schedule":"sch0001",
"kode_matkul":"TIB01",
"title":"Basis Data",
"ruang":"501",
"latitude":"-6.18861653446272",
"longitude":"106.801122526546",
"lantai":"5",
"hari":"Selasa",
"jam":"17:45:00"
},
{
"kode_schedule":"sch0001",
"kode_matkul":"TIB02",
"title":"Pemrograman Berorientasi Objek",
"ruang":"LABB",
"latitude":"-6.18864706134991",
"longitude":"106.801161122636",
"lantai":"5",
"hari":"Selasa",
"jam":"19:30:00"
}
]
}
So i want to store the "kode_schedule","kode_matkul",etc values into variable such as String or maybe string with arrays.
Please kindly help me.
You are getting results in response string.
JSONObject mainObject=new JSONObject(response);
for(int i: 0 and 1){
mainObject.getJSONArray("length").getJSONObject(i).getString("kode_schedule");
mainObject.getJSONArray("length").getJSONObject(i).getString("kode_matkul");
}
use json method to access accordingly. Their are are so many tutorial to learn json parsing.
I am trying to make a HttpPost from my app to a php script, which will then insert data to a remote database. I'm not getting any runtime errors, but the data never gets inserted into my remote database.
Code:
public class InsertResult extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... arg0)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.<myDomain>.co.za/insertTeamResultwithCode.php");
try
{
ArrayList<NameValuePair> nameValues = new ArrayList<NameValuePair>(10);
nameValues.add(new BasicNameValuePair("Code", password));
nameValues.add(new BasicNameValuePair("Section", section));
nameValues.add(new BasicNameValuePair("Gender", gender));
nameValues.add(new BasicNameValuePair("WinningTeam", newResult.getWinningTeam()));
nameValues.add(new BasicNameValuePair("LosingTeam", newResult.getLosingTeam()));
nameValues.add(new BasicNameValuePair("FixtureD", newResult.getDate()));
nameValues.add(new BasicNameValuePair("FixtureT", newResult.getTime()));
nameValues.add(new BasicNameValuePair("Venue", newResult.getVenue()));
nameValues.add(new BasicNameValuePair("Court", newResult.getCourt()));
nameValues.add(new BasicNameValuePair("Texts", newResult.getText()));
httppost.setEntity(new UrlEncodedFormEntity(nameValues));
HttpResponse response = httpclient.execute(httppost);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
GoToJarvisDashboard();
}
}
And PhP script:
<?php
//Code verifications
$Code = $_GET['Code'];
//Variables for SQL INSERT
$Section = $_GET['Section'];
$Gender = $_GET['Gender'];
$WinningTeam = $_GET['WinningTeam'];
$LosingTeam = $_GET['LosingTeam'];
$FixtureD = $_GET['FixtureD'];
$FixtureT = $_GET['FixtureT'];
$Venue = $_GET['Venue'];
$Court = $_GET['Court'];
$Texts = $_GET['Texts'];
$SetsWon = $_GET['SetsWon'];
$SetsLost = $_GET['SetsLost'];
$Winner_Score = $_GET['Winner_Score'];
$Loser_Score = $_GET['Loser_Score'];
$dbname = '<dbName>';
$dbuser = '<user>';
$dbpass = '<password>';
$dbhost = '<host>t';
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die ("Unable to Connect to '$dbhost'");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$SQL = "SELECT * FROM squasdlw_db1.validationCodes WHERE Code = '$Code'";
$codeValid = mysqli_query($connect, $SQL) or die (mysqli_error($connect));
$response["no"] = array();
if (mysqli_num_rows($codeValid) > 0)
{
echo "Code is valid\n\n";
//Insert Result
$query = "INSERT INTO squasdlw_db1.jarvisTeamResults (Section,Gender,WinningTeam,LosingTeam,FixtureD,FixtureT,Venue,Court,Texts,SetsWon,SetsLost,Winner_Score,Loser_Score) VALUES('$Section','$Gender','$WinningTeam','$LosingTeam','$FixtureD','$FixtureT','$Venue','$Court','$Texts','$SetsWon','$SetsLost','$Winner_Score','$Loser_Score')";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Result successfully submitted to Jarvis Remote Database: Table -> jarvisTeamResults\n\n" ;
//Update Winner on jarvisLogs
$query = "UPDATE squasdlw_db1.jarvisLogs SET Points = Points + '$Winner_Score', Played = Played + 1, Won = Won + 1 WHERE Gender = '$Gender' AND Section = '$Section' AND Team = '$WinningTeam'";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Log update for '$WinningTeam': Table -> jarvisLogs\n\n";
//Update Winner on jarvisLogs
$query = "UPDATE squasdlw_db1.jarvisLogs SET Points = Points + '$Loser_Score', Played = Played + 1, Lost = Lost + 1 WHERE Gender = '$Gender' AND Section = '$Section' AND Team = '$LosingTeam'";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Log update for '$LosingTeam': Table -> jarvisLogs\n\n";
$response["isValid"] = true;
echo json_encode($response);
}
else
{
$response["isValid"] = false;
echo "The code is not valid\n";
echo json_encode($response);
}
mysqli_close($connect);
?>
Whats even weirder is that if I try this in a web browser, it works fine and the data does get added to the remote database-
http://www.<myDomain>.co.za/insertTeamResultwithCode.php?Code=<password>&Section=A&Gender=Men&WinningTeam=NW&LosingTeam=KZN&FixtureD=2015-05-25&FixtureT=09:00:00&Venue=Puk&Court=6&Texts=Andrew%20(NW)%20beat%20Kevin%20(WP)%203-1&SetsWon=15&SetsLost=5&Winner_Score=15&Loser_Score=5
Please help out, I have no idea what is going wrong because it does not create runtime errors? I am about to go crazy...
You are doing an HttpPost so you should get your data via POST and not GET
//Code verifications
$Code = $_POST['Code'];
//Variables for SQL INSERT
$Section = $_POST['Section'];
$Gender = $_POST['Gender'];
$WinningTeam = $_POST['WinningTeam'];
$LosingTeam = $_POST['LosingTeam'];
$FixtureD = $_POST['FixtureD'];
$FixtureT = $_POST['FixtureT'];
$Venue = $_POST['Venue'];
$Court = $_POST['Court'];
$Texts = $_POST['Texts'];
$SetsWon = $_POST['SetsWon'];
$SetsLost = $_POST['SetsLost'];
$Winner_Score = $_POST['Winner_Score'];
$Loser_Score = $_POST['Loser_Score'];
Or change your android code to make GET requests :
HttpGet httpget = new HttpGet("http://www.example.com/insertTeamResultwithCode.php");
You are sending POST in android BUT you are expecting GET in php which are not the same.
Change the $_GET to $_POST and it will work.
Here a post that will tell you difference between then
Here another with some more details
The code queries the user table ("name") to retrieve the Chinese name corresponding to the username (unique) input by user.
In DEBUG mode, found that username in $_POST['username'] is blank when passed to PHP. I can retrieve the Chinese name in DEBUG mode. Please help to figure out what's wrong in parameter-passing.
Android part to send a POST request to PHP.
public class SigninActivity extends AsyncTask<String,Void,String> {
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://www.example.com/login.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://www.example.com/login.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
// Code in PHP
$con = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con, $mysql_database) or die("Could not select database");
if (DEBUG) {
echo "Connected to database $mysql_database";
}
mysqli_set_charset($con, 'utf8');
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
if (DEBUG) {
$username = "b";
}
$qry1 = "SELECT c_f_name FROM name where username = \"$username\" ";
$result = mysqli_query($con, $qry1);
if(DEBUG) {
echo "This is the username: ";
echo $username;
if ($result) {
echo $username;
//successful query
if (mysqli_num_rows($result) > 0) {
echo "query successful -
";
echo mysqli_num_rows($result);
} else {
echo "query successful-0 rows
";
}
} else {
// query not successful
echo "Query unsuccessful";
}
}
$row = mysqli_fetch_array($result);
//Since there is only 1 record that match, just retrieve the first and only record
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
You are passing your username/password through the url
http://www.example.com/login.php?username="+username+"&password="+password
Therefor request your values using either $_GET['username'] or $_REQUEST['username'].
you are passing GET variable and trying to retrieve variables from POST method.. that won't work you also have to use $GET['variable_name'] or $REQUEST['variable_name'] to retrieve data from that url.
its a simple rule that if you are passing your data through get or post method than also you have to retrieve that data as same method.
I am in a problem can any one help me please.
I have a php file which i am calling from my java class file's Asynctask.
In the Asynctask i am sending three variables email,password and pin.
What is happening, is that when i run my php with hardcoded values it gives me proper result.
RESULT IS:
Inside 1st if
Inside 2nd if
Verified
main if
But wen i try running my php through the code it gives me wrong result
RESULT IS:
Inside 1st if
Invalid
main if
I'am not able to understand why is this happening please Guide me.
My PHP File
<?php
require 'DbConnect.php';
$i=1;
$Password = $_POST["password"];
$Email = $_POST["email"];
$Pin = $_POST["pin"];
//$KeyCode = $_REQUEST["key"];
if((isset($_POST["password"])) && (isset($_POST["email"])) && (isset($_POST["pin"])))
{
$query4 = ("SELECT seller_id, name, email, password, verification_Pin, verification_Code, created_Date FROM `seller` WHERE email = '$Email'");
$query_run = mysql_query($query4);
$row=mysql_fetch_row($query_run);
$int=$row[0];
$strName=$row[1];
$strEmail=$row[2];
$strPwd=$row[3];
$strPin=$row[4];
echo $Pin;
echo $Password;
echo $Email;
echo $int;
echo $strEmail;
echo $strPwd;
echo $strPin;
if(($Email==$strEmail) && ($Password==$strPwd) && ($Pin==$strPin))
{
global $i;
$i=2;
$id=updateValidation($int);
echo $id;
if($id==1)
{
echo "Verified";
}
else
{
echo "Not Verified";
}
}
else
{
echo "Invaild";
}
}
else
{
echo "Values not set";
}
function updateValidation($sid)
{
global $i;
if($i==2)
{
echo "Inside Update vAlidation";
$queryUpdate = ("UPDATE `seller` SET verification_Pin = 0, verification_Code = 'Verified', created_Date = CURDATE() where seller_id='$sid'");
if(mysql_query($queryUpdate))
{
return 1;
}
else
{
return 2;
}
}
else
{
echo "i not 2";
}
}
?>
My Class file:
Button ok = (Button) myDialog
.findViewById(R.id.button1);
et_pin = (EditText) myDialog
.findViewById(R.id.editText1);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"CLICKED OK", Toast.LENGTH_LONG).show();
pin = et_pin.getText().toString();
Toast.makeText(
getApplicationContext(),
"email,pass,pin= " + str1 + "," + str2
+ "," + pin, Toast.LENGTH_LONG)
.show();
new App_pin_Task().execute(FILENAME_pin);
// Intent intent = new
// Intent(Dealer_details.this,
// Login.class);
// startActivity(intent);
}
});
public class App_pin_Task extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),
"Inside App_pin_Task post Execute(Result)=" + result,
Toast.LENGTH_LONG).show();
if (result.contains("Invalid")) {
et_pin.setText("");
} else {
Intent myIntent = new Intent(Login.this, UserActivity.class);
startActivity(myIntent);
}
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
// String is = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://animsinc.com/verifyEmail.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
4);
nameValuePairs.add(new BasicNameValuePair("email", str1));
nameValuePairs.add(new BasicNameValuePair("password", str2));
nameValuePairs.add(new BasicNameValuePair("pin", pin));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return is;
}
}
What is being returned with
$Password = $_REQUEST["password"];
$Email = $_REQUEST["email"];
$Pin = $_REQUEST["pin"];
$KeyCode = $_REQUEST["key"];
Your server configuration may have this option disabled and not returning anything.
You shouldn't use $_REQUEST anyway because you can never be sure where the data is actually coming from: $_POST, $_GET or $_cookie.
try this!
Change this
$Password = $_REQUEST["password"];
$Email = $_REQUEST["email"];
$Pin = $_REQUEST["pin"];
$KeyCode = $_REQUEST["key"];
to for Get Request
$Password = $_GET["password"];
$Email = $_GET["email"];
$Pin = $_GET["pin"];
$KeyCode = $_GET["key"];
or for Post Request
$Password = $_POST["password"];
$Email = $_POST["email"];
$Pin = $_POST["pin"];
$KeyCode = $_POST["key"];
or
"SELECT seller_id, name, email, password, verification_Pin,
verification_Code, created_Date FROM seller WHERE email = '".$Email."'"
Complementing the answer from fayeq-ali-khan I would also do the following;
First use post and add html special character for security.
htmlspecialchars => Convert special characters to HTML entities
$Password = htmlspecialchars($_POST['password'],ENT_QUOTES);
$Email = htmlspecialchars($_POST['email'],ENT_QUOTES);
$Pin = htmlspecialchars($_POST['pin'],ENT_QUOTES);
$KeyCode = htmlspecialchars($_POST['key'],ENT_QUOTES);
Also on your android activity and before you send the string it would be a good idea to trim the value to make sure that you are not transmitting empty character that can also mess up with the PHP
nameValuePairs.add(new BasicNameValuePair("email", str1.trim()));
nameValuePairs.add(new BasicNameValuePair("password", str2.trim()));
nameValuePairs.add(new BasicNameValuePair("pin", pin.trim()));
I hope it help you with something
Hi friends I am trying to add PHP web services to my ANDROID application, my android code:
userName = userNameField.getText().toString();
passWord = passWordField.getText().toString();
try {
JSONObject json = new JSONObject();
json.put("username", userName);
json.put("password", passWord);
json.put("device_type", "Android");
json.put("lat", "0.0");
json.put("long", "0.0");
JSONObject json1 = new JSONObject();
json1.put("method_name", "checkLogin");
json1.putOpt("body", json);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost(URL);
request.setEntity(new StringEntity(json1.toString()));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = client.execute(request, responseHandler);
Toast.makeText(this, response, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
Request:
{"method_name":"checkLogin","body": {"username":"someone#some.com","password":"password","device_type":"android","lat":"","long":""}}
expected Response:
[{"status":"1","message":"Login successfully","data":{"id":"xx","username":"someone#some.com","first_name":"xxx","last_name":"yyy","gender":"xxx","relationship":"xxxx","birthdate":"xxxx","hometown":"","major":null,"class":null,"house":null,"device_type":"iphone","current_location_lat":"0.0","current_location_lon":"0.0","profile_image":"no_male_user.png","is_login":"1","created":"2012","status":"1","tag":[{"id":"x","tag_name":"xxxx"},{"id":"x","tag_name":"xxx xxx"}]}}]
main.php
<?php
require_once('configure.php');
require_once('db.php');
require_once("request.php");
require_once("error_msg.php");
require_once("./includes/JSON.php");
$json = $_POST['json'];
$objRequest = new Request($json);
$rows = $objRequest -> main();
echo $rows;
?>
request.php
<?php
require_once("./includes/JSON.php");
require_once("db.php");
require_once('SimpleImage.php');
class Request
{
function __construct($json)
{
$this -> array1 = #json_decode(stripcslashes(trim($json)));
}
function main()
{
$objDb = new DB();
$conn = $objDb -> getConnection();
if(!$conn)
return Error :: $DB_CONN_ERROR." ".$DB_CONN_ERROR_DESC;
else
{
if($this -> array1 -> method_name == 'checkLogin')
return $this -> getLoginFlag($this -> array1 -> body);
}
}
// For Login Start
function getLoginFlag($body)
{
$username = trim($body -> username);
$password = ($body -> password);
$device_type = trim($body -> device_type);
$this -> rs_login = DB :: selectLoginRecord($body);
$arr_resp = array();
$retArray = array();
$tagListArray = array();
if(mysql_num_rows($this -> rs_login) > 0)
{
while($rows = mysql_fetch_array($this -> rs_login))
{
$arr_resp = array("id"=> $rows['id'],"username"=> $rows['username'],"first_name"=> ucfirst($rows['first_name']),"last_name"=>ucfirst($rows['last_name']),"gender"=>$rows['gender'],"relationship"=>$rows['relationship'],"birthdate"=>date('M d, Y', strtotime($rows['birthdate'])),"hometown"=>$rows['hometown'],"major"=>$rows['major'],"class"=>$rows['class'],"house"=>$rows['house'],"device_type"=>$rows['device_type'],"current_location_lat"=>$rows['current_location_lat'],"current_location_lon"=>$rows['current_location_lon'],"profile_image"=>$rows['profile_image'],"is_login"=>$rows['is_login'],"created"=>date('Y', strtotime($rows['created'])),"status"=>$rows['status']);
}
$this -> rs_tag_list = DB :: selectTagList($arr_resp['id']);
if(mysql_num_rows($this -> rs_tag_list) > 0)
{
while($rows = mysql_fetch_array($this -> rs_tag_list))
{
$tagListArray['tag'][]= array("id"=> $rows['id'],"tag_name"=> $rows['tag_name']);
}
}
$finalArray = array_merge($arr_resp,$tagListArray);
$retArray[] = array("status" => "1","message" => "Login successfully","data" => $finalArray);
}
else
{
$retArray[] = array("status" => "0","message" => "The username or password you entered is incorrect");
}
return json_encode($retArray);
}
// End Login
}
?>
but am getting empty response, can anybody please help me.
Here I am using JSON for data parsing.
thanks for your response friends.
Can you check the php code if it gets the required value correctly and executing the the desired method exactly ?