I want to fetch data in my flutter app from my own PHP file where I did echo jsonEncode(object);
but it giving following error :
Error: XMLHttpRequest error.
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 906:28 get current
packages/http/src/browser_client.dart 71:22 <fn>
dart-sdk/lib/async/zone.dart 1612:54 runUnary
dart-sdk/lib/async/future_impl.dart 152:18 handleValue
dart-sdk/lib/async/future_impl.dart 704:44 handleValueCallback
dart-sdk/lib/async/future_impl.dart 733:13 _propagateToListeners
dart-sdk/lib/async/future_impl.dart 530:7 [_complete]
dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue
dart-sdk/lib/async/stream.dart 1219:7 <fn>
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14 _checkAndCall
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39 dcall
dart-sdk/lib/html/dart2js/html_dart2js.dart 37307:58 <fn>
at Object.createErrorWithStack (http://localhost:42101/dart_sdk.js:5347:12)
at Object._rethrow (http://localhost:42101/dart_sdk.js:39349:16)
at async._AsyncCallbackEntry.new.callback (http://localhost:42101/dart_sdk.js:39343:13)
my flutter code where is giving the error ..
getdata() async {
typesOfc = await http.get(Uri.parse("http://localhost:4545/"));
print(jsonDecode(typesOfc));
}
I'm using http plugin
my php code ..
if($action == 'fetchData'){
$fetchQuery = "SELECT `NAME` , `PASSWORD` FROM `REGISTER`";
$FetchResult = mysqli_query($connectLhost , $fetchQuery);
$data = array();
if($FetchResult->num_rows > 0){
while($row = $FetchResult->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
}else{
echo "Cant FetchData";
}
}
Related
I've successfully setup retrofit 2 in android studio. The app displays the following error when doing a GET request to the mysql database via the php file.
expected begin_array but was string at line 1 column 1 path $
I've tried rewriting the php file several times but its not been successfull. Please see my current php file below.
<?php
header('Content-Type: application/json');
include('conn.php');
$response = array();
//if(isset($_GET['1'])){
//$getid = $_GET['1'];
$read = "SELECT * FROM Cbt";
$result = $conn->query($read);
while ($row = $result->fetch_assoc()) {
$cbtLog = [
$userId = $row['userId'];
$moodBefore = $row['moodBefore'];
$automaticThought = $row['automaticThought'];
$distortions = $row['distortions'];
$challengeThought = $row['challengeThought'];
$alternativeThought = $row['alternativeThought'];
$moodAfter = $row['moodAfter'];
];
array_push($response, $cbtlog)
}
echo json_encode($response);
I would like the fix whatever the error is in the php file so that the results can be displayed on the android app. Please help me diagnose and fix the problem.
Got it working
<?php
include('conn.php');
enter code here
$query = "SELECT * FROM feelingFit_Cbt";
$result = mysqli_query($conn, $query);
$json_array = array();
while ($row = mysqli_fetch_assoc($result)){
$json_array[] =$row;
}
echo json_encode($json_array);
I'm using Factory in AngularJS, The Script is
app.factory('GetCountryService', function ($http, $q) {
return {
getCountry: function(str) {
// the $http API is based on the deferred/promise APIs exposed by the $q service
// so it returns a promise for us by default
var url = "https://www.bbminfo.com/sample.php?token="+str;
return $http.get(url)
.then(function(response) {
if (typeof response.data.records === 'object') {
return response.data.records;
} else {
// invalid response
return $q.reject(response.data.records);
}
}, function(response) {
// something went wrong
return $q.reject(response.data.records);
});
}
};
});
My Output Response Screen Shot:
My PHP Script:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$dbname = "xyzData";
$link = mysql_connect("localhost", "Super", "Super") or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $link) or die("Couldn't select database");
$uid = "";
$txt = 0;
$outp = "";
$data = file_get_contents("php://input");
$objData = json_decode($data);
if (isset($objData->token))
$uid = mysql_real_escape_string($objData[0]->token, $link);
else if(isset($_GET['uid']))
$uid = mysql_real_escape_string($_GET['uid']);
else
$txt += 1;
$outp ='{"records":[{"ID":"' . $objData->token . '"}]}';
echo($outp);
?>
I got error_log message is
[18-Mar-2016 21:40:40 America/Denver] PHP Notice: Trying to get
property of non-object in /home/sample.php
I tried both $objData->token and $objData->token[0]. But I got the same error notice. Kindly assist me...
I tried the Solution provided in the Post Notice: Trying to get property of non-object error, But it fails so, I raised 50 Bounty Points for this post. I tried to update my requirement in that post Question https://stackoverflow.com/review/suggested-edits/11690848, But the Edit was Rejected so I posted my requirement as a new Question. Kindly assist me...
The AngularJS is not sending any Object instead it passes the GET element.
Just access the Value by simply using $_GET['uid']
$objData doesn't seem to be an object.
try $objData['token'].
Or echo the object $objData and try to figure out what is its structure.
I have tried to get the image from gallery and upload the selected image to server using webservices in titanium.
I have used below code. But am getting the debug error : HTTP error And also it shows the alert box like "There was an error during the connection"
This code is working fine in my development server.But it is not working in my client server. What's the reason ? why my code is not working in my client server ?
The file upload is working fine when upload the file from android device.But it's not working while upload a file from iphone device.Can you please give me a idea to resolve this issue ?
Why am getting this error on my console window.
function AUF_ADD_File_FolderData () {
Titanium.Media.openPhotoGallery({
success:function(event) {
var request = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.API.info(this.responseText);
Ti.API.info("image pathe"+" "+event.media);
if(this.responseText == "Successfully file is created"){
var managefolders =Alloy.createController('manage_folders').getView();
managefolders.open();
}
else{
alert(this.responseText);
}
},
onerror: function(e){
Ti.API.debug(e.error);
alert("There was an error during the connection");
},
timeout:20000,
});
var uploadabc = event.media.imageAsResized(400 , 400);
request.open("POST",url+"client/manager/at_manager_create_common_file.php");
var params = ({"manager_id": manager_id,"file": uploadabc,});
// var params = ({"manager_id": manager_id,"file": event.media,});
request.send(params);
},
cancel:function() {
// called when user cancels taking a picture
},
error:function(error) {
// called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery:false,
// allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]
});
}
EDIT:
this is php file :
<?php
$request = base64_decode($_POST['jsondata']);
$data = json_decode($request,true);
$manager_id = $data['manager_id'];
$file_name = $data['file_name'];
$source = base64_decode($data['source']);
include "db_connect.php";
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("SELECT * from at_common_files WHERE user_id = '$manager_id' and file_name = '$file_name'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$response='{"Error":"1","Message":"Filename already existed"}';
echo $response;
} else {
$upload_dir = 'common_files/'.$manager_id."_".$file_name;
file_put_contents($upload_dir,$source);
$qugery = mysql_query("insert into at_common_files (user_id,file_name) values ($manager_id, '$file_name') ");
$response = '{"Error":"0","Message":"Successfully file is created"}';
echo $response;
}
?>
EDIT:
As am getting the below error :
: [DEBUG] HTTP error
: [INFO] IN ERROR {"type":"error","source":{"cache":false},"code":404,"error":"HTTP error","success":false}
if i have call the same url and pass a manager_id alone , am getting the results fine.if i have passing the manager_id and file, this time only am getting the Http error. i can't find a exact issue.Because the same titanium code and php code (development server)is working fine and the image is uploading to development server folder. but i have moved the same php file to my client server.now it is not working . also the same web service url is working fine in browser and android.it's not working in iphone only.so that exactly i can't find where is the issue ? can you please give me a solutions.
EDIT :
please refer the below link:
http://developer.appcelerator.com/question/174462/image-not-uploading-from-iphone#comment-224007
I have facing a exact same issue.could you please give me a solution.
i have found many questions like this (e.g. The 'Passive' connection '<appname>' access to protected services is denied).
the answer is always:
"This error is what's known as a "Red Herring". It's a clue that's misleading. The HID isn't a real error that affects your app. There should be other messages that may indicate what's going on."
so look if there is a other error massege which describes your problem.
for example try to escape the filename you are using within the sql statements:
$file_name = mysql_real_escape_string($data['file_name']);
Make sure your device is connected to the internet and then try it like this:
Titanium:
function AUF_ADD_File_FolderData () {
Titanium.Media.openPhotoGallery({
success:function(event) {
var xhr = Titanium.Network.createHTTPClient();
xhr.onerror = function(e){
Ti.API.info('IN ERROR ' + JSON.stringify(e));
alert('Sorry, we could not upload your photo! Please try again.');
};
xhr.onload = function(){
Ti.API.info(this.responseText);
Ti.API.info("image pathe"+" "+event.media);
if(this.responseText == "Successfully file is created"){
var managefolders =Alloy.createController('manage_folders').getView();
managefolders.open();
}else{
alert(this.responseText);
}
};
xhr.open('POST', url+"client/manager/at_manager_create_common_file.php");
xhr.send({
media: event.media,
manager_id: manager_id
});
},
cancel:function() {
// called when user cancels taking a picture
},
error:function(error) {
// called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery:false,
// allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]*/
});
}
PHP:
<?php
//this function returns a random 5-char filename with the jpg extension
function randomFileName()
{
$length = 5;
$characters = 'abcdefghijklmnopqrstuvwxyz';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string . '.jpg';
}
//create the random filename string and uploads target variables
$randomString = randomFileName();
$target = 'common_files/'.$randomString;
if(move_uploaded_file($_FILES['media']['tmp_name'], $target))
{
echo "success";
}
else
{
echo "moving to target failed";
}
?>
For more info check this link: http://code.tutsplus.com/tutorials/titanium-mobile-build-an-image-uploader--mobile-8860
If it works like this you will have to add your logic again (resizing and manager_id)
I have developing the one application using titanium.
Here the values are inserted successfully.But i didn't get the success message from webservices code.
I have using following code for insert a databaase :
In titanium side code :
function StaffRegistration(){
if($.staff_firstname.value != "" && $.staff_firstname.value != null){
var request = Ti.Network.createHTTPClient({
onload:alert(this.responseText),
onerror: function(e){
Ti.API.debug(e.error);
alert(this.responseText);
},
timeout:1000,
});
request.open("POST","xxx/xxx.php");
var params = ({"staff_firstname": $.staff_firstname.value,"staff_email": $.staff_email.value,"staff_password": $.staff_password.value,});
request.send(params);
}
else{
alert("Please enter the firstname");
}
Ti.API.info("Result for registration = " + this.responseText);
};
I have using a following php(webservice code) :
<?php
$request = base64_decode($_POST['jsondata']);
$data = json_decode($request,true);
$staff_firstname = $data['staff_firstname'];
$staff_email = $data['staff_email'];
$staff_password = md5($data['staff_password']);
include "db_connect.php";
$db = new DB_CONNECT();
$result = mysql_query("SELECT staff_email,staff_firstname from at_staff WHERE staff_email = '$staff_email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while($queryresult=mysql_fetch_array($result)) {
$uname[]=$queryresult['staff_firstname'];
$uemail[]=$queryresult['staff_email'];
}
if(in_array($staff_firstname,$uname) and in_array($staff_email,$uemail)) {
$response='{"Error":"1","Message":"Username and Email already exist"}';
echo $response;
} else if (in_array($staff_firstname,$uname)) {
$response='{"Error":"1","Message":"Username already exist"}';
echo $response;
} else {
$response='{"Error":"1","Message":"Email already exist"}';
echo $response;
}
} else {
$response='{"Error":"1","Message":"Successfully Registered"}';
echo $response;
$data=array("staff_firstname"=>"'".$staff_firstname."'",
"staff_email"=>"'".$staff_email."'",
"staff_password"=>"'".$staff_password."'"
);
echo $response;
}
?>
How can i get the $response in titanium from this webservice url.
#user2218667
Ti.API.info("Result for registration = " + this.responseText);
will NEVER work as you show in the first piece of code .
why ? because you send a request which will take like 1 seconde (for exemple), obviously, your programm won't wait 1 sec after
request.send(params);
i will continue the programm and when the request return a result, it will get into
onload(e) :
and here only you will be able to have your $result.
is this ok? well now, if this.responseData isn't effective, I don't have the solution .Can you check your line : "} else {" ,i supose there is a if above in the code? are you sure $result is defined upper?
Can you try the same request without titanium with a basic html form to be sure $result is write correctly in this case, like this, we will know if the problem come from php or from the link betwin php & titanium.
well , i supose it's asynchronous request, so the folowing may not work
Ti.API.info("Result for registration = " + this.responseText);
coud you try :
onload : function(e) {
Ti.API.info(this.responseText); // maybe Ti.API.info(this.reponsedata) according to your php.
},
onerror : function(e) {...
in my mind, if you receive JSON information (it trully look's like), you need
this.responseData //instead of this.responseText
I moved my files from my Xampp server over to a live server and now the PHP doesn't seem to be working correctly. This file is the problem
<?php
require ("../Android/connect.php");
require ("../Android/queries.php");
if ($query_run = mysql_query($questions_query)) {
if (mysql_num_rows($query_run) == NULL) {
$response["success"] = 0;
echo json_encode($response);
} else {
$response ['questions'] = array();
while ($row = mysql_fetch_assoc($query_run)) {
$info = array();
$info ['display_name'] = $row['display_name'];
$info ['field_type'] = $row['field_type'];
$info ['option_value'] = $row['option_value'];
array_push($response["questions"], $info);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
}
?>
My Android app that was getting JSON from this file now gets null JSONObjects. When I open it in my browser it gives me this error:
"Server error
The website encountered an error while retrieving http://mysite.com/Android/myfile.php. It may be down for maintenance or configured incorrectly."
My first thought was my connect.php or queries.php that are included were at fault. However they work fine. I can get them to display in my browser or echo out messages to me. The file above however will not work. Anyone know what the problem is?
if ($query_run = mysql_query($questions_query)) {
Be sure to define $questions_query- looks like that's your problem right there