Hello as i am new to flutter, i want to fetch data from php api to flutter app with json data which have multiple data's in one file
my flutter code
Future<Album> fetchAlbum() async {
final response = await http.post(
Uri.parse('https://domain/folder/api.php'),
body: jsonEncode({
"description": 'description',
"naw": "homeprod",
}),
);
if (response.statusCode == 200) {
// If the server did return a 201 CREATED response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 201 CREATED response,
// then throw an exception.
throw Exception('Failed to create.');
}
}
class Album {
//final int productid;
String description;
Album({this.description = ""});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
//productid: json['product_id'],
description: json['description'],
);
}
}
this my php code on server
if($postjson['naw']=="homeprod"){
$prod = array();
$query = mysqli_query($mysqli, "SELECT * FROM product order by rand() limit 30");
while($getpost = mysqli_fetch_array($query))
{
$prod[] = array(
'description' => $getpost['description']
);
}
if($query) $result = json_encode(array('success'=>true, 'prodlists'=>$prod));
else $result = json_encode(array('success'=>false));
echo $result;
}
always flutter return with Null data type with sub type string.
Thank you in advance
Related
I am a student studying Volley request.
There's an error that I can't solve, so I'm asking you to find a solution.
I don't understand why can't POST from Android to PHP at all.
It worked well in other situations, but not only in JsonArrayRequest.
I'll attach the code, so if there's any problem with my code, please let me know.
This is string request code in Android Studio
package kr.ac.castcommunity.cc.request
import android.util.Log
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.Response.success
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.StringRequest
import java.util.HashMap
import org.json.JSONObject
import com.android.volley.toolbox.JsonObjectRequest
import org.json.JSONArray
class CommentRequest(boardid : String , listener: Response.Listener<JSONArray>) :
JsonArrayRequest(Request.Method.POST, URL, JSONArray(), listener, Response.ErrorListener { error ->
Log.d("COMMENT ERROR", "Server Response FAIL: $error")
}) {
private val parameters: MutableMap<String, String>
companion object {
private val URL = "http://MyIP/cc/commentlist.php"
}
init {
parameters = HashMap()
parameters["boardid"] = boardid
Log.d("boardID :",boardid)
}
override fun getParams(): Map<String, String> {
return parameters
}
}
This is PHP code
(It works well if I randomly assign a variable.)
(But it doesn't work when I interlock it.)
<?php
$con = mysqli_connect("localhost", "root", "root", "cc");
mysqli_query($con, 'SET NAMES utf8');
$boardid = $_POST["boardid"]; // but It's not operating
//$boardid = "1"; // It's operating
$boardid = (int)$boardid;
$statement = mysqli_prepare($con, "select * from comment where boardid = ?");
mysqli_stmt_bind_param($statement, "i", $boardid);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $commentid, $boardid, $content, $writer, $date);
$response = array();
$response["success"] = false;
$result = array();
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["commentid"] = $commentid;
$response["boardid"] = $boardid;
$response["content"] = $content;
$response["writer"] = $writer;
$response["date"] = substr($date,10,-3);
array_push($result, array(
"success"=>$response["success"],
"commentid" => $response["commentid"],
"boardid" => $response["boardid"],
"content" => $response["content"],
"writer" => $response["writer"],
"date" => $response["date"]));
}
echo json_encode($result);
?>
D/COMMENTÂ ERROR: Server Response Fail: com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
and response code
val boardid = intent.getIntExtra("bnum", 0)
mCommentRecyclerView = comment_recyclerView
val responseListener = Response.Listener<JSONArray> { response ->
try {
Log.d("response", "comment response Start")
for (i in 0 until response.length()) {
val jobject = response.getJSONObject(i)
val success = jobject.getBoolean("success")
val boardid = jobject.getInt("boardid")
val commentid = jobject.getInt("commentid")
val content = jobject.getString("content")
val date = jobject.getString("date")
val writer = jobject.getString("writer")
if (success == true) {
mDatas.add(Comment(boardid, commentid, content, date, writer))
} else {
return#Listener
}
}
mAdpater = CommentAdapter(this, mDatas)
mCommentRecyclerView!!.adapter = mAdpater
mCommentRecyclerView!!.addItemDecoration(BoardDecoration(20))
val lm = LinearLayoutManager(this)
lm.reverseLayout = true
lm.stackFromEnd = true
mCommentRecyclerView!!.layoutManager = lm
mCommentRecyclerView!!.setHasFixedSize(true)
val decoration = DividerItemDecoration(this, LinearLayoutManager.VERTICAL)
mCommentRecyclerView!!.addItemDecoration(decoration)
} catch (e: JSONException) {
e.printStackTrace()
}
}
val commentRequest = CommentRequest(boardid.toString(), responseListener)
val queue = Volley.newRequestQueue(this#DetailActivity)
queue.add(commentRequest)
I really don't know why. I need your help.
Through your error message. I think there is a problem with the conversion of String to JsonObject.
You can print out the response from the server first, and then print out the conversion parameters.
I think the error appears in the for loop code below. Please check if the error is caused by the <br> tag.
Log.d("response", "comment response Start")
for (i in 0 until response.length()) {
val jobject = response.getJSONObject(i)
val success = jobject.getBoolean("success")
val boardid = jobject.getInt("boardid")
val commentid = jobject.getInt("commentid")
val content = jobject.getString("content")
val date = jobject.getString("date")
val writer = jobject.getString("writer")
println(jobject)
println(success)
println(boardid)
println(commentid)
println(content)
println(date)
println(writer)
if (success == true) {
mDatas.add(Comment(boardid, commentid, content, date, writer))
} else {
return#Listener
}
}
I am creating an app similar to those from online stores
I did an ArrayList for products added to the shopping cart.
How I must do to send this into my PHP script and add this to MySQL database.
I tried return count of my ArrayList elements, but I can't.
This is PHP code:
<?php
$postedArray = $_POST["arrayToPOST"];
$response = array();
if(isset($postedArray))
{
$count = count($postedArray);
$response["Count"] = $count;
$response["postedArray"] = $postedArray;
}
else
{
$response["Count"] = 0;
$response["postedArray"] = "ERROR ON POST";
}
echo json_encode($response);
?>
This is my function in Android app:
val arrayList: ArrayList<String> = ArrayList<String>()
arrayList.add("First value")
arrayList.add("Second value")
arrayList.add("Third value")
val gson = GsonBuilder()
.setLenient()
.create()
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl("http://192.168.100.11/")
.build()
val webAPIInterface = retrofit.create(WebAPIInterface::class.java)
var call = webAPIInterface.postData(arrayList)
call.enqueue(object : Callback<ResponsePOJO> {
override fun onFailure(call: Call<ResponsePOJO>?, t: Throwable?) {
Log.e("MainActivity", "Retrofit 2 ERROR: "+t.toString())
}
override fun onResponse(call: Call<ResponsePOJO>?, response: Response<ResponsePOJO>?)
{
Log.v("MainActivity", "RESPONSE: "+response!!.body().toString())
if(response!!.isSuccessful)
{
Log.v("MainActivity", "Response is successful")
Log.v("MainActivity", "")
}
else
{
Log.e("MainActivity", "Response isnt successful")
}
}
})
I looking for solution in internet, but I found nothing.
Please help !
I use the Vtiger webservice with its different methods CRUD, login ... etc. I created a task via the Calendar module, it worked well, but when I want to delete it does not work.
If I'm not mistaken, I need to have the object's id (so Calendar) in order to delete it. So I do:
public static function getTaskUser($user)
{
$idUser = self::getUserAccountId('XXXX');
$vtiger = new VtigerWS();
$connect = $vtiger->getConnection();
if ($connect && $connect['success'] == true) {
$response = $vtiger->query("id", "Calendar", "parent_id = '$idUser' ORDER BY id");
if ($response['success'] == false) {
$result = $response['error'];
} else {
$result = array();
foreach ($response['result'] as $task) {
$result[] = $task['id'];
}
}
} else {
$result = $connect['error'];
}
$vtiger->logout();
return $result;
}
==> In this function, I first look for the user id in vtiger (the user who was assigned to the previously created task). It works well.
But when the query is running:
($ vtiger-> query ("id", "Calendar", "parent_id = '$ idBaz' ORDER BY id");)
I get an error:
"code" => "DATABASE_QUERY_ERROR"
"message" => "Database error while performing requested operation"
The connection is good, I tried a query SELECT * FROM Calendar it does not work either ... I do not see where the error can come from.
My alamofire request is coming back as a failure when i print the response in xcode however, the web service is actually performing this and everything is supposed to happen as it should apart from the fact its coming back as a failure
Alamofire.request(BASE_URL + "index.php/feed/like", method: .post, parameters: parameters, headers: headers).responseJSON { response in
let result = response.result
debugPrint(response)
print(result)
if (result.value != nil) {
let json = JSON(result.value!)
print(json)
if json["status"] == false {
showError(type: "generic")
} else {
let nolikes = Int(self.lblLikes.text!)! + 1
self.lblLikes.text = String(nolikes)
self.actionLike.image = UIImage(named: "ActionLiked")
}
}
}
this is my error
[Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 1." UserInfo={NSDebugDescription=Invalid value around character 1.}))
[Timeline]: Timeline: { "Request Start Time": 509902187.696, "Initial Response Time": 509902188.176, "Request Completed Time": 509902188.177, "Serialization Completed Time": 509902188.177, "Latency": 0.480 secs, "Request Duration": 0.480 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.481 secs }
and this is my php function in codeigniter
function like_post()
{
$post = $this->_post_args;
$post = $this->security->xss_clean($post);
$like = $this->Feed_model->likePost($post);
if($like == TRUE) {
$this->set_response([
'status' => TRUE,
'message' => 'SUCCESS'
], REST_Controller::HTTP_ACCEPTED);
} else {
$this->set_response([
'status' => FALSE,
'error' => 'ALREADY_LIKED'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
public function likePost($post)
{
$postid = $post['post_id'];
$userid = $post['user_id'];
$query = $this->db->query("SELECT * FROM `post_likes` WHERE `user_id` = '{$userid}' AND `post_id` = '{$postid}'");
if($query->num_rows() > 0) {
return false;
} else {
$insert = [
'user_id' => $userid,
'post_id' => $postid
];
$this->db->insert('post_likes', $insert);
$currpost = $this->db->query("SELECT * FROM `posts` WHERE `post_id` = '{$postid}'");
$likes = $currpost->likes;
$update = ['likes' => $likes + 1];
$this->db->update('posts', $update, "post_id = '{$postid}'");
return true;
}
}
the code will return false if the user has already performed this action so if i first click on the action it will come back as failure in the console but the php script will run inserting everything to the database etc however, if i click it again i will get the php failure response (so the request shows as successful but it failed)
I have a php file that i connect to it with ajax and callback value is JSON
when i get data from php it dosnt show and when alert data i see Object
Where is my problem ?
PHP:
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])){
$query = mysql_query("select * from tab");
for ($i=0;$i<mysql_num_rows($query);$i++){
while($row = mysql_fetch_assoc($query)){
$title['t'][i] = $row['title'];
$title['d'][i] = $row['description'];
}
}
echo(json_encode($title));
exit();
?>
JS:
$('#button').click(function(){
$.ajax({
url : "test2.php",
data : $("#tab"),
type : "GET",
success : function(b){
b = eval('('+ b +')');
console.log((b['t']));
alert(b);
}
});
});
How can i get all of data from this JSON and show me corect it ?
Here's a full working example with single row fetch and multi row fetch, without using mysql_ syntax and using prepared statements to prevent sql injections.
And yes, DON'T use mysql specific syntax, like I mentioned here: I cant get the form data to go into database. What am I doing wrong?
function example()
{
var select = true;
var url = '../scripts/ajax.php';
$.ajax(
{
// Post select to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'select' : select // the variable you're posting.
},
success : function(data)
{
// This happens AFTER the PHP has returned an JSON array,
// as explained below.
var result1, result2, message;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
result1 = data[i].result1;
result2 = data[i].result2;
message = data[i].message;
// Do something with result and result2, or message.
// For example:
$('#content').html(result1);
// Or just alert / log the data.
alert(result1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
}
Now we need to receive the posted variable in ajax.php:
$select = isset($_POST['select']) ? $_POST['select'] : false;
The ternary operator lets $select's value become false if It's not set.
Make sure you got access to your database here:
$db = $GLOBALS['db']; // An example of a PDO database connection
Now, check if $select is requested (true) and then perform some database requests, and return them with JSON:
if($select)
{
// Fetch data from the database.
// Return the data with a JSON array (see below).
}
else
{
$json[] = array
(
'message' => 'Not Requested'
);
}
echo json_encode($json);
flush();
How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows.
Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)):
function selectMultipleRows($db, $query)
{
$array = array();
$stmt = $db->prepare($query);
$stmt->execute();
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
{
foreach($result as $res)
{
foreach($res as $key=>$val)
{
$temp[$key] = utf8_encode($val);
}
array_push($array, $temp);
}
return $array;
}
return false;
}
Then you can do something like this:
if($select)
{
$array = array();
$i = 0;
$query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
foreach(selectMultipleRows($db, $query) as $row)
{
$array[$i]["result1"] = $row['result1'];
$array[$i]["result2"] = $row['result2'];
$i++;
}
if(!(empty($array))) // If something was fetched
{
while(list($key, $value) = each($array))
{
$json[] = array
(
'result1' => $value["result1"],
'result2' => $value["result2"],
'message' => 'success'
);
}
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
Or, if you want to KISS (Keep it simple stupid):
Init a basic function which select some values from the database and returns a single row:
function getSingleRow($db, $query)
{
$stmt = $db->prepare($query);
$stmt->execute();
// $stmt->execute(array(":id"=>$someValue)); another approach to execute.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
$array = (
'result1' => $result['result1'],
'result2' => $result['result2']
);
// An array is not needed for a single value.
return $array;
}
return false;
}
And then fetch the row (or the single value) and return it with JSON:
if($select)
{
// Assume that the previously defined query exists.
$results = getSingleRow($db, $query);
if($results !== false)
{
$json[] = array
(
'result1' => $results['result1'],
'result2' => $results['result2'],
'message' => 'success'
);
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
And if you want to get the value of $("#tab") then you have to do something like $("#tab").val() or $("#tab").text().
I hope that helps.
I suggest to use either:
b = jQuery.parseJSON(data)
see more here
or
$.getJSON
instead of eval()