How to make a post request to a PHP server - php

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

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 catch returned data if statement

I've been pulling my hair out to get this to work but no luck.
I have the below AJAX call;
$("#orderverify-form").submit(function(e) {
$('#loader').show();
e.preventDefault();
initiateCall();
});
function initiateCall() {
// Client side validation
if ($("#phone_number").val() == "") {
$('#loader').hide();
detError();
} else {
$.post("php/corder-verify.php", {
phone_number : $("#phone_number").val()
}, function(data) {
if (data.verification_code == 0) {
console.log(data.verification_code);
numberError();
} else {
console.log(data.verification_code);
showCodeForm(data.verification_code);
checkStatus();
}
}, "json");
}
}
My responses received from PHP are below;
Query successfull
// return verification code as JSON
$json = array();
$json["verification_code"] = $code;
header('Content-type: application/json');
echo(json_encode($json));
exit;
Query not successful
else {
// return verification code as JSON
$json = array();
$json["verification_code"] = 0;
header('Content-type: application/json');
echo(json_encode($json));
exit;
}
Code is just a rand number I'm generating. For failure I just set it to 0.
I never seem to be able to catch the error.
Only the else part of my AJAX if..else statement work :(
Help please.

Ajax call doesn't work from iPhone app and arduino

I've created an Arduino project wich sends the coordinates to an URL. The URL does some ajax calls. In the browser it works fine, but when I'm trying it with the Arduino it doesn't work. So I tried to do the same thing with an iOS app, but I got the same problem. This is the code on the page that the Arduino and iOS app request.
var directionsService = new google.maps.DirectionsService();
var base_url = window.location;
var received_data = <?php echo json_encode($received_data); ?>;
$.ajax({
url: 'http://gps-tracker.domain.nl/_api/handler.php',
data: { action: 'post', device_id: received_data['device_id']},
type: 'GET',
dataType:"jsonp",
jsonp:"callback",
success: function (response){
var error = [];
var total = response.length;
for (var type in response) {
if(response[type].types == 'area'){
var x = checkInsideCircle(response[type].longitude, response[type].latitude, received_data['longitude'], received_data['latitude'], response[type].reach / 1000);
if(x == false){
// Outside
error.push(true);
}else{
// Inside
error.push(false);
}
}else if(response[type].types == 'route'){
// Check route
checkOnRoute(response[type].start_latitude, response[type].start_longitude, response[type].end_latitude, response[type].end_longitude, response[type].type, response[type]['reach'], type, function(result) {
error.push(result);
if(error.length == total){
if(error.indexOf(false) >= 0){
// Device is inside route or area
outside = false;
}else{
// Send data to database
$.ajax({
url: 'http://gps-tracker.domain.nl/_api/handler.php',
data: { action: 'post', device_id: received_data['device_id'], longitude: received_data['longitude'], latitude: received_data['latitude']},
type: 'GET',
dataType: 'json',
success: function (response){
console.log('good');
},error: function(jq,status,message) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
}
}
});
}
}
},error: function(jq,status,message) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
Here is the code from the handler.php file, that the ajax request requests.
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : false;
// Switch actions
switch($action) {
case 'get':
$callback ='callback';
if(isset($_GET['callback'])){
$callback = $_GET['callback'];
}
$routes = ORM::for_table('gps_tracker_route')
->inner_join('gps_tracker_device', array('gps_tracker_device.device_id', '=', 'gps_tracker_route.device_id'))
->where('gps_tracker_route.device_id', $_GET['device_id'])
->where('gps_tracker_device.device_id', $_GET['device_id']);
if($routes = $routes->find_many()){
foreach($routes as $k=>$v){
$v = $v->as_array();
if($v['status'] == 'on' or strtotime(date('Y-m-d H:i:s')) > strtotime($v['start_time']) and strtotime(date('Y-m-d H:i:s')) < strtotime($v['end_time'])){
$response1[$k] = $v;
$response1[$k]['types'] = 'route';
}
}
}
$area = ORM::for_table('gps_tracker_area')
->inner_join('gps_tracker_device', array('gps_tracker_device.device_id', '=', 'gps_tracker_area.device_id'))
->where('gps_tracker_area.device_id', $_GET['device_id'])
->where('gps_tracker_device.device_id', $_GET['device_id']);
if($area = $area->find_many()){
foreach($area as $k=>$v){
$v = $v->as_array();
if($v['status'] == 'on' or strtotime(date('Y-m-d H:i:s')) > strtotime($v['start_time']) and strtotime(date('Y-m-d H:i:s')) < strtotime($v['end_time'])){
$response2[$k] = $v;
$response2[$k]['types'] = 'area';
}
}
}
if(isset($response1) and isset($response2)){
$response = array_merge($response1, $response2);
}elseif(isset($response1)){
$response = $response1;
}else{
$response = $response2;
}
if ( isset($response) ) {
if ( is_array($response) ) {
if (function_exists('json_encode')) {
header('Content-Type: application/json');
echo $callback.'(' . json_encode($response) . ')';
} else {
include( ABSOLUTE_PATH . '/classes/json.class.php');
$json = new Services_JSON();
echo $json->encode($response);
}
} else {
echo $response;
}
exit(0);
}else{
exit();
}
break;
case 'post':
$_GET['timestamp'] = date("Y-m-d H:i:s");
$record = ORM::for_table('gps_tracker_device_logging')->create($_GET);
$record->save();
$item = ORM::for_table('gps_tracker_device_logging')
->where('id', $record->id);
if($item = $item->find_one()){
$item = $item->as_array();
echo json_encode($item);
}
break;
default:
die('invalid call');
}
Can someone help me?
EDIT
I think it is something with Javascript. I don't know if it's possible to use javascript when a device, like Arduino, makes a http request to a server. Someone know?
I think that it's because you need a Web Browser that supports JavaScript.
I don't work with Arduino, but from what I know it does not have a "real" Web Browser - it can only pull/download data but can't execute the JS part.
For JS to work you need something to run it. That is why it works in a the browser.

Ajax request not giving output

I have created a .post() request
function validateLogin()
{
var username = $("#username").val();
var password= $("#password").val();
var details = {"name": username, "password": password};
console.log(details);
console.log(JSON.stringify(details));
$.post("getthedb.php", JSON.stringify(details), function(response)
{
if(response.code==0)
{
alert("Response: " + response.message);
$("#myDiv").innerHTML = response.message;
}
else
{
$("#myDiv").innerHTML = response.message;
}
}, "application/json");
}
getthedb.php
<?php
header('Content-type: application/json');
$jsonobj = file_get_contents("php://input");
$detail= json_decode($jsonobj);
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc"))
{
$response1['code']=0;
$response1['message']="Success";
}
else
{
$response1['code']=1;
$response1['message']="No Success";
}
$response = json_encode($response1);
echo $response;
?>
This is not giving back any result,'console.log(details)' and
'console.log(JSON.stringify(details))' produces the JSON object. how to debug this???
where am i lagging here.??
If you code doesn't provide some error i assume that your if down there isn't called and $response1 is empty. So no response to read.
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc")
{
$response1['code']=0;
$response1['message']="Success";
}
else ???
$response = json_encode($response1); // Response1 is empty
echo $response;
missing ) in if loop.
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc")
should be
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc"))
$response1 array not declared.
You haven't written else case

Jquery ajax parsing error for json

I am trying to send some data using php and jquery ajax using json datatype method.
Here is my code:
$("#username").on("keyup change keypress", function () {
var username = $("#username").val();
$.ajax
({
type: "POST", // method send from ajax to server
url: window.location.protocol + '//' + window.location.host + '/' + "admin/admins/user_exists",
data: {
username: username
},// Specifies data to be sent to the server
cache: false, // A Boolean value indicating whether the browser should cache the requested pages. Default is true
contentType: "application/json",
dataType: 'json', // The data type expected of the server response.
success: function (response_data_from_server) {
for (var key in response_data_from_server)
var result = response_data_from_server[key] + ""; // JSON parser
if (result == 'true') {
console.log("---------------- in true");
$("#username_alert").text("ERROR");
$('#username_alert').removeClass("alert-success");
$("#username_alert").css("visibility", "visible");
}
else {
if (result == 'false') {
console.log("---------------- in false");
$("#username_alert").text("NO ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').addClass("alert-success");
}
else {
if (result == 'empty') {
console.log("---------------- in empty");
$("#username_alert").text("ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').removeClass("alert-success");
}
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
and it always goes to an error function. The error that I receive is the following:
parsererror SyntaxError: Unexpected token  {}
My url location is correct and is indeed returning the correct json format. Here is my php code:
public function user_exists()
{
$username = $this->input->post("username");
$is_exists = "false";
$this->load->database();
if ($username != "")
{
$rows = $this->db->query("
SELECT * FROM `admins` WHERE `username` = '" . $username . "'
")->num_rows();
if ($rows > 0)
{
$is_exists = "true";
}
else
{
$is_exists = "false";
}
}
else
{
$is_exists = "empty";
}
$arr = array ('result' => $is_exists );
$response = json_encode($arr);
echo $response;
}
I've debugged it million times, the firebug sees the response as correct and expected json, however the client side seems to refuse to get it as a json respone, for what I believe.
Will appreciate any help!
...
header('Content-type: application/json');
echo $response;
Maybe you could use "header('Content-type: application/json');" before "echo"

Categories