getting empty response from PHP server - php

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 ?

Related

insert values to mysql using php

I am inserting some values from my android login page to mysql database using php .
login.php
<?php
$con = mysql_connect("localhost","abc","xyz") or die(mysql_error());
mysql_select_db("sync",$con) or die(mysql_error());
$user_name = $_POST['user_name'];
$user_mobile_no = $_POST['user_mobile_no'];
$user_email_id = $_POST['user_email_id'];
$imei_no = $_POST['imei_no'];
$login_date = $_POST['login_date'];
$time = $_POST['time'];
$user_name = 'Navdeep';
$user_mobile_no = '12345678990';
$user_email_id = 'nav#gmail.com';
$imei_no = '1234567890';
$login_date = '24-12-2012';
$time = '01:01:01';
$result = mysql_query("INSERT INTO
login_details(user_name,user_mobile_no,user_email_id,
imei_no,login_date,time)
VALUES('$user_name','$user_mobile_no','$user_email_id',' $imei_no','$login_date','$time')");
if($result)
{
$response["success"] = 1;
$response["message"] = "User Details inserted successfully";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "There was an error inserting user details";
echo json_encode($response);
}
mysql_close($con);
?>
When i use $_POST[''] values are getting inserted as blank , but when i hardcode the values it is getting inserted , need some help
Android code :
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_name",userName);
jsonObject.put("user_mobile_no",mobNo);
jsonObject.put("user_email_id",email);
jsonObject.put("imei_no",imeino);
jsonObject.put("login_date",date);
jsonObject.put("time",time);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
String basicAuth = "Device " + new
String(Base64.encode((imeino).getBytes(), Base64.NO_WRAP));
RequestBody body =
RequestBody.create(JSON,String.valueOf(jsonArray));
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().header("Authorization",
basicAuth).url(url).post(body).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Login.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Request to the
server failed", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, Response response) throws
IOException {
Log.i("response ", "onResponse(): " + response );
StatusLine statusLine = null;
String result = response.body().string();
if(result.equals("") || result.equals(null)){
Log.i("No response", "No response");
}else{
Log.i("Response","Response "+result);
statusLine = StatusLine.get(response);
final int responseCode = statusLine.code;
Log.d("Code:", String.valueOf(responseCode));
}
}
});
}catch (Exception e){
e.printStackTrace();
}
You should send form data request from android.
Replace this
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_name",userName);
jsonObject.put("user_mobile_no",mobNo);
jsonObject.put("user_email_id",email);
jsonObject.put("imei_no",imeino);
jsonObject.put("login_date",date);
jsonObject.put("time",time);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
String basicAuth = "Device " + new
String(Base64.encode((imeino).getBytes(), Base64.NO_WRAP));
RequestBody body =
RequestBody.create(JSON,String.valueOf(jsonArray));
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().header("Authorization",
basicAuth).url(url).post(body).build();
With
RequestBody formBody = new FormBody.Builder()
.add("user_name",userName)
.add("user_mobile_no",mobNo)
.add("user_email_id",email)
.add("imei_no",imeino)
.add("login_date",date)
.add("time",time)
.build();
String basicAuth = "Device " + new
String(Base64.encode((imeino).getBytes(), Base64.NO_WRAP));
Request request = new Request.Builder().header("Authorization",
basicAuth).url(url).post(formBody).build();

Delete row from MySQL table via android

I need to delete an item from a list view on android when clicked. The thing is, my table is not on the phone(SQLite), but on the server. So I'm using a PHP code for this.
I have set up an onClickListener.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v,int position, long id) {
Show_Alert_box(v.getContext(),
"Please select action.", position);
}
});
public void Show_Alert_box(Context context, String message, int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context)
.create();
//alertDialog.setTitle(getString(R.string.app_name_for_alert_Dialog));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DBHandlerComments dbhelper = new DBHandlerComments(Comments.this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
try{
JSONObject json2 = JSONParser.makeHttpRequest(urlDelete, "POST", params);
try {
int success = json2.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
//adapter.notifyDataSetChanged();
db.close();
}catch(Exception e){
}
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage(message);
alertDialog.show();
}
This is my JSONParser's makehttprequest code:
public static JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
//from here
while ((line = reader.readLine()) != null) {
if(!line.startsWith("<", 0)){
if(!line.startsWith("(", 0)){
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
`
And this is my PHP code:
$response = array();
if (isset($_POST['id'])) {
$id = $_POST['id'];
// include db connect class
$db = mysql_connect("localhost","tbl","password");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("shareity",$db);
// mysql update row with matched id
$result = mysql_query("DELETE FROM comments_activities WHERE id = $id");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully deleted";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
I'm adding the params like this:
params.add(new BasicNameValuePair(KEY_ID, id));
params.add(new BasicNameValuePair(KEY_AID, aid));
params.add(new BasicNameValuePair(KEY_ANAME, an));
params.add(new BasicNameValuePair(KEY_EVENT, ev));
params.add(new BasicNameValuePair(KEY_COMMENT, cb));
params.add(new BasicNameValuePair(KEY_USER, cby));
params.add(new BasicNameValuePair(KEY_TIME, cd));
I don't get any result. Can I know why?
I have noticed that you add unneeded parameters although you just need the id.
This is a simple code for deleting the given id, you can try it. If it worked, the error would be in your android code.
<?php
$servername = "your servername";
$username = "your username";
$password = "your password";
$dbname = "your dbname";
$link = mysql_connect($servername, $username, $password);
mysql_select_db($dbname, $link);
$id=$_POST['id'];
$result = mysql_query("DELETE FROM table_name WHERE id=$id", $link);
$response["success"] = 1;
$response["message"] = "Deleted successfully!";
echo json_encode($response);
?>
Change the servername to your database url and so on the other information.

Why cant the code match ? PHP Response and Android

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";
}

I trying to send this json data form android to php server

I trying to send this json data form android to php server.
this my json data{email:"user111#gmail.com",password:"00000"},
any one help how the decode this json data in php server
this my php server code
<?php
$response = array();`
require_once __DIR__ . '/db_connect.php';`
if(!isset($_POST['params'])){
$decoded=json_decode($_POST['params'],true)
$email=json_decode['email'];
$pass=json_decode['password'];
// connecting to db
$db = new DB_CONNECT();`
$result = mysql_query("SELECT *FROM user WHERE email = $email");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {`
$result = mysql_fetch_array($result);
$this->mylog("email".$email.",password".$pass);
if($pass==$result[password]){
echo " password is correct";
$response["code"]=0;
$response["message"]="sucess";
$response["user_id"]=$result["userid"];
$response["firstname"]=$result["fname"];
$response["lastname"]=$result["lname"];
echo json_encode($response);
}else{
$response["code"]=3;
$response["message"]="invalid password and email";
echo json_encode($response);
}
}else {
// required field is missing
$response["code"] = 1 ;
$response["message"] = "no data found";
// echoing JSON response
echo json_encode($response);
}
}
}else {
// required field is missing
$response["code"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response); }?>
**this my android code json praser **
public JSONObject loginUser(String email, String password) {
Uri.Builder loginURL2 = Uri.parse(web).buildUpon();
loginURL2.appendPath("ws_login.php");
JSONObject loginJSON = new JSONObject();
try {
loginJSON.put("email", email);
loginJSON.put("password", password);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = jsonParser.getJSONFromUrl(loginURL2.toString(),
loginJSON);
return json;
}
this my android json data send function
public JSONObject getJSONFromUrl(String url, JSONObject params) {
// Making HTTP request
try {
// defaultHttpClient
// boolean status=isNetworkAvailable();
HttpParams param = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(param, 10000);
HttpConnectionParams.setSoTimeout(param, 10000);
DefaultHttpClient httpClient = new DefaultHttpClient(param);
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(params.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
CONTENT_TYPE_JSON));
httpPost.setEntity(se);
Log.d("URL Request: ", url.toString());
Log.d("JSON Params: ", params.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
Log.d("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
Log.e("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
Log.e("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
jsonResp = sb.toString();
Log.d("Content: ", sb.toString());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting Response " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonResp);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
If $_POST['params'] is a JSON encoded string, you only have to call json_decode once, not the multiple times that you have shown.
$decoded = json_decode($_POST['params'], true);
// Decoded is now an array of the JSON data
$email = $decoded['email'];
$pass = $decoded['password'];
It should be noted that the string in your question is not valid JSON, as email and password need to be quoted, as well.
You can do live testing of the json_decode function here:
http://php.fnlist.com/php/json_decode
You can validate your JSON here:
http://jsonlint.com

Sending and receiving json from android app to php script?

I am new to android development and I am trying to make a login page which sends the password and username to a php script as a json array and the php script returns a json array response which contains the meassage accordingly.
I have made a android code as:
jobj.put("uname", userName);
jobj.put("password", passWord);
JSONObject re = JSONParser.doPost(url, jobj);
Log.v("Received","Response received . . ."+re);
// Check your log cat for JSON reponse
Log.v("Response: ", re.toString());
int success = re.getInt("success");
if (success == 1) {
return 1;
}
else{
return 0;
}
}
catch(Exception e){ e.getMessage(); }
}
The JsonParser doPost code is as follows:
public static JSONObject doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
request.setEntity(entity);
Log.v("entity",""+entity);
HttpResponse response;
try{
response = httpclient.execute(request);
Log.v("REceiving","Received . . .");
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
Log.v("RESPONSE",""+is);
}
catch(Exception e){
Log.v("Error in response",""+e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
Log.v("Reader",""+reader.readLine());
while ((line = reader.readLine()) != null) {
Log.v("line",""+line);
sb.append(line + "\n");
}
Log.v("builder",""+sb);
is.close();
json = sb.toString();
} catch (Exception e) {
Log.v("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.v("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have the php script as:
$response = array();
$con=mysqli_connect("localhost","uname","password","db_manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password'];
$query = "SELECT mm_emp_id,mm_password FROM employee_master WHERE mm_emp_id='$empid'and mm_password='$pass'";
$result = mysqli_query($con, $query);
if(count($result) > 0){
$response["success"] = 1;
$response["message"] = "";
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "The username/password does not match";
echo json_encode($response);
}
}
I am getting undefined index at the line where I check for isset(). What am I doing wrong in receiving the json in php script?
If you can see I have used a link for my help
Please do help me out.
In the doPost method you don't use the JSON object (JSONobject c) that contains the variables
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = "http://test.myhodo.in/index.php/test/execute";
#Override
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));
} catch (Exception e) { e.printStackTrace();}
return jsonResponse;
}
Main Activity
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", "hello");
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}

Categories