I get following error:
Error parsing data org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
Here is the Android and PHP code I have:
private void eventUpdatePoint(String eventStatus,int lat,int lon){
JSONParser jsonParserEUP = new JSONParser();
try
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("longtitude", Integer.toString(lon)));
params.add(new BasicNameValuePair("latitude", Integer.toString(lat)));
params.add(new BasicNameValuePair("eventstatus", eventStatus));
String url_updatePoint = "http://10.0.2.2/android_connect/event_update_point.php";
JSONObject json = jsonParserEUP.makeHttpRequest(url_updatePoint,"POST", params);
Log.d("Response", json.toString());
}
catch(Exception e)
{
e.printStackTrace();
Log.d("ERROR:","ERROR:" + e.getClass().getName() + ":" + e.getMessage());
}
}
php code:
$response = array(); if (isset($_POST['longtitude']) && isset($_POST['latitude']) &&isset($_POST['eventstatus'])) {
$longtitude = $_POST['longtitude'];
$latitude = $_POST['latitude'];
$eventstatus = $_POST['eventstatus'];
$e_id=0;
$score=0;
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT id FROM cordinates WHERE longtitude=$longtitude AND latitude=$latitude") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$e_id = $row["id"];
}
$result = mysql_query("SELECT score FROM point WHERE e_id=$e_id") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$score = $row["score"];
}
if($eventstatus=="inc")
{
$score+=10;
$result = mysql_query("UPDATE point SET score=$score where e_id=$e_id") or die(mysql_error());
$response["success"] = 1;
$response["message"] ="Score point increased";
}
else if($eventstatus=="dec")
{
$score-=10;
$result = mysql_query("UPDATE point SET score=$score where e_id=$e_id") or die(mysql_error());
$response["success"] = 0;
$response["message"] ="Score point decreased";
}
}
echo json_encode($response);
What am I doing wrong?
The webservice you are using returns a JSONArray. You have to use an object of type JSONArray to store it. You can't use a JSONObject.
Change this line:
JSONObject json = jsonParserEUP.makeHttpRequest(url_updatePoint,"POST", params);
...to this:
JSONArray json = jsonParserEUP.makeHttpRequest(url_updatePoint,"POST", params);
Log your response.If it starts with"[" and ends with "]",you have to store it in variable of type "JSONArray".With attention to your log,your response must be a "JSONArray",so simply save your response in a variable of type "JSONArray".
Related
I'm trying to store Arabic characters in a database on server. But when I add something it will be displayed as ???????????? in the database! I tried too add from my php to check if the problem from the php file, but it added the text correctly in database. So the error from android and json, how can I make the encoding of json to utf8 in android?
Here's my code:
class AddStories extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Caregiver_ID", ID));
params.add(new BasicNameValuePair("Title", "قصة"));
params.add(new BasicNameValuePair("Story", "قصتي بدأت عندما"));
JSONObject json = jsonParser.makeHttpRequest(url_add_story,"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
suc=1;
sucess();
}
else {
suc=0;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
PHP for adding:
<?php
header("Content-Type: text/html; charset=utf-8");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['Caregiver_ID']) && isset($_POST['Title'])&& isset($_POST['Story'])) {
$Caregiver_ID = $_POST['Caregiver_ID'];
$Title = $_POST['Title'];
$Story = $_POST['Story'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
// mysql inserting a new row
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "glossary successfully created.";
// echoing JSON response
echo json_encode($response,JSON_UNESCAPED_UNICODE );
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
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 );
}
?>
Also when I tried to retrieve from android I got this for the text:
نةيىؤتيلالاؤتيلاارلابارابي-الالالتعا
while its retrieved correctly in php.
PHP code
<?php
header("Content-Type: text/html; charset=utf-8");
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM Stories ") or die(mysql_error());
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
if (mysql_num_rows($result) > 0) {
$response["story"] = array();
while ($row = mysql_fetch_array($result)) {
$story = array();
$story ["Caregiver_ID"] = $row["Caregiver_ID"];
$story ["Title"] = mb_convert_encoding($row["Title"],'HTML-ENTITIES','utf-8');
$story ["Story"] = mb_convert_encoding($row["Story"],'HTML-ENTITIES','utf-8');
array_push($response["story"], $story);
}
$response["success"] = 1;
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No locations found";
// echo no users JSON
echo json_encode($response);
}
?>
Try below code in android
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
byte[] buffer = new byte[1024];
int nread;
while ((nread = stream.read(buffer)) > 0) {
baos.write(buffer, 0, nread);
}
} catch (ClientProtocolException | IOException e) {
}
//Create a JSON from the String that was return.
JSONObject jsonObject = new JSONObject();
try {
String jsonText = new String(baos.toByteArray(), StandardCharsets.UTF_8);
jsonObject = new JSONObject(jsonText);
You have to put N before the columns which you need to add the Arabic text.
For example N'مختار'.
According to your code,you should change this line
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");
........
.....
...
to be
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', N'$Title',N'$Story')");
I am making an app wherein I fetch user data from the corresponding sql table using php.
<?php
$email = $_POST["email"];
#mysql_connect("localhost","root","root") or die(#mysql_error());
#mysql_select_db("dtbse") or die(#mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(#mysql_error());
$result = array();
while ($y=mysql_fetch_array($x)) {
echo $y["uname"]."<br>";
echo $y["gender"]."<br>";
echo $y["pass"]."<br>";
echo $y["address"]."<br>";
echo $y["email"]."<br>";
}
?>
Any help will be greatly apprecitated. I know this question has been a lot of times but I dont think there is something replicating this issue. Thanks.
Here is the code snippet responsible for fetching and parsing.
final ArrayList arr = new ArrayList();
arr.add(new BasicNameValuePair("email", uname));
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://xxyoxx.esy.es/getDetails.php");
httppost.setEntity(new UrlEncodedFormEntity(arr));
HttpResponse hr = httpclient.execute(httppost);
HttpEntity ent = hr.getEntity();
is = ent.getContent();
Toast.makeText(getApplicationContext(),"1 wrk ",Toast.LENGTH_LONG).show();
} catch (Exception fl) {
Toast.makeText(getApplicationContext(),"First Try error "+fl,Toast.LENGTH_LONG).show();
}
/*// Depends on your web service
httppost.setHeader("Content-type", "application/json");*/
String result=null;
try {
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Toast.makeText(getApplicationContext(),"2 str\n "+result,Toast.LENGTH_LONG).show();
} catch (Exception sl) {
sl.printStackTrace();
Toast.makeText(getApplicationContext(),"2 err\n "+sl,Toast.LENGTH_LONG).show();
}
try{
String aa = "", b = "", c = "";
JSONArray ar = new JSONArray(result);
for (int i = 0; i < ar.length(); i++) {
JSONObject jo = ar.getJSONObject(i);
aa = jo.getString("uname");
b = jo.getString("address");
c = jo.getString("email");
}
nm.setText(aa);
addr.setText(b);
mail.setText(c);
Toast.makeText(getApplicationContext(),"3 wrk"+result,Toast.LENGTH_LONG).show();
}
catch (Exception tl){
Toast.makeText(getApplicationContext(),"3 err "+tl,Toast.LENGTH_LONG).show();
}
Strings separated by <br> are not a valid JSON array. PHP can create JSON strings using json_encode
If you need to read a JSON array in Android you need to echo a JSON array from PHP:
<?php
$email = $_POST["email"];
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("dtbse") or die(mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(mysql_error());
$result = array();
$res=[];
while ($y=mysql_fetch_array($x)) {
$res[] = [
$y["uname"],
$y["gender"],
$y["pass"],
$y["address"],
$y["email"]
];
}
echo json_encode($res); //Make PHP return a valid JSON response
Also, the error suppression operators may hide valuable debug infomation which may help you diagnose other problems.
If you instead prefer to pass the JSON object to Java then you can do the following (simpler) thing.
<?php
$email = $_POST["email"];
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("dtbse") or die(mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(mysql_error());
$result = array();
$res=[];
while ($y=mysql_fetch_array($x)) {
$res[] = $y;
}
echo json_encode($res); //Make PHP return a valid JSON response
I am trying to retrieve multiple rows of data. However, I am getting a error.
I want to retrieve rows of which the name (under the column name) = the name of the user. Which part of my code do I have to alter?
protected String doInBackground(String... args) {
// Building Parameters
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_coupons, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String couponexpires = c.getString(TAG_COUPONEXPIRES);
String coupondetails = c.getString(TAG_COUPONDETAILS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_COUPONEXPIRES, couponexpires);
map.put(TAG_COUPONEXPIRES, coupondetails);
// adding HashList to ArrayList
couponsList.add(map);
My php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
if (isset($_GET["name"])) {
$name= $_GET['name'];
$result = mysql_query("SELECT * FROM coupons WHERE name = '$name'") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["couponcreated"] = $row["couponcreated"];
$product["couponexpires"] = $row["couponexpires"];
$product["coupondetails"] = $row["coupondetails"];
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
My logcat
5202-5251/info.androidhive.loginandregistration E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
12-21 11:24:50.750 5202-5251/info.androidhive.loginandregistration W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x41b9f700)
12-21 11:24:50.755 5202-5251/info.androidhive.loginandregistration E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at info.androidhive.loginandregistration.CouponPageActivity$LoadAllProducts.doInBackground(CouponPageActivity.java:103)
at info.androidhive.loginandregistration.CouponPageActivity$LoadAllProducts.doInBackground(CouponPageActivity.java:76)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
There is syntax error in script(if condition not closed). use below script:
<?php
// array for JSON response
$response = array();
$response["success"] = 0;
$response["message"] = "No products found";
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
if (isset($_GET["name"])) {
$name = $_GET['name'];
$result = mysql_query("SELECT * FROM coupons WHERE name = '$name'") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["couponcreated"] = $row["couponcreated"];
$product["couponexpires"] = $row["couponexpires"];
$product["coupondetails"] = $row["coupondetails"];
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
$response["message"] = '';
} else {
// no products found
// echo no users JSON
}
}
echo json_encode($response);
?>
I have an error as stated in the title when trying to read SQL and encode it back to android.
I have tried the following:
Verified the value of $androidIMEI by printing to log file, value is returned as expected.
Verified the output of $sql and the query is OK (including the $_POST['myIMEI_toString']) value from android.
Verified the value of $json array, 2 arrays are returned as the query returns 2 rows from SQL, OK.
Replacing
$androidIMEI = isset($_POST['myIMEI_toString']) ? $_POST['myIMEI_toString'] : '';
WITH
$androidIMEI = "000000000000000" //works fine but I want to get that programmatically.
Code:
Android (Send IMEI):
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
myIMEI = mngr.getDeviceId();
myIMEI_toString = myIMEI.toString();
...............
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myIMEI_toString",myIMEI_toString));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://path_on_server/file.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
InputStreamReader ireader = new InputStreamReader(is);
BufferedReader bf = new BufferedReader(ireader);
sb = new StringBuilder();
String line = null;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
System.out.println("Error catch");
}
return id;
}
Android (JSON):
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("myarray");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Request_Name");
number = jsonChildNode.getString("Request_Number");
username = jsonChildNode.getString("Request_Username");
status = jsonChildNode.getString("Status");
arrName.add(name);
arrNumber.add(number);
arrUsername.add(username);
arrStatus.add(status);
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
PHP:
<?php
include 'config.php';
//$androidIMEI = "000000000000000";
$androidIMEI = isset($_POST['myIMEI_toString']) ? $_POST['myIMEI_toString'] : '';
//$f = fopen("log.txt", "w");
//fwrite($f, print_r($androidIMEI, true));
//fclose($f);
$con=mysql_connect("$servername", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$sql = "SELECT * from users WHERE Request='0' AND IMEI = '$androidIMEI' ";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['myarray'][]=$row;
}
}
else
{
//$error = "Error selecting record: " . $conn->error " ";
//$f = fopen("$error.txt", "w");
//fwrite($f, print_r($error, true));
//fclose($f);
}
$f = fopen("log.txt", "w");
fwrite($f, print_r($sql, true));
fclose($f);
mysql_close($con);
echo json_encode($json);
?>
Logcat Error:
org.json.JSONException: Value [] of type org.json.JSONarray cannot be converted to JSONObject
(i have asked this question before but will try again with more information)
i want to send all contacts with contact name and number in one row in one array in my android application like
john => "+92312xxxxxxx" ,
Right now i'm using namevaluepairs to post two arrays but it's not working like :
public class ContactList extends Activity {
public TextView outputText;
String phoneNumber = null;
String names = null;
String[] keyValue;
String[] kes;
int Count;
String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
outputText = (TextView) findViewById(R.id.textView1);
fetchContacts();
//Http connection
InputStream is=null;
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>(1);
for (int i = 0; i < Count ; i++)
{
nameValuePairs.add(new BasicNameValuePair("CN[]", keyValue[i]));
nameValuePairs.add(new BasicNameValuePair("names[]",kes[i]));
Log.i("Response", "you sent :" +kes[i]+" :"+ keyValue[i] + "\n ");
}
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.107/older/ContactList.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(ClientProtocolException e)
{
Log.e("ClientProtocol","Log_tag");
e.printStackTrace();
System.out.println("Excep: "+e);
}
catch(IOException e)
{
Log.e("Log_tag","IOException");
e.printStackTrace();
}
String result = "";
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");
}
reader.close();
is.close();
result=sb.toString();
Log.i("Response", "result "+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//result = "[{\"0\":\"Muhaimin\",\"1\":\"3\",\"2\":\"o+\"}]";
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
s= s +";"+ jArray.getString(i) + "\n";
}
}
catch (Exception e)
{
Log.e("Response", "error fetching indexes" + e);
}
String[] friends= s.split(";");
StringBuffer output = new StringBuffer();
for (int i = 0; i < friends.length; i++)
{
Log.i("List","Your friends namee"+friends[i]);
output.append("\n Your friend's number"+ friends[i]);
}
}
//Fetch Contacts
public void fetchContacts() {
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
//String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
// String DATA = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
Count = cursor.getCount();
if (cursor.getCount() > 0) {
keyValue= new String[Count];
kes= new String[Count];
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext())
{
int i=0;
String stu = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
phoneNumber +=":"+ stu;
names +=":" + name;
Log.i("List",stu + name +"\n" );
}
phoneCursor.close();
}
}
}
keyValue = phoneNumber.split(":");
kes = names.split(":");
Log.i("List","24th"+keyValue[23]);
Toast.makeText(getApplicationContext(), "99th "+keyValue[909] ,Toast.LENGTH_LONG).show();
}
PHP after receiving contacts will match them and return only those which have a match with database contacts. And then it returns contacts with names
i'm stuck with sending and receving part
Here is php code
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'verification');
define('DB_USER','root');
define('DB_PASSWORD','');
// 1. Create a database connection
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$PhoneNum= $_POST["CN"];
$i=0;
$j=0;
$friends = array();
$Invite = array();
unset ($PhoneNum[0]);
foreach ($PhoneNum as $i=> $element){
//or do whatever you need to do to that variable
$query="SELECT Number FROM `user` WHERE Number=$element";
$query_exec = mysqli_query($connection ,$query);
if (!$query_exec)
{ echo mysql_error(); }
ELSE {
if(mysqli_num_rows($query_exec)>0)
{
$friends["$j"]= $PhoneNum[$i];
$j++;
}
else
{
;
}}
}
echo (json_encode($friends));
?>
You'll get a URL now that would look like:
www.example.com/yourscript?CN[]=keyValue1&names[]=key1&CN[]=keyValue2&names[]=key2 etc.. going on untill your whole list has looped.
I doubt that is what your PHP script wants to receive, you probably want to send the POST for each time you increment the loop. But thats just conjecture untill you post more information/code.
Instead send a JSON array as the value of the nameValuePair and convert it to a PHP array using json_decode function in the server side.