echo posted json data in server php - worklight-adapters

The json sent to server php file as post request from ibm worklight Http adapter not accessible even after decoding:
Here are the codes:
Http adapter:
function storeRegistrationData(emailVal, passVal, fname1, gender, phone, userType, vehType) {
var credentials = JSON.stringify({jemailVal: emailVal, jpassVal: passVal, jfname1: fname1, jgender: gender, jphone: phone, juserType : userType, jvehType : vehType});
var input = {
method : 'post',
returnedContentType : 'json',
path : "/carbikepooling/index.php",
parameters: {credentials: credentials}
};
return WL.Server.invokeHttp(input);
}
Server php code:
$jsonObj = (isset($_POST['credentials']) ? $_POST['credentials'] : null);
$credentials = json_decode($jsonObj);
$email = $credentials->jemailVal;
$pass = $credentials->jpassVal;
$uname = $credentials->jfname1;
$gender = $credentials->jgender;
$phone = $credentials->jphone;
$usertype = $credentials->juserType;
$vehtype = $credentials->jvehType;
$boolean = false;
$userId; $userTypeId;
// sanitation, database calls, etc
$connection = mysqli_connect("localhost","root","","carbikepooling");
if (mysqli_connect_errno($connection))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connection,"insert into userInfo values(0,".$email.",'".$pass."','".$uname."','".$gender."','".$phone."')");
$result1 = mysqli_query($connection, "select u.userId from userInfo u order by u.userId desc limit 1");
if($result1){
$row1 = mysqli_fetch_row($result1);
$userId = $row1[0];
mysqli_query($connection,"insert into userType values(0,".$userId.",'".$usertype."')");
$result2 = mysqli_query($connection, "select t.userTypeId from userType t order by t.userTypeId desc limit 1");
if($result2){
$row2 = mysqli_fetch_row($result2);
$userTypeId = $row2[0];
mysqli_query($connection, "insert into vehicleType values(0,".$userTypeId.",'".$vehtype."')");
$boolean = true;
}
}
mysqli_close($connection);
$returnData[] = array(
'boolean' => "$boolean"
);
echo json_encode($returnData);
?>
Javascript code to show return result from server php:
function storeFormData(emailVal, passVal, fname1, gender, phone, userType, vehType){
var invocationData = {
adapter : 'registerUser',
procedure : 'storeRegistrationData',
parameters : [emailVal, passVal, fname1, gender, phone, userType, vehType]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : storeFormDataSuccess,
onFailure : storeFormDataFailure,
});
}
function storeFormDataSuccess(result){
WL.Logger.debug('Data stored Successfully');
alert(JSON.stringify(result.invocationResult));
}
function storeFormDataFailure(result){
WL.Logger.error('Error in storing Data');
}
What happens is that when I used decoded json data in server php file in the insert statements, nothing happens. I tried echoed values of email, gender, etc. but nothing prints as if they contain no values. However, if I sent the decoded json values of email, gender etc. in the returnData array as they are used in insert statements, values successfully received by the app which made the request, i.e: shown those values in the alert in the js code. Please solve this problem?

Hmm, that is strange. I copied and pasted your exact code and I was able to echo the variables that were passed from the Worklight adapter. Maybe the way you are trying to use the variables for your sql statements is wrong?
Can you change your mysql query to look something more like this?
mysqli_query($connection, "insert into vehicleType values(0, '$userTypeId','$vehtype')");
Notice how I've removed the concatenation '.' from the query and I now I just have the variables surrounded by single quotes.

Related

"Failed to issue Dequeue" when using Twilio Task Router for non-phone related tasks

NOTE: Code snippets below are functional. The "dequeue" error mentioned in this post was based on an existing Assignment Callback external to these scripts. Once the URL was removed and the reservation.dequeue moved to this code, the error was resolved.
We are in the process of developing a chat application using Conversations between two people. I currently have it "wired" up with the following steps when a user initiates the chat:
Conversation is created.
User is created.
User is added to the conversation.
Task is created with conversation meta-data in attributes.
(followed by steps on the other user's session to accept the reservation, etc.)
These steps work as expected, but a "40140 - Failed to issue Dequeue instruction due to missing 'call_sid' property" is generated since the task isn't an incoming phone call. I tried putting the task into the "SMS" Task Channel, but that didn't stop the error.
I couldn't find any specific documentation on creating non-phone call-based tasks so I might be setting up the task routing incorrectly.
Here are code snippets showing how I create (in .NET) the conversation, user, and task, and how I accept (in TaskRouter.js) the reservation.
/***********************************************************************************************************
This code is server-side in .NET
***********************************************************************************************************/
public ConversationCredentials CreateConversation( string program, string name )
{
var memberId = DateTime.Now.ToString( "yyyyMMdd" ); // Temporary
TwilioClient.Init( _twilioAccountSid,_twilioAuthToken );
// If we decide to keep conversations on Twilio, we should replace the memberid with phiid, since member id might change
var conversation = ConversationResource.Create(
friendlyName: memberId + "_" + DateTime.Now.ToString( "HHmmss" )
);
var conversationCredentials = JoinConversation( conversation.Sid, name );
var taskSid = CreateTask( program, conversation.Sid, memberId );
conversationCredentials.taskSid = taskSid;
return conversationCredentials;
}
public ConversationCredentials JoinConversation( string conversationSid, string name )
{
var identity = name + "_" + DateTime.Now.ToString( "HHmmss" ); // Makes sure the user is unique, in case it's an employee joining more than one chat session)
TwilioClient.Init( _twilioAccountSid,_twilioAuthToken );
var participant = ParticipantResource.Create(
pathConversationSid: conversationSid,
identity: identity
);
var user = UserResource.Update(
pathSid: identity,
friendlyName: name
);
var token = GetJWT( _twilioConversationServiceSid, name ); // Conversation Service Sid
var conversationCredentials = new ConversationCredentials();
conversationCredentials.token = token;
conversationCredentials.conversationSid = conversationSid;
conversationCredentials.participantSid = participant.Sid;
conversationCredentials.participantName = name;
conversationCredentials.participantIdentity = participant.Identity;
return conversationCredentials;
}
public string CreateTask( string program, string conversationSid, string memberId )
{
TwilioClient.Init( _twilioAccountSid, _twilioAuthToken );
var attributes = JsonConvert.SerializeObject( new Dictionary<string,Object>()
{
{"conversationSid", conversationSid },
{"memberId", memberId },
{"program", program },
{"call_sid", "CHAT" }
}, Formatting.Indented);
var task = TaskResource.Create(
attributes: attributes,
workflowSid: _twilioWorkflowSid,
pathWorkspaceSid: _twilioWorkspaceSid_Nurses,
taskChannel: "Default"
);
return task.Sid;
}
/***********************************************************************************************************
This code is browser-side using TaskRouter.js
NOTE: This handles both voice (works fine) and conversations (the part in question)
***********************************************************************************************************/
registerTaskRouterCallbacks( _this ) : void {
this.worker.on('ready', function(worker) {
_this.updateButton( worker.activityName, "" );
});
this.worker.on("reservation.created", function(reservation) {
if ( reservation.task.attributes.type != "CHAT" )
{
_this.updateButton( "Call", reservation.task.attributes.from.replace( "+1", "" ) );
reservation.dequeue();
} else {
_this.updateButton( "Chat", reservation.task.attributes.memberId );
confirm("You have an incoming chat!");
reservation.accept();
// This is where the chat window would pop-up
}
});
this.worker.on("reservation.accepted", function(reservation) {
_this.worker.update({"ActivitySid": _this.activitySids["Busy"][0].sid});
_this.updateButton( "Busy", "" );
});
The "dequeue" error mentioned in this post was based on an existing Assignment Callback external to these scripts. Once the URL was removed and the reservation.dequeue moved to this code, the error was resolved.

How do I set custom parameters for Twilio TVOCallInvite on iOS?

I'm trying to pass custom parameters in call invite structure but don't receive them on the recipient side.
let connectOptions: TVOConnectOptions = TVOConnectOptions(accessToken: token) { (builder) in
builder.params = ["To": "Recipeint Id",
"From": "Caller name"]
builder.uuid = uuid
}
self.call = TwilioVoice.connect(with: connectOptions, delegate: self)
Any ideas?
You need to add logic in backend or you can say server code for the same.
Link for server code in node
https://github.com/twilio/voice-quickstart-server-node
need to modify below function
function makeCall(request, response) {
// The recipient of the call, a phone number or a client
var to = null;
if (request.method == 'POST') {
to = request.body.to;
callerId = request.body.from; //--> new added line for caller name
} else {
to = request.query.to;
callerId = request.body.from; //--> new added line for caller name
}
const voiceResponse = new VoiceResponse();
if (!to) {
voiceResponse.say("Congratulations! You have made your first call! Good bye.");
} else if (isNumber(to)) {
const dial = voiceResponse.dial({callerId : callerNumber});
dial.number(to);
} else {
const dial = voiceResponse.dial({callerId : callerId});
dial.client(to);
}
console.log('Response:' + voiceResponse.toString());
return response.send(voiceResponse.toString());
}
also need make var instead of const for callerId variable , and If you are passing caller name then node code format should save value in this format
'client:callername'
i.e. client: and after that value which is being passed from iOS app
Gave up actually with this idea... Followed this instruction so that the app reports a call to CallKit and then updates the caller name after that.

Message: mysql_real_escape_string() expects parameter 2 to be resource, boolean given Filename: mysql/mysql_driver.php Line Number: 346

I am using the following code to select from a MySQL database with a Code Igniter webapp:
My Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class m_login extends CI_Model{
function __construct(){
parent::__construct();
}
public function validate(){
// grab user input
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$password = md5($password);
// Run the query
//$array = array('nip' => $this->db->escape_str($username), 'password' => $this->db->escape_str($password));
//$this->db->select('pegawai.NIP, akun.PASSWORD, akun.ROLE');
//$this->db->from('pegawai');
//$this->db->join('akun', 'akun.ID_PEGAWAI = pegawai.ID_PEGAWAI');
//$this->db->get_where('nip', $username);
//$this->db->where($array);
//$this->db->where('PASSWORD', 'd93591bdf7860e1e4ee2fca799911215');
//$query = $this->db->get();
$sql = "SELECT NIP, PASSWORD, ROLE FROM pegawai LEFT JOIN akun ON pegawai.ID_PEGAWAI=akun.ID_PEGAWAI WHERE pegawai.NIP=('".$this->db->escape_str($username)."') AND akun.PASSWORD=('".$this->db->escape_str($password)."')";
$this->db->query($sql);
//$query = $this->db->query("SELECT NIP, PASSWORD, ROLE FROM pegawai LEFT JOIN akun ON pegawai.ID_PEGAWAI=akun.ID_PEGAWAI WHERE pegawai.NIP='$username' AND akun.PASSWORD='$password'");
// Let's check if there are any results
//var_dump($this->db);
//var_dump($username);
if($query->num_rows == 1)
{
//If there is a user, then create session data
$row = $query->row();
$data = array(
'role' => $row->role,
'nip' => $row->nip,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
//If the previous process did not validate
//then return false.
return false;
}
}
?>
I have error like this
A PHP Error was encountered
Severity: Warning
Message: mysql_real_escape_string() expects parameter 2 to be resource, boolean given
Filename: mysql/mysql_driver.php
Line Number: 346
Backtrace:
File: C:\xampp\htdocs\simpeg\application\models\m_login.php
Line: 27
Function: escape_str
File: C:\xampp\htdocs\simpeg\application\controllers\login.php
Line: 26
Function: validate
File: C:\xampp\htdocs\simpeg\index.php
Line: 292
Function: require_once
Most likely, this is a syntax error, but I just can't figure out which part of my code is responsible.
I've also gone through the Queries section of the user guide of CodeIgniter, but it wasn't explained clearly there.
Can anyone please tell me where my mistake is, and what is the correct syntax for what I'm trying to do?

Dart lang, manipulating server returned JSON data in the client

I want to check the user log in parameters, and if the parameters accepted, I want the server to send back to the client both the name and roles of the user, to be saved in the SeassonStorage for further usages.
my server side code is:
....
....
var users = <Map>[];
var logged = <Map>[];
....
....
.then((_) {
for (var user in users)
if(_theData['userName']==user['Alias'] && _theData['password']==user['Password'])
{
userFound=true;;
logged.add({
"Alias":user['Alias'],
"Roles": user['Roles']
});
}
})
.then((_) {
if(userFound == true)
res.write(JSON.encode(logged));
else
res.write('sorry, unknown loggin');
res.close();
});
in the client side, I've:
....
....
if(request.responseText != 'sorry, unknown loggen'){
server_msg.innerHtml='Welcome';
print(request.responseText);
print(JSON.decode(request.responseText));
var FonixLogin = JSON.decode(request.responseText);
print(FonixLogin['Alias']);
print(FonixLogin['Roles']);
Storage sessionStorage = window.sessionStorage;
sessionStorage['FonixAlias'] = FonixLogin['Alias'];
sessionStorage['FonixRoles'] = FonixLogin['Roles'];
....
the output I get is:
[{"Alias":"Admin","Roles":"admin"}]
[{Alias: Admin, Roles: admin}]
Exception: Illegal argument(s): Alias login.dart:66login_Element.onData
Why mistake I made here, so that the returned data is not saved properly in the
FonixLogin is a List and you access it like a Map.
Try print(FonixLogin[0]['Alias']);

Node CSV Parser output issue

I am trying to use Node CSV Parser to read in a query result from my Mongo database and write it out to a csv file.
When I run my script, I get a csv file with two [object] entries on the first line and everything else blank.
This is my code:
// node samples/sample.js
var csv = require('csv');
var mongoose = require('mongoose');
var User = require('../models/userModel').User;
dsn = "mongodb://localhost/test";
mongoose.connect(dsn);
console.log ("here");
var users = User.find({}, function(err, result){
console.log(result);
});
var columns = ['userName','agencyName','email','password','id'];
csv()
.from(users, {
columns: true
})
.toPath(__dirname+'/users.csv',{
columns: ['userName','agencyName','email','password','id']
})
.transform(function(data){
data.unshift(data.pop());
return data;
})
.on('data',function(data,index){
console.log('#'+index+' '+JSON.stringify(data));
})
.on('end',function(count){
console.log('Number of lines: '+count);
})
.on('error',function(error){
console.log(error.message);
});
This is the data displayed in terminal:
[ { userName: 'LasVegas',
agencyName: 'City of Las Vegas',
email: 'lasvegas#gmail.com',
password: 'upload1',
_id: 4ffe2e6bddc0c02b15000001 } ]
I have only entered one user into the database so I believe it is correct.
Any help would be greatly appreciated!
EDIT:
Here is my code after trying to call csv in the callback:
// node samples/sample.js
var csv = require('csv');
var mongoose = require('mongoose');
var User = require('../models/userModel').User;
dsn = "mongodb://localhost/test";
mongoose.connect(dsn);
console.log ("here");
var columns = ['userName','agencyName','email','password','id'];
var users = User.find({}, function(err, result){
console.log(result);
if (err){
callback(err,null);
}else{
csv()
.from(users, {
columns: true
})
.toPath(__dirname+'/users.csv',{
columns: ['userName','agencyName','email','password','id']
})
.transform(function(data){
data.unshift(data.pop());
return data;
})
.on('data',function(data,index){
console.log('#'+index+' '+JSON.stringify(data));
})
.on('end',function(count){
console.log('Number of lines: '+count);
})
.on('error',function(error){
console.log(error.message);
})
}
});
Now instead of two [object] fields, the fields contain weird symbols and I am asked to choose a filter when opening the file.
Your call to User.find() is asynchronous; it's not assigning the results of the search to users. You need to move your call to csv into the callback and either replace the reference to users there with results or rename the callback parameter to users.

Resources