Fetch data directly from php to flutter - php

I'm currently working on a Flutter project with php mysql as the backend. Is there anyway that I could possibly fetch data directly from php file? I'm so clueless.
For example, how do I fetch $dept from php file below and display it in a widget or store the data in Flutter:
<?php
session_start();
include_once ('config.php');
$lg_username = $_REQUEST['lg_username'];
$lg_password = $_REQUEST['lg_password'];
$lg_password = md5($lg_password);
$sql = "SELECT lg_username, lg_name, lg_dp_code FROM hr_login WHERE lg_username = '$lg_username' AND lg_password = '$lg_password'";
$res = mysqli_query($conn,$sql);
$userRow = mysqli_fetch_array($res,MYSQLI_ASSOC);
$user = $userRow['lg_username'];
$name = $userRow['lg_name'];
$dept = $userRow['lg_dp_code'];
$count = mysqli_num_rows($res);
if($count == 1){
return $dept;
}else{
echo json_encode("Error");
}
?>
Future _saveCheckIn()
Future _saveCheckIn() async {
var url = Uri.http(
"192.168.68.216", '/ump_attendance_2/save_check_in.php', {'q': '{http}'});
var response = await http.post(url, body: {
"lg_username": user.lg_username,
"lg_password": user.lg_password
});
//call the string data from php file
}
Thanks in advance.

You can use json_encode($dept) instead of $dept on the php side. After that, you can check data like below and return $dept data and use the futurebuilder.
Future _saveCheckIn() async {
var url = Uri.http(
"192.168.68.216", '/ump_attendance_2/save_check_in.php', {'q': '{http}'});
var response = await http.post(url,
body: {"lg_username": user.lg_username, "lg_password": user.lg_password});
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
print('Something wents wrong');
}
}
FutureBuilder(
future: _saveCheckIn(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
if (snapshot.hasData) {
return Text(snapshot.data);
}
return const Text('What do you want');
default:
return const Center(
child: CircularProgressIndicator(),
);
}
},
)

Related

How to debug network API in flutter

Please anyone help me to check the code. The web call is not made. I checked the future function is working well with the other working working code. Another doubt, can I use two http.post in a single future function? One to only post data not to get, and another one to use both post and get data.
Future<String> saveTime() async {
var usagetime = 5;
if (usagetime >= 0) {
var savetime = {
'user_id': 120,
'app_id': 1,
'usage_duration': 200,
};
var url2 =
'http://192.168.43.55:8080/php/save_usage_duration.php';
var response = await http.post(url2, body: savetime);
var message1 = jsonDecode(response.body.toString());
print(message1);
if (message1 == 'ok') {
Constants.prefsSaveTime.setInt("usage_time", 0);
Scaffold.of(context).showSnackBar(SnackBar(
content:
Text("Your previous usage time has been saved successfully."),
));
} else {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text(
"Previous data not saved, please inform AA Store developer."),
backgroundColor: Colors.redAccent,
duration: Duration(seconds: 5, milliseconds: 500),
));
}
}
}
And here is my PHP code
<?php
include ("includes/conn.php"); //$conn
include ("includes/datetime.php"); //$date $time
$user_id = $_POST["user_id"];
$app_id = $_POST["app_id"];
$usage_duration = $_POST["usage_duration"];
// $user_id = 120;
// $app_id = 1;
// $usage_duration = 5532;
$sql = "INSERT INTO `save_usage_duration`(`duration_id`, `user_id`, `app_id`, `usage_duration`, `usage_date`, `usage_entry_timing`) VALUES (' ','$user_id','$app_id','$usage_duration','$date','$time')";
if (mysqli_query($conn, $sql)) {
$success='ok';
echo json_encode($success);
} else {
$fail = 'fail';
echo json_encode($fail);
}
?>
You are sending a Map savetime which contain value of integers.
You should send a jsonObject in your body,
So use jsonEncode() to convert yoyr map to jsonObject
Replace this line
var response = await http.post(url2, body: savetime);
With
var response = await http.post(url2, body: jsonEncode(savetime));

Ajax response return undefined

Hi I have been using ajax for many times. But I can't figure out whats the problem with my code this time. My head is blowing up since 2 days. I am using pusher for the realtime notification in CodeIgniter. Here's my code.
$(document).on("click", ".myonoffswitch", function () {
if (confirm("Sure!!! You want to Change the post status?"))
{
var thiss = $(this);
var prod_id = $(this).attr('id');
var status = $(this).attr('value');
var tdid = $(this).parent().prev().attr('class');
var td = $(this).parent().prev();
var adsstatus = $.ajax({type: "POST", dataType: "json", url: base_url + 'init/ads_status', data: {'prod_id': prod_id, 'status': status}});
$.when(adsstatus).done(function (adsstatuss) {
var msg;
msg = adsstatuss;
alert(msg.length);
var updated_status = msg[0].post_status;
alert(updated_status);
//alert(updated_status);
if (updated_status == "0" && tdid == prod_id) {
td.css("background", "#ccffcc");
td.text("On");
thiss.val(updated_status);
}
if (updated_status == "1" && tdid == prod_id) {
td.css("background", "#ffcccc");
td.text("Off");
thiss.val(updated_status);
}
});
}
});
ads_status (method in CodeIgniter)
public function ads_status() {
$prod_id = $_POST['prod_id'];
$status = $_POST['status'];
if ($status == "1") {
$new_status = "0";
$this->cmsdbmodel->ads_status($prod_id, $new_status);
$dat = $this->cmsdbmodel->get_updated_status($prod_id);
$ads_type = "product";
$emailreturn = $this->send_email_ads_status($prod_id, $ads_type);
//send user alert of product//
if ($dat[0]->post_status == "0") {
$lastInsertedId = $prod_id;
$modelNBrandId = $this->dbmodel->checkProductContainsAlert($lastInsertedId);
$getAlertEmail = $this->dbmodel->getAlertEmailFromBrandNModelId($modelNBrandId);
if (!empty($getAlertEmail)) {
foreach ($getAlertEmail as $alerts) {
$alertsEmail = $alerts->email;
}
}
$alertsPost = $this->dbmodel->getPostAlerts($lastInsertedId);
$sendPostAlerts = json_encode($alertsPost);
$encrytpEmail = hash('sha256', $alertsEmail);
$this->pusher->trigger($encrytpEmail, 'alerts', $sendPostAlerts);
}
//send user alert of product//
$realtime = $this->realTime_charts();
$realtime["post_status"] = $dat[0]->post_status;
$realtime["emailres"] = $emailreturn;
$data = $realtime;
$this->pusher->trigger('recent_activity', 'new_event1', $data);
echo json_encode($data);
}
}
Here I want to trigger event in pusher as well as echo json object. But in ajax, response is undefined. Also in console I can see json but when alerting the reponse it says undefined. Wheres problem in my code. Please help me.

saving data from csv to php and mysql

I am trying to import all the data from csv to the database.
Below code is ajax request that is sent to a php file.
$('#upload_location_csv').click(function(e){
e.preventDefault();
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]});
fi = document.getElementById("csv_file_input").files[0];
reader = new FileReader;
reader.onload = function(){
csv_data = reader.result;
$.ajax({
type:"post",
url:ajax_root_path+'fend.php',
data:{
location_id:queryDict['id'],
csv_data:csv_data,
perform_action:"save_delivery_csv_data"
},
success:function(resObj){
window.location.reload();
},
error:function(resObj){
}
});
};
reader.readAsText(fi);
});
This is the action that is performed, where here is, save_delivery_csv_data .
When I click on import csv, the page reloads and no request is sent to fend.php.
case 'save_delivery_csv_data':
{
$location_id = $param_array['location_id'];
$csv_data = $param_array['csv_data'];
$csv_data_rows = explode("\n",$csv_data);
unset($csv_data_rows[0]);
$csv_data_rows = array_values($csv_data_rows);
debug($csv_data_rows);
$csv_data_array = array();
foreach ($csv_data_rows as $csv_row_key => $csv_row_value)
{
$csv_row_value_array = explode(",",$csv_row_value);
debug($csv_row_value_array);
if(count($csv_row_value_array) == 5)
{
/*$csv_data_array[$csv_row_key] = array();
$csv_data_array[$csv_row_key]['locality_id'] = $csv_row_value_array[0];
$csv_data_array[$csv_row_key]['locality_name'] = $csv_row_value_array[1];
$csv_data_array[$csv_row_key]['minimum_order_amount'] = $csv_row_value_array[2];
$csv_data_array[$csv_row_key]['delivery_time'] = $csv_row_value_array[3];
$csv_data_array[$csv_row_key]['delivery_charge'] = $csv_row_value_array[4];*/
//debug($csv_row_value_array);
if(isset_empty($csv_row_value_array[3]))
{
//debug($csv_row_value_array);
$locality_id = $csv_row_value_array[0];
$location_outletValues = array();
$location_outletValues['cloud_site_id'] = $cloud_site_id;
$location_outletValues['location_id'] = $location_id;
$location_outletValues['locality_id'] = $locality_id;
$location_outletValues['minimum_order'] = $csv_row_value_array[2];
$location_outletValues['delivery_time'] = $csv_row_value_array[3];
$location_outletValues['delivery_charge'] = $csv_row_value_array[4];
$sql = "SELECT outlet_locality_id FROM ".PLATFORM_OUTLET_LOCALITIES."
WHERE location_id='".$location_id."' AND locality_id='".$locality_id."'";
$outlet_locality_array = $DB->query($sql);
//debug($outlet_locality_array);
if(count($outlet_locality_array) > 0)
{
$condition_array = array();
$condition_array['outlet_locality_id'] = $outlet_locality_array[0]->outlet_locality_id;
//debug($condition_array);
debug($location_outletValues);
$DB->update(PLATFORM_OUTLET_LOCALITIES,$location_outletValues,$condition_array);
}
else
{
$DB->insert(PLATFORM_OUTLET_LOCALITIES,$location_outletValues);
}
}
}
}
break;
//debug($csv_data_array);
}
What am I missing out here?? I also tried debugging variables values, but no request was sent to fend.php, whereas other request on the same page are being successfully sent.

YUI-2 Datatable : Dynamic column definition with Server side AJAX pagination sorting

I am using the below code to create a YUI datatable with dynamic data(columns). But am facing a issue in server side pagination. As of now it is working fine with client side pagination, but I need server side pagination, so that my page loading time will get reduced. Can you help me on this to fix the issue. Since I'm struggling in this area for past 2 days.Server side pagination with AJAX to render the data is my expectation.
Here is the code I Used
DataProvider.prototype = {
url:null,
data:null,
ds:null,
getData:function() {return this.data},
initialize:function(){
var str = generateRequest();
var newUrl = this.url+str;
YAHOO.util.Connect.asyncRequest('GET', newUrl, this);
},
success:function(response){
var responseVal = YAHOO.lang.JSON.parse(response.responseText);
var columnList = responseVal.columnList;
var sortedBy = responseVal.sortedBy;
this.data = responseVal.results;
if(this.data == '') {
$('#dynamicdata').html('<font style="color:red;"> No Data Found!</font>');
} else {
this.ds = new YAHOO.util.FunctionDataSource(function(){return this.dataProvider.getData()});
this.ds.responseSchema = {
resultsList:"results",
fields:columnList,
// Access to values in the server response
metaFields: {
totalRecords: "totalRecords",
startIndex: "startIndex"
}
}
this.ds.dataProvider = this;
// DataTable configuration
var myConfigs = {
paginator: new YAHOO.widget.Paginator({ rowsPerPage:20 }), // Enables pagination
width:"80%", height:"auto"
};
// FORMATTING CELL COLOUR BASED ON THEIR VALUES
var myCustomFormatter = function(elLiner, oRecord, oColumn, oData) {
var columnKey = oColumn.getKey();
var frmCurrentPeroid = $('#from').val();
//var frmCurrentPeroid = '2013-03-13';
var defaultLabels = ['Product type','Total 1','Total 2','Change'];
if (isDate(columnKey) && $.inArray(columnKey, defaultLabels) === -1) {
if(columnKey < frmCurrentPeroid) {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
} else {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
}
} else {
if(columnKey == 'Total 1') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Total 2') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Change') {
split_data = oData.toString().split('_');
var fieldData = null;
var fieldFormatter = null;
fieldData = split_data[0];
fieldFormatter = split_data[1];
if(fieldFormatter == 'green') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'green');
elLiner.innerHTML = fieldData;
}
if(fieldFormatter == 'red') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'red');
elLiner.innerHTML = fieldData;
}
}
else if(columnKey == 'Product Name') {
var filterStr = oData.substring(0,30);
elLiner.innerHTML = ''+filterStr+'';
//alert('blue');
}
else {
elLiner.innerHTML = oData;
}
}
};
// Add the custom formatter to the shortcuts
YAHOO.widget.DataTable.Formatter.myCustom = myCustomFormatter;
//YAHOO.widget.DataTable.formatLink = formatLink;
/* make call to initialize your table using the data set */
var myDataTable = new YAHOO.widget.DataTable("dynamicdata", columnList, this.ds, myConfigs);
}
}
}
Followed the code posted in this page
Click here
Thanks in Advance,
Raja
I haven't been doing YUI2 for quite some time so I am no longer able to help you directly. Perhaps this example can help: http://www.satyam.com.ar/yui/#ServerDriven . I do remember that there were big changes in 2.6 and this examples are marked 2.4, perhaps they no longer work.

passing a javascript variable to a php function and quoting it correctly

Im using Zend Framework ..in one of my phtml file's i have this code
<script>
function foobar(id,type){
var idarray = <?php AppNamespace_General::getparentids( ?>id, type<?php ) ?>; // here the id and type are from js
//the php function returns a json array to the js variable
......
location.href = baseurl +'/somepage/id/'+id;
}
How can i correctly pass the js elements to the php function
The php function(Already thought of doing it via ajax..its quite complex)
public static function getparentids($id, $type, $elmarray = '') {
if (empty($elmarray)) { //avoiding redeclaration of array
$elmarray = array();
}
switch (strtolower($type)) {
case 'group':
case 'product':
case 'specification':
$gp_handler = new PackAssist_Model_DbTable_Groups();
$q = "SELECT * FROM t_groups WHERE group_id = $id";
$sql = $gp_handler->getAdapter()->query($q);
break;
case 'part':
$pt_handler = new PackAssist_Model_DbTable_Parts();
$q = "SELECT * FROM t_parts WHERE part_id = $id";
$sql = $pt_handler->getAdapter()->query($q);
break;
}
$result = $sql->fetchAll();
$i = 0;
if (count($result) > 0) {
foreach ($result as $row) {
if (isset($row['group_parent_id']) && $row['group_parent_id'] != 0) {
if (in_array($row['group_id'], $elmarray)) {
$e = $row['group_parent_id'];
} else if ($row['group_parent_id'] != 0) {
$e = $row['group_id'];
}
} else if (isset($row['part_group_id'])) {
$e = $row['part_group_id'];
} else if ($row['group_parent_id'] == 0) {
break;
}
if (isset($e) && !empty($e)) {
array_push($elmarray, $e);
}
self::getparentids($e, 'group', $elmarray);
$i++;
}
} else {
array_push($elmarray, $id);
}
array_pop($elmarray); //removing the group of super parent group which we dont need
if ($i == 0) { // just encode the array only once
echo json_encode(array_reverse($elmarray));
}
}
If you use jQuery, you can do the following to execute the JSON request:
$.ajax({
type: 'GET',
url: '/path/to/script.php',
data: '{ id: '+id+', type: '+type+' }',
contentType: 'application/json',
dataType: 'json',
success: function(data) {
dataObject = JSON.parse(data);
// process data
},
error: function(e) {
console.log(e.message);
}
});
You can use your existing PHP code with this solution. The url you point to would just have to print the JSON result, as you are currently doing in getparentids().

Categories