How to debug network API in flutter - php

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));

Related

Fetch data directly from php to flutter

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(),
);
}
},
)

How to make a post request to a PHP server

I know this is a duplicate question but I still need help with my code.
When I make a post request with postman it succeeds but when I use the flutter code it fails.
Any idea why?
So this is the flutter code to make the post request:
Future createQuote() async {
final response = await http.post(
Uri.parse('http://<myserver.com>/quotes/post.php'),
body: json.encode(
{
'quot': _quoteController.text,
'teller': _tellerController.text,
},
),
);
if (response.statusCode == 200 && response.body == 'success') {
print('s: ' + response.body);
// Navigator.pop(context);
} else {
print(response.body);
var test = jsonEncode(
{
'quot': _quoteController.text,
'teller': _tellerController.text,
},
);
print(test);
// throw Exception('Failed to create quote');
}
}
And this is the php file:
require_once('db.php');
$stm = $db->prepare("INSERT INTO quots (quot, teller) VALUES (:quot, :teller)");
$stm->bindParam(':quot', $_POST['quot']);
$stm->bindParam(':teller', $_POST['teller']);
$quot = $_POST['quot'];
$teller = $_POST['teller'];
if ($stm->execute()) {
echo "success";
} else {
echo "failure: ". $_POST['quot'] . $teller;
};
There is no need to jsonEncode the post body, use it as a plain Map.
final response = await http.post(
Uri.parse('http://<myserver.com>/quotes/post.php'),
body:
{
'quot': _quoteController.text,
'teller': _tellerController.text,
},
);

Continuously get PHP loop data in Ajax Call

I have this codes in process.php:
$users = $_POST['users']; // Sample: "user1, user2, user5"
$users = explode(', ', $users);
$step = 0;
foreach ($users as $r) {
$user_email = get_user_email($r); // Get email of each user
if (!empty($user_email)) {
send_w_mail(); // Send email to each user
$step++;
echo json_encode(
['step' => $step, 'all' => count($users)]
); // echo output
}
}
And this is my ajax call in index.php:
$("#send-message").click(function () {
$.ajax({
url: global_base_url + 'process.php', // global_base_url defined.
async : true,
type: 'POST',
data: {'users': input_users}, // input_users is val() of a input.
encoding: 'UTF-8',
success: function (data) {
data = $.trim(data);
if (data){
data = $.parseJSON(data);
var p_value = parseInt(data.step*100)/data.all;
set_progressbar_value(p_value); // set progressbar value. sample: 23%
}
}
});
});
This codes don't have any problem for execute and showing result.
But I want to Continuously get output json data from process.php in order to show process of each $step in Percent unit in a bootstrap process-bar;
I found some function like ignore_user_abort(), ob_clean() and ob_flush() but don't know how can I solve my problem with them.
How Can I do this? Please help me to solve the problem.
Thanks a lot.
There are two ways of approaching this problem
Websocket
Long polling
I will be describing the long polling method here:
$users = $_POST['users']; // Sample: "user1, user2, user5"
$users = explode(', ', $users);
$step = 0;
foreach ($users as $r) {
$user_email = get_user_email($r); // Get email of each user
if (!empty($user_email)) {
send_w_mail(); // Send email to each user
$step++;
echo json_encode(
['step' => $step, 'all' => count($users)]
); // echo output
//Flush the output to browser
flush();
ob_flush();
}
Jquery does not provide api for XMLHttpRequest.readyState == 3 (Loading docs here) so we need to use raw XMLHttpRequest object
$("#send-message").click(function () {
var prev_response = "";
var xhr = new XMLHttpRequest();
xhr.open("POST", global_base_url + 'process.php', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == 3) {
// Partial content loaded. remove the previous response
var partial_response = xhr.responseText.replace(prev_response,"");
prev_response = xhr.responseText;
//parse the data and do your stuff
var data = $.parseJSON(partial_response);
var p_value = parseInt(data.step*100)/data.all;
set_progressbar_value(p_value);
}
else if(xhr.readyState == 4 && xhr.status == 200){
set_progressbar_value(100);
console.log("Completed");
}
}
xhr.send("users="+ input_users);
});

Why do the responses of my new plugin not save?

So below are some of the actions that my plugin is supposed to perform when submitting the survey. On my console I should get 'response saved', but I get absolutely nothing, not even 'Could not save response'. I have looked through the code, but I can't see why ajax is not performing the function of saving the response. Can anyone else see what is going on here?
// 5.3
// hint: ajax form handler for saving question responses expects: $_POST['survey_id'] and $_POST['response_id']
function ssp_ajax_save_response() {
$result = array(
'status'=>0,
'message'=>'Could not save response.',
'survey_complete'=>false
);
try {
$survey_id = (isset($_POST['survey_id'])) ? (int)$_POST['survey_id']: 0;
$response_id = (isset($_POST['response_id'])) ? (int)$_POST['response_id']: 0;
$saved = ssp_save_response($survey_id, $response_id);
if($saved) {
$survey = get_post($survey_id);
if(isset($survey->post_type) && $survey->post_type = 'ssp_survey') {
$complete = true;
$html = ssp_get_question_html($survey_id);
$result = array(
'status'=>1,
'message'=>'Response saved!',
'survey_complete'=>$complete,
'html'=>$html
);
} else {
$result['message'].='Invalid survey.';
}
}
} catch(Exception $e) {
// php error
}
ssp_return_json($result);
}
// 5.4
// hint: saves single question response
function ssp_save_response($survey_id, $response_id) {
global $wpdb;
$return_value = false;
try {
$ip_address = ssp_get_client_ip();
// get question post object
$survey = get_post($survey_id);
if($survey->post_type == 'ssp_survey'):
// get current timestamp
$now = new DateTime();
$its = $now->format('Y-m-d H:i:s');
// query sql
$sql = "INSERT INTO {$wpdb->prefix}ssp_survey_responses (ip_address, survey_id, response_id, created_at) VALUES (%s, %d, %d, %s) ON DUPLICATE KEY UPDATE survey_id = %d";
// prepare query
$sql = $wpdb->prepare($sql, $ip_address, $survey_id, $response_id, $ts, $survey_id);
// run query
$entry_id = $wpdb->query($sql);
// If response saved successfully...
if($entry_id):
// return true
$return_value = true;
endif;
endif;
} catch(Exception $e) {
// php error
ssp_debug('ssp_save_response php error', $e->getMessage());
}
return $return_value;
}
Someone made me aware that I need to add the jQuery code and so here it is and thank you in advance.
jQuery(document).ready(function($){
// do something after jQuery has loaded
ssp_debug('public js script loaded!');
// hint: displays a message and data in the console debugger
function ssp_debug(msg, data) {
try {
console.log(msg);
if(typeof data !== "undefined") {
console.log(data);
}
} catch(e) {
}
}
// setup our wp ajax URL
var wpajax_url = document.location.protocol + '//' + document.location.host + '/wp-admin/admin-ajax.php';
// bind custom function to survey form submit event
$(document).on('submit', 'ssp-survey-form', function(e){
// prevent form from submitting normally
e.preventDefault();
$form = $(this);
$survey = $form.closest('.ssp-survey');
// get selected radio button
$selected = $('input[name^="ssp_question_"]:checked', $form);
// split field name into array
var name_arr = $selected.attr('name').split('_');
// get the survey id from the last item in name array
var survey_id = name_arr[2];
// get the response id from the value of the selected item
var response_id = $selected.val();
var data = {
_wpnonce: $('[name="wp_nonce"]', $form).val(),
_wp_http_referer: $('[name="wp_http_referer"]', $form).val(),
survey_id: survey_id,
response_id: response_id
};
ssp_debug('data', data);
// get the closest dl.ssp-question element
$dl = $selected.closest('dl.ssp-question');
// submit the chosen item via ajax
$.ajax({
cache: false,
method: 'post',
url: wpajax_url + '?action=ssp_ajax_save_response',
dataType: 'json',
data: data,
success: function(response) {
// return response in console for debugging...
ssp_debug(response);
// If submission was successful...
if(response.status) {
// update the html of the current li
$dl.replaceWith(response.html);
// hide survey content message
$('.ssp-survey-footer', $survey).hide();
} else {
// If submission was unsuccessful...
// notify user
alert(response.message);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// output error information for debugging...
ssp_debug('error', jqXHR);
ssp_debug('textStatus', textStatus);
ssp_debug('errorThrown', errorThrown);
}
});
});
});

Ajax call doesn't return data after echoed

The ajax call successfully update the record but doesn't return the string of echo. This script was working before but might be because of some upgrade it stops working. It is working fine on my local system but when I move it to bluehost server then it does not work.
Here is my Ajax call:
// call to ajax script to update site
function autopost_update_site() {
// get base directory url
var baseDir = jQuery('#baseDir').val();
var id = jQuery('#site_id').val();
var site_name = jQuery('#site_name').val();
var site_url = jQuery('#site_url').val();
var is_active;
if ( jQuery('#active_radio').is(':checked') ){
is_active = '1';
} else {
is_active = '0';
}
var username = jQuery('#login_username').val();
var login_pass = jQuery('#login_pass').val();
// call to ajax script to update script
jQuery.ajax( {
type: "POST",
url: baseDir + "/autopost_ajax_actions.php",
data: "id=" + id + "&site_name=" + site_name + "&site_url=" + site_url + "&is_active="+ is_active + "&username=" + username + "&login_pass="+login_pass +"&action=update_site",
beforeSend: function() {
jQuery('#update_site_button').attr("disabled", true);
// shortcode edit button
jQuery('#update_site_button').html('Updating...');
// admin page edit button
jQuery('#update_site_button').val('Updating...');
},
complete: function() {
jQuery('#update_site_button').attr("disabled", false);
// shortcode edit button
jQuery('#update_site_button').html('Update');
// admin page edit button
jQuery('#update_site_button').val('Update');
},
success: function(data) {
alert("Result: " + data); // NOTHING IS HAPPENING HERE, NO ALERT DATA
if (jQuery.trim(data) === "success") {
alert("Site updated.");
// refresh page
window.setTimeout('location.reload()', 200);
} else {
alert("Some error occured, Please try again.");
}
}
});
}
Here is my custom php script for ajax actions:
// update site
if ( $_POST['action'] == 'update_site' && isset ($_POST['id']) ) {
// collect site data
$site_name = $wpdb->escape($_POST['site_name']);
$site_id = intval($wpdb->escape($_POST['id']));
$site_url = $wpdb->escape($_POST['site_url']);
$username = $wpdb->escape($_POST['username']);
$login_pass = $wpdb->escape($_POST['login_pass']);
$is_active = $wpdb->escape($_POST['is_active']);
$query = $wpdb->prepare("UPDATE " . $autopost_sites_table_name . " SET site_name = %s, site_url = %s, username = %s, login_pass = %s, is_active = %s WHERE id = %s", $site_name, $site_url, $username, $login_pass, $is_active, $site_id);
#$log->LogDebug($query);
// execute query
$result = $wpdb->query($query);
#$log->LogDebug($result);
if ( $result !== FALSE || $result !== 0) {
// return success
$response = "success";
#$log->LogDebug($response);
echo $response; // THIS RESPONSE IS NOT SHOWING ON AJAX SUCCESS
} else {
$log->LogError("Failed to update site with ID: " . $_POST['id']);
echo "Failed to update site.";
}
}
Can anyone tell me what is missing?
Change data as follows
data:{
id:id,
site_name:site_name,
site_url:site_url ,
is_active:is_active ,
username:username,
login_pass:login_pass,
action:"update_site"
}
As It is mentioned that the script is working great on local but not working on server. So it was some server issue and I was getting error for "Access-Control-Allow-Origin" in chrome network.
I just added
header('Access-Control-Allow-Origin: *');
to my ajax action script and it worked! Thanks
after
echo $response;
put
die();
See http://codex.wordpress.org/AJAX_in_Plugins
In the example it says:
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}

Categories