I am working in flutter app that connect to the phpMyAdmin. I have to check the phone number if it's found in the database or not found and it's works and the result "found" or not return into the debug console successfully. My problem is how can i connect the flutter to the result from php? if it's found i want to print a message and if it not show another message.
this is the php :
<?php
include "config.php"; // call connection
$err= array();
$phone_login = $_POST["login_phone"];
try{
$stmt = $connect->prepare("SELECT * FROM profile WHERE phone = ?");
$stmt->execute(array($phone_login));
$count = $stmt->rowCount();
}catch(PDOException $e){
echo $e-> getMessage();}
if($count > 0){
echo json_encode(array("status" => "found"));
}else{
echo json_encode(array("status" => "not found"));
}
?>
and this is the function in login.dart:
const String linklogin = "$linkServerName/checkphone.php";
JsonAPI _tst = JsonAPI();
login() async {
var response = await _tst.postRequest(linklogin, {
"login_phone": mobileNumTF_login.text,
});
if (response['status'] == "found") {
print("found");
} else {
print("not found");
}
}
How can i do an action in flutter app if i received the found and not found?
You can use a FutureBuilder, pass the login() future and display a Text() widget as follows:
FutureBuilder<String>(
future: login(),
builder: (
BuildContext context,
AsyncSnapshot<String> snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Text('Error');
} else if (snapshot.hasData) {
return Text(
snapshot.data,
style: const TextStyle(color: Colors.cyan, fontSize: 36)
);
} else {
return const Text('Empty data');
}
} else {
return Text('State: ${snapshot.connectionState}');
}
},
),
if (response.statusCode == 200){
}else {
print("______##################################_______");
print(
'Request failed with status: ${response.statusCode}.');
print("______##################################_______");
}
Related
so i have a login form where in iwant to show a error message if the account is not exsisting or the inputed account is incorrect. but the error message using snackbar is not showing.
here is my code for vue js.
const Login = Vue.component('login-view', {
data () {
return {
validate: {
login: false,
forgot: false
},
loading: {
login: false
},
form: {
email: null,
password: null
},
showPassword: false
}
},
computed: {
passField () {
var type = null
if (this.showPassword) {
type = 'text'
} else {
type = 'password'
}
return type
}
},
methods: {
signIn () {
if (this.$refs.login.validate()) {
this.loading.login = true
axios.post('./sql/login.php', this.form)
.then((res) => {
const data = res.data
console.log(data)
if(data) {
sessionStorage.setItem('uid', data.uid)
sessionStorage.setItem('displayName', data.displayName)
sessionStorage.setItem('email', data.email)
sessionStorage.setItem('type', data.type)
if (data.type === 'customer') { router.push('/'); location.reload() }
else if (data.type === 'seller') { router.push('/seller') }
}
this.loading.login = false
})/* Catching the error and displaying it in the console. */
.catch((error) => { console.log(error); this.$emit('snackbar', "incorrect"); this.loading.login = false })
}
}
},
here is my code for php
<?php
require_once("connection.php");
// Used to recognize JSON data posted by Axios.js
$data = json_decode(file_get_contents("php://input"), true);
//Check if the account exists
$sql = $handler->prepare("SELECT * FROM accounts WHERE email = ?");
$sql->execute(array($data['email']));
$count = $sql->rowCount();
// If account exists, its data will be fetched.
if($count === 1) {
$info = $sql->fetch(PDO::FETCH_OBJ);
$verified = password_verify($data['password'], $info->password);
// Checks if password entered matches the hashed password in account's data.
if ($verified) {
// Encodes initial account information as a JSON and sends it back.
$accountData = new \stdClass();
$accountData->uid = $info->uid;
$accountData->displayName = $info->fname . ' ' . $info->lname;
$accountData->email = $info->email;
$accountData->type = $info->type;
header("HTTP/1.1 200 OK");
/* Encoding the account data as a JSON and sending it back to the client. */
die(json_encode($accountData));
} else {
console_log(json_encode(array('message' => 'ERROR', 'code' => 2000)));
$error = 'Wrong email or password. Please try again.';
header('HTTP/1.1 500 Internal Server');
header('Content-Type: application/json; charset=UTF-8');
/* Sending a JSON object back to the client. */
die(json_encode(array('message' => 'ERROR', 'code' => 2000)));
}
die();
}
else {
$error = 'Account does not exists under this email. Please try again.';
}
die();
function console_log($output, $with_script_tags = true) {
$js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) .
');';
if ($with_script_tags) {
$js_code = '<script>' . $js_code . '</script>';
}
echo $js_code;
}
?>
here is the link to the website that i built. https://www.tailorshopthesis.online/tailorshop%20twofish/shop/#/sign-in
i hope some of you guys will help me. thanks
I'm setting up a rest-API on my server, and I want to update a table (i.e "comp_holding_stock"). but every time I test to post new data it returns "No item found"
Here is my controller
public function create_comp_holding_stock(){
$returnArr['status'] = '0';
$returnArr['response'] = '';
try {
if (!$this->input->post()) {
$returnArr['response'] = "Only POST method is allowed";
} else {
$holding_stock_data = array(
'comp_id' => $this->input->post('comp_id'),
'customer_id' => $this->input->post('customer_id'),
'quantity' => $this->input->post('quantity'),
'date' => date('Y-m-d H:i:s')
);
if (!isset($holding_stock_data)) {
$returnArr['response'] = "Some Parameters are missing";
} else {
$customer = $this->Customer->save_holding_stock($holding_stock_data);
if (!$customer) {
$returnArr['response'] = 'No items found';
} else {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
}
}
}
} catch (Exception $ex) {
$returnArr['response'] = "Error in connection";
$returnArr['error'] = $ex->getMessage();
}
$response = json_encode($returnArr, JSON_PRETTY_PRINT);
echo $response;
}
And here is my model below
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$success = $this->db->insert('comp_holding_stock', $holding_stock_data);
return $success;;
}
what am i doing wrong? what is the best approach to this scenarios
I would recommend try to check if you have load model in your controller.
And in your model try to do this.
public function save_holding_stock($holding_stock_data, $comp_id=FALSE)
{
if(!$comp_id == -1 || !$this->exists($comp_id))
{
if($this->db->insert('comp_holding_stock', $holding_stock_data))
{
$holding_stock_data['comp_id'] = $this->db->insert_id();
return TRUE;
}
return FALSE;
}
$this->db->where('comp_id', $comp_id);
return $this->db->update('comp_holding_stock', $holding_stock_data);
}
Try these changes in your code
In your controller,
$customer = $this->Customer->save_holding_stock($holding_stock_data);
$save_status = $this->db->affected_rows();
if ($save_status>0) {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
} else {
$returnArr['response'] = 'No items found';
}
In your model,
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$this->db->insert('comp_holding_stock', $holding_stock_data);
}
We are working on a car booking app to make it work with a PHP server. the mobile app is already using Signal R for real-time communication with a .NET server. we want to modify the code to connect to our PHP server.
My question is how can I connect this signal R code to communicate to a PHP server? How signal R will Work with a PHP server? Any solution for that?
Our primary aim is to make it work with signal R instead of switching to other solutions. Still, I would appreciate your recommendations.
Here is Java code that needs to communicate with PHP server
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Newtonsoft.Json;
using MyBuddyRide_APIs.Models;
using System;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using SortApp.ChatService;
using MyBuddyRide_APIs.Helper_Snippets;
using System.Data.Entity;
using MyBuddyRide_APIs.Enums;
using System.Collections.Generic;
namespace MyBuddyRide_APIs.ChatService
{
[HubName("brHub")]
public class PrivateChatHub : Hub
{
private MBRDbContext db = new MBRDbContext();
#region Internal Calls
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
public override Task OnDisconnected(bool stopCalled)
{
string connectionId = this.Context.ConnectionId;
User user = this.db.Users.Where(s => s.ConnectionId == connectionId).FirstOrDefault();
if (user != null)
{
user.ConnectionId = null;
this.db.SaveChanges();
}
else
{
var driver = this.db.Driver.Where(s => s.ConnectionId == connectionId).FirstOrDefault();
if (driver != null)
{
//get all the active vehicles, if any vehicle is not in progress, set vehicles status offiline
var veh = db.Vechicles.Where(s => s.Status == DriverStatus.InProgress || s.Status == DriverStatus.OnLine).FirstOrDefault();
if (veh != null)
{
if (veh.Status == DriverStatus.OnLine)
{
veh.Status = DriverStatus.OffLine;
RemoveDriver(driver.DriverId);
}
}
driver.ConnectionId = null;
this.db.SaveChanges();
}
}
return base.OnDisconnected(stopCalled);
}
#endregion
#region Rider Calls
[HubMethodName("goOnlineUser")]
public string GoOnlineUser(int userId)
{
try
{
if (userId > 0)
{
string connectionId = this.Context.ConnectionId;
User user = this.db.Users.Where(s => s.UserId == userId).FirstOrDefault();
if (user != null)
{
user.ConnectionId = connectionId;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
[HubMethodName("goOfflineRider")]
public string GoOfflineRider(long riderId, string token)
{
try
{
if (riderId > 0)
{
var user = this.db.Users.Where(s => s.UserId == riderId).FirstOrDefault();
if (user != null)
{
user.ConnectionId = null;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
[HubMethodName("getNearbyDriver")]
public string GetNearbyDriver(long userId, string token)
{
try
{
if (userId > 0 && token != null)
{
var user = db.Users.Where(s => s.UserId == userId && s.Token == token).FirstOrDefault();
if (user != null)
{
//get all the online drivers's location
var locations = db.Driver.Where(s => !s.InRide && s.ConnectionId != null && s.Vehicles.Where(e => e.Status == DriverStatus.OnLine).FirstOrDefault() != null).Select(s => new DriverLocationUpdate
{
bearing = s.Bearing,
driverId = s.DriverId,
lat = s.Latitude,
lon = s.Longitude
}).ToList();
return JsonConvert.SerializeObject(new HubResponse()
{
data = locations
});
}
else
{
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid User"
});
}
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
#endregion
#region Driver Calls
[HubMethodName("goOnlineDriver")]
public string GoOnlineDriver(long driverId, int vehicleId = 0)
{
try
{
if (driverId > 0)
{
string connectionId = this.Context.ConnectionId;
var user = this.db.Driver.Where(s => s.DriverId == driverId).FirstOrDefault();
if (user != null)
{
user.ConnectionId = connectionId;
db.Entry(user).State = EntityState.Modified;
if (vehicleId > 0)
{
//check if any vehicle was not in progress, then make it online
var veh = db.Vechicles.Where(s => s.VehicleId == vehicleId && s.Status != DriverStatus.InProgress).FirstOrDefault();
if (veh != null)
{
veh.Status = DriverStatus.OnLine;
}
}
db.SaveChanges();
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
[HubMethodName("updateLocation")]
public string UpdateDriverLocation(long driverId, int vehicleId, double latitude = 0.0, double longitude = 0.0, double bearing = 0.0)
{
try
{
if (driverId > 0 && vehicleId > 0)
{
var user = this.db.Driver.Where(s => s.DriverId == driverId && s.Vehicles.Where(x=>x.VehicleId == vehicleId).FirstOrDefault()!=null).FirstOrDefault();
if (user != null)
{
user.Latitude = latitude;
user.Longitude = longitude;
user.Bearing = bearing;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
//notify all the users who are not in ride
NewDriverLocation(new DriverLocationUpdate
{
driverId = user.DriverId,
bearing = bearing,
lat = latitude,
lon = longitude
});
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
[HubMethodName("goOfflineDriver")]
public string GoOfflineDriver(long driverId, int vehicleId = 0)
{
try
{
if (driverId > 0)
{
var user = this.db.Driver.Where(s => s.DriverId == driverId).FirstOrDefault();
if (user != null)
{
user.ConnectionId = null;
db.Entry(user).State = EntityState.Modified;
if (vehicleId > 0)
{
//put the online vehicle offline
var veh = db.Vechicles.Where(s => s.VehicleId == vehicleId && s.Status == DriverStatus.OnLine).FirstOrDefault();
if (veh != null)
{
veh.Status = DriverStatus.OffLine;
RemoveDriver(driverId);
}
}
db.SaveChanges();
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
#endregion
#region Chat Calls
[HubMethodName("getAllChats")]
public string GetAllChats(int rideId)
{
try
{
var ride = db.Rides.Where(s => s.RideId == rideId).FirstOrDefault();
if (ride == null)
{
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "Unknows Ride!"
});
}
var resp = db.PrivateChats.AsNoTracking().Where(e => e.Ride.RideId == rideId).AsEnumerable().Select(s => new HubChatMessage
{
message = s.Message,
rideId = rideId,
datetime = s.Time.ToString("MM/dd/yyyy HH:mm"),
sender = s.Sender
}).ToList();
HubResponse hubResponse = new HubResponse
{
data = resp
};
return JsonConvert.SerializeObject(hubResponse);
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
[HubMethodName("sendMessage")]
public string SendMessage(int rideId, string sender, string message, string datetime)
{
try
{
var ride = db.Rides.Include("User").Include("Driver").Where(s => s.RideId == rideId).FirstOrDefault();
if (ride != null)
{
if (ride.User == null || ride.Driver == null)
{
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "Invalid Ride Session!"
});
}
//receiver
string connectionId = null;
if (sender == "rider")
{
connectionId = ride.Driver.ConnectionId;
}
else
{
connectionId = ride.User.ConnectionId;
}
var newMessage = new HubChatMessage
{
datetime = datetime,
message = message,
sender = sender,
rideId = rideId
};
var privateChatMessage = new PrivateChatMessage
{
Message = message,
Time = DateTime.ParseExact(datetime, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture),
Sender = sender,
Ride = ride
};
db.PrivateChats.Add(privateChatMessage);
db.SaveChanges();
if (connectionId != null)
{
//call client side method.s
NewMessage(connectionId, newMessage);
}
else
{
if (sender != "rider")
{
//send push
SendPushNotifications push = new SendPushNotifications();
push.NotifyPerson(ride.User.UserId, message, "New Message", newMessage);
}
else
{
//send push
SendPushNotifications push = new SendPushNotifications();
push.NotifyDriver(ride.Driver.DriverId, message, "New Message", newMessage);
}
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
message = "message sent"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid message"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
#endregion
#region Ride Session
[HubMethodName("updateCaptainLocation")] //Captain's location who accepted the request will sync his location to rider
public string UpdateCaptainLocation(long rideId, double latitude = 0.0, double longitude = 0.0, double bearing = 0.0)
{
try
{
if (rideId > 0)
{
var userConnId = db.Rides.Where(s => s.RideId == rideId).Select(s => new
{
s.Driver.DriverId,
s.User.ConnectionId
}).FirstOrDefault();
if (userConnId != null)
{
if (userConnId.ConnectionId != null)
{
//notify rider
NewCaptianLocation(userConnId.ConnectionId, new DriverLocationUpdate
{
driverId = userConnId.DriverId,
bearing = bearing,
lat = latitude,
lon = longitude
});
}
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
#endregion
#region Client Side Invocations
private void NewMessage(string connectionId, HubChatMessage newMessage)
{
Clients.Client(connectionId).newMessage(JsonConvert.SerializeObject(newMessage));
}
//notify all the online users
private void NewDriverLocation(DriverLocationUpdate location)
{
var onlineUsers = db.Users.Where(s => s.ConnectionId != null && !s.InRide).Select(s => s.ConnectionId).ToList();
if (onlineUsers.Count > 0)
{
Clients.Clients(onlineUsers).newDriverLocation(JsonConvert.SerializeObject(location));
}
}
//notify the rider about his captian location.
private void NewCaptianLocation(string riderConnectionId, DriverLocationUpdate location)
{
Clients.Client(riderConnectionId).newCaptainLocation(JsonConvert.SerializeObject(location));
}
//notify users to remove driver from map as he's offline.
private void RemoveDriver(long driverId)
{
var onlineUsers = db.Users.Where(s => s.ConnectionId != null && !s.InRide).Select(s => s.ConnectionId).ToList();
if (onlineUsers.Count > 0)
{
Clients.Clients(onlineUsers).removeDriver(JsonConvert.SerializeObject(new
{
driverId = driverId
}
));
}
}
#endregion
#region Controller Helpers
/// <summary>
/// Helper function for Ride controller to remove the driver who have accepted the ride request
/// This pirtucular driver should not send his location to all users except the one who have requested him.
/// </summary>
/// <param name="driverId"></param>
/// <param name="onlineUsers"></param>
public static void RemoveDriverWhenInRide(long driverId,List<string> onlineUsers)
{
if (onlineUsers.Count > 0)
{
var hub = GlobalHost.ConnectionManager.GetHubContext<PrivateChatHub>();
hub.Clients.Clients(onlineUsers).removeDriver(JsonConvert.SerializeObject(new
{
driverId = driverId
}
));
}
}
#endregion
}
}
Im trying to convert some of my PHP functions to mongodb, but cant figure it out, could someone help me out?
PHP function applications:
function applications($gangId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `status`='avaliable' and `gangid`='$gangId'");
return ($applications ? $applications : false);
}
my attempt on function applications:
gangshema.methods.applications(thisid) {
// some sort of callback?
db.gang_applications.find({status:avaliable, gangid: thisid}, function(err, cursor) {
if (cursor != 0) {
console.log(cursor);
}
});
}
PHP function application_done
function application_done($applicationId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `id`='$applicationId'")->row();
return ($applications->status == 'avaliable' ? false : true);
}
my attempt on function application_done
gangshema.methods.application_done(applicationid) {
db.gang_applications.find({id:applicationid}, function(err,cursor) {
// return ($applications->status == 'avaliable' ? false : true);
});
}
but my main consern is a function called accept_applications. I have no clue on how to do this part, including calling other functions for their response.
function accept_application($userid,$applicationId) {
$box = 'failure';
if (empty($applicationId)) {
$message = "applicationId is empty";
} elseif ($this->application_done($applicationId)) {
$message = "Already registred!";
} else {
$application = $this->getApplication($applicationId);
$test = true;
if(!($test)) {
$message = "false test";
} else {
$this->db->query("UPDATE `gang_applications` SET `status`='accepted', `by`='$userid' where `id`='$applicationId'");
$this->gangs->add_member($application->userid,'gang','member',$application->gangid);
$message = "Accept!";
}
}
return $message;
}
Using this at the beginning of the Node.js script:
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
First snippet:
function applications($gangId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `status`='avaliable' and `gangid`='$gangId'");
return ($applications ? $applications : false);
}
becomes:
var findApplications = function(db, gangId) {
var cursor = db.collection('gang_application').find({
"status": "available"
"gangId": gangId
});
var results = [];
cursor.each(function(err, doc) {
if (err) console.log("Error: " + err);
} else if (doc != null) {
console.log("Null document.");
} else {
results.push(doc);
}
});
return results;
};
Second snippet:
function application_done($applicationId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `id`='$applicationId'")->row();
return ($applications->status == 'avaliable' ? false : true);
}
becomes:
function applications(gangId) {
db.gang_application
}
var applicationsDone = function(db, applicationId) {
var cursor = db.collection('gang_application').find({
"id": applicationId
});
var results = [];
cursor.each(function(err, doc) {
if (err) {
console.log("Error: " + err);
} else if (doc != null) {
console.log("Null document.");
} else {
results.push(doc.status);
}
});
return results;
};
Call both as follows:
MongoClient.connect(url, function(err, db) {
if (!db) {
console.log("Database did not connect.");
}
else {
findApplications(db, "102"); // Replace "102" with gangId
applicationsDone(db, "104"); // Replace "104" with applicationId
}
});
EDIT per comments, here's how to include a callback:
// Note extra `callback` parameter
var applicationsDone = function(db, applicationId, callback) {
var cursor = db.collection('gang_application').findOne({
"id": applicationId
});
cursor.each(function(err, doc) {
if (err) {
console.log("Error: " + err);
} else if (doc != null) {
console.log("Null document.");
} else {
return (doc.status == "available");
}
});
};
To call:
MongoClient.connect(url, function(err, db) {
if (!db) {
console.log("Database did not connect.");
}
else {
var callback = function(doc) { console.log(doc.status); };
applicationsDone(db, "104", callback);
}
});
EDIT Third snippet:
function accept_application($userid, $applicationId) {
$box = 'failure';
if (empty($applicationId)) {
$message = "applicationId is empty";
} elseif ($this->application_done($applicationId)) {
$message = "Already registred!";
} else {
$application = $this->getApplication($applicationId);
$test = true;
if(!($test)) {
$message = "false test";
} else {
$this->db->query("UPDATE `gang_applications` SET `status`='accepted', `by`='$userid' where `id`='$applicationId'");
$this->gangs->add_member($application->userid,'gang','member',$application->gangid);
$message = "Accept!";
}
}
return $message;
}
becomes this. Note some changes to the functions above to get this to work, such as returning an array of documents from applications, and using .findOne() for applicationDone():
function acceptApplication(userId, applicationId) {
if (!applicationId) return "No application ID";
if (applicationDone(db, applicationId)) return "Application already submitted.";
// Left out `if (!$test)`
db.gang_applications.update({
"id": applicationId,
"userId": userId
}, {
"status": "accepted"
}, upsert: false);
// $this->gangs->add_member($application->userid,'gang','member',$application->gangid);
return "Accepted!";
}
I have a function A which loads the data from db if the user has liked the image. I have another function B which loads the count for the total number of likes for the image. Both these functions return response using JSON.
If I call them individually, everything works fine, but if I call function B in function A, I get no JSON response and nothing happens although firebug does show two JSON arrays being outputted.
What is wrong with the code?
Function A:
public function loadLikes() {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $imageid, ':author' => $author);
$query->execute($params);
//calling function B
$this->countLikes($imageid);
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
if ($row['like'] == '1') {
$response = json_encode(array('like' => true));
echo $response;
return TRUE;
}
elseif ($row['like'] == '2') {
$response = json_encode(array('unlike' => true));
echo $response;
return TRUE;
}
else {
$error = "Invalid";
$response = json_encode(array('like' => false, 'text' => $error));
echo $response;
return FALSE;
}
}
}
else {
$response = json_encode(array('unlike' => true));
echo $response;
return FALSE;
}
}
catch(PDOException $ex)
{
echo json_encode(array('like' => false, 'text' => $ex));
return FALSE;
}
}
Function B:
public function countLikes($i) {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $i);
$query->execute($params);
if ($query->rowCount() > 0) {
$count = $query->fetchColumn();
$response = json_encode(array('count' => $count));
echo $response;
return TRUE;
}
}
catch(PDOException $ex)
{
return FALSE;
}
}
jQuery:
$.ajax({
type: "POST",
url: url,
data: postData,
dataType: "json",
success: function(data){
$(".count-like").show(600).text(data.count);
if(data.like) {
$("a#alike").attr('class', 'starred');
}
else if (data.unlike) {
$("a#alike").attr('class', 'unlike');
}
else {
alert(data.text);
}
}
});
If you invoke both functions, then each will output a JSON array. This will result in a HTTP response with following content:
{"like":1}{"count":2}
Both arrays would be valid separately. But if concatenated like this, it's no longer valid JSON.
Instead of outputting the json serialization with echo you should collect it in a temporary variable, merge the two arrays, and then output the combined array with a single:
echo json_encode(array_merge($countArray, $likeArray));
Example adaptions of your code
Function B should become:
public function countLikes($i) {
//sql query
try
{
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $i);
$query->execute($params);
if ($query->rowCount() > 0) {
$count = $query->fetchColumn();
/* JUST RETURN HERE */
return (array('count' => $count));
}
}
catch(PDOException $ex)
{
/* INSTEAD OF FALSE use an empty array,
which is interpreted as false in boolean context*/
return array();
}
}
Then when you call the function:
//calling function B
$countArray = $this->countLikes($imageid);
This will always be an array. Which you then can use in the output code:
$response = json_encode(array('like' => true) + $countArray);
(It's still inadvisable to have an echo right there. But too much code, too little context to propose a nicer rewrite. And if it works, ..)