Yii, already define index but `Undefined Index` - post

I have already properly defined the index to be POST-ed but still it says Undefined Index
Below is my code:
in the _form.php:
<?php echo $form->labelEx($model,'clientPackagedService_id'); ?>
<?php $client = Client::model()->findByPk(1);?>
<?php echo $form->dropDownList($model, 'clientPackagedService_id', CHtml::listData($client->clientPackagedservices(array('condition'=>'client_id='.$client->id.' AND booking_id IS NULL')),'id','packagedServiceInfo'),
array(
'disabled'=>'disabled',
'prompt'=>'Select Packaged Service...',
'ajax' => array( 'type'=>'POST', //request type
'url'=>CController::createUrl('updateMasseuseAndStationListPSID'), //url to call.
//This line-> 'data'=>array('clientPackagedService_id'=>'js:this.value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
'dataType'=>'json',
'success'=>'js:function(data) {
//alert(data.masseuse);
var mass="#'.CHtml::activeId($model, 'masseuse_id').'";
$(mass).html(data.masseuse);
$(mass).trigger("chosen:updated");
$(mass+"_chzn").css("width","300px");
$(mass+"_chzn > .chzn-drop").css("width","298px");
var station="#'.CHtml::activeId($model, 'station_id').'";
$(station).html(data.station);
$(station).trigger("chosen:updated");
$(station+"_chzn").css("width","300px");
$(station+"_chzn > .chzn-drop").css("width","298px");
//alert(data.timeEnd);
var timeEnd="#'.CHtml::activeId($model, 'timeEnd').'";
$(timeEnd).val(data.timeEnd);
}',
)
)
); ?>
in the controller.php:
public function actionUpdateMasseuseAndStationListPSID(){
$sid = Booking::getServices($_POST['clientPackagedService_id']);
....(codes to update Masseuse, Station, and TimeEnd.
}
in the model.php
public static function getServices($cpsID){
$psID = Yii::app()->db->createCommand('SELECT packagedService_id FROM client_packagedservice WHERE id='.$cpsID)->queryAll();
$sID = Yii::app()->db->createCommand('SELECT service_id FROM packaged_service WHERE id = '.$psID)->queryAll();
return $sID;
}
As you can see, I have already posted the appropriate name $_POST['clientPackagedService_id'] in the controller.php, but I still get the Error 500: Undefined index: clientPackagedService_id.
Did I do something wrong somewhere? Please advise. Thanks

I think problem is the data your are posting with ajax request. This is your data:
'data'=>array('clientPackagedService_id'=>'js:this.value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
Try to change it into this:
'data'=>array('clientPackagedService_id'=>'js:$(this).value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
Best way for debugging ajax request is to inspect browser's console. You can see ajax's posted data and realize your problem.

Related

How to handle my sms statuscallback in twilio using php laravel?

I saw an example in twilio: https://www.twilio.com/docs/sms/tutorials/how-to-confirm-delivery-php
<?php
$sid = $_REQUEST['MessageSid'];
$status = $_REQUEST['MessageStatus'];
openlog("myMessageLog", LOG_PID | LOG_PERROR, LOG_USER);
syslog(LOG_INFO, "SID: $sid, Status: $status");
closelog();
I don't know what the code above exactly do, but what I want is to save the data to my local database.
The code in my post method(my statuscallback):
public function smsStatusCallback(Request $request){
$sms = SmsChannel::create([
'number' => $request['MessageSid'],
'body' => $request['MessageStatus'],
]);
}
I've found a solution already. I saw the possible solutions in twilio debugger: "Double check that your TwiML URL does not ...". So I tried making it as a twiml
public function smsStatusCallback(Request $request){
$response = new Twiml();
$sms = SmsChannel::create([
'sid' => $request['MessageSid'],
'status' => $request['MessageStatus'],
]);
return response($response)
->header('Content-Type', 'text/xml');
}
I've added my route to api.php since the URL should be accessible by twilio.
Route::post('sms-status-callback','CommunicationController#smsStatusCallback');

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?

Redirecting a Call to a new Twiml URL

I am following the tutorial on https://www.twilio.com/docs/api/rest/change-call-state#post I am coding in php the portion that allows you to forward a current inbound call to a new Twiml URL. I am finding that in order for this to work, I have to specify a To and From parameter in the update array. I need the call forwarded to the URL specified not the number specified in the To parameter. However, the Twilio API throws an error that says the To parameter is required but the docs indicate that it is not. Is there something I am doing wrong here?
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('TwilioAPI/twilio-php-master/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = 'XXXXXXX';
$token = 'XXXXXXX';
$callSid = $_POST['CallSid'];
$client = new Services_Twilio($sid, $token);
// Get an object from its sid. If you do not have a sid,
// check out the list resource examples on this page
$call = $client->account->calls->get($callSid);
$call->update(array(
"Url" => "http://ftstoo.com/Phone/TheFinalTouchSecurity/forwardToBob.xml",
"Method" => "POST"
));?>
forwardToBob.xml contains a Response with a Say Verb.
This php code (not the twiml) throws the error
Uncaught exception 'Services_Twilio_RestException' with message 'No 'To' number is specified' in /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/TwilioAPI/twilio-php-master/Services/Twilio.php:297
If I add
"To" => "Some Ten Digit Phone Number",
"From" => "Some Ten Digit Phone Number",
to the array, the error is not thrown. The call is then directed to the "To" phone number. If the phone number specified in the "To" parameter answers, then the call is connected AND the twiml at forwardToBob.xml executes all at the same time.
EDIT # 3----------------------------------------------------------------------
Here is my entire code....
This is the Twiml that is executed everytime the Twilio verified number is called. I got this code from the Twilio quickstart site.
<?php
header('Content-type: text/xml');
$callerId = "+19012311158";
// put your default Twilio Client name here, for when a phone number isn't given
$number = "Bob";
// get the phone number from the page request parameters, if given
if (isset($_REQUEST['PhoneNumber'])) {
$number = htmlspecialchars($_REQUEST['PhoneNumber']);
}
// wrap the phone number or client name in the appropriate TwiML verb
// by checking if the number given has only digits and format symbols
if (preg_match("/^[\d\+\-\(\) ]+$/", $number)) {
$numberOrClient = "<Number>" . $number . "</Number>";
} else {
$numberOrClient = "<Client>" . $number . "</Client>";
}
?>
<Response>
<Dial callerId="<?php echo $callerId ?>">
<?php echo $numberOrClient ?>
</Dial>
</Response>
This is the client browser which I mostly copied from the Twilio quickstart site.
<?php
include 'TwilioAPI/twilio-php-master/Services/Twilio/Capability.php';
// put your Twilio API credentials here
$accountSid = 'XXXXXXXX';
$authToken = 'XXXXXXXX';
// put your Twilio Application Sid here
$appSid = 'XXXXXXXXXXXXX';
// put your default Twilio Client name here
$clientName = 'Bob';
// get the Twilio Client name from the page request parameters, if given
if (isset($_REQUEST['client'])) {
$clientName = $_REQUEST['client'];
}
$capability = new Services_Twilio_Capability($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$capability->allowClientIncoming($clientName);
$token = $capability->generateToken();
?>
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script type="text/javascript"
src="//static.twilio.com/libs/twiliojs/1.2/twilio.min.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<link href="http://static0.twilio.com/bundles/quickstart/client.css"
type="text/css" rel="stylesheet" />
<script type="text/javascript">
var callSid = "";
Twilio.Device.setup("<?php echo $token; ?>");
Twilio.Device.ready(function (device) {
$("#log").text("Client '<?php echo $clientName ?>' is ready");
});
Twilio.Device.error(function (error) {
$("#log").text("Error: " + error.message);
});
Twilio.Device.connect(function (conn) {
callSid = conn.parameters.CallSid;
$("#log").text("Successfully established call");
});
Twilio.Device.disconnect(function (conn) {
$("#log").text("Call ended");
});
Twilio.Device.incoming(function (conn) {
$("#log").text("Incoming connection from " + conn.parameters.From);
// accept the incoming connection and start two-way audio
conn.accept();
});
Twilio.Device.presence(function (pres) {
if (pres.available) {
// create an item for the client that became available
$("<li>", {id: pres.from, text: pres.from}).click(function () {
$("#number").val(pres.from);
call();
}).prependTo("#people");
}
else {
$("#" + pres.from).remove();
}
});
function call() {
// get the phone number or client to connect the call to
params = {"PhoneNumber": $("#number").val()};
Twilio.Device.connect(params);
}
function forward() {
var xmlhttp = new XMLHttpRequest();
params = "?CallSid=" + callSid + "&ForwardTo=" + document.getElementById("number").value;
xmlhttp.open("POST","forward.php" + params,false);
xmlhttp.send();
document.getElementById("log").innerHTML=xmlhttp.responseText;
}
function hangup() {
Twilio.Device.disconnectAll();
}
</script>
</head>
<body>
<button class="call" onclick="call();">
Call
</button>
<button class="hangup" onclick="hangup();">
Hangup
</button>
<input type="text" id="number" name="number"
placeholder="Enter a phone number or client to call"/>
<button class="call" onclick="forward();">
Forward
</button>
<div id="log">Loading pigeons...</div>
<ul id="people"/>
</body>
</html>
This is the forwarding code that is called via an HTTP POST request from my forward() function.
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('TwilioAPI/twilio-php-master/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = 'XXXXXX';
$token = 'XXXXXX';
$callSid = $_POST['CallSid'];
$client = new Services_Twilio($sid, $token);
// Get an object from its sid. If you do not have a sid,
// check out the list resource examples on this page
$call = $client->account->calls->get($callSid);
$call->update(array(
"Url" => "http://ftstoo.com/Phone/TheFinalTouchSecurity/forwardToBob.xml",
"Method" => "POST"
));
The first code snippet shows the Twiml that is executed when 901-231-1158 is called. It is then directed to the Client "Bob". Once the connection is successful, I press the forward button which I added in. This forward button calls the forward function which then makes an HTTP POST request to the PHP script which is the last snippet. Upon executing, if I do not have the "To" and "From" parameters specified in the array for the update function, I receive an error. Any suggestions on what I should try to fix this would help very much!
PLEASE NOTE: The button that I created in HTML is called Forward and it calls the function forward() which I created. I am getting the call Sid and saving it in an instance variable. I retrieve this value in the Twilio.Device.Connect function.
The full stack trace.
Stack trace:
#0 /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/TwilioAPI/twilio-php-master/Services/Twilio.php(180): Base_Services_Twilio->_processResponse(Array)
#1 /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/TwilioAPI/twilio-php-master/Services/Twilio/InstanceResource.php(31): Base_Services_Twilio->createData('/2010-04-01/Acc...', Array)
#2 /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/forward.php(22): Services_Twilio_InstanceResource->update(Array)
#3 {main}
thrown in /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/TwilioAPI/twilio-php-master/Services/Twilio.php on line 297
[12-Jun-2015 00:19:39 UTC] PHP Fatal error: Uncaught exception 'Services_Twilio_RestException' with message 'No 'To' number is specified' in /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/TwilioAPI/twilio-php-master/Services/Twilio.php:297
Twilio developer evangelist here.
Thanks for all the details, I managed to put together most of what you were trying to do in order to find the errors. I never received the error message you had though, so bare that in mind.
I found I had to change the following parts of your code to get this to work.
In your XHR request, stop trying to make the request synchronously (I was using Firefox and it was deprecated), just use:
xmlhttp.open("POST","forward.php" + params);
I was also not getting the call sid from the XHR request in my PHP, so I changed $_POST to $_REQUEST and that started to work.
Finally, the call sid on the client side is not the same as the originating call sid. That is the parent call and you can get hold of it like this using the twilio-php helper library:
$callSid = $_REQUEST['CallSid'];
$client = new Services_Twilio($sid, $token);
// Get an object from its sid. If you do not have a sid,
// check out the list resource examples on this page
$call = $client->account->calls->get($callSid);
$parentCall = $client->account->calls->get($call->parent_call_sid);
$parentCall->update(array(
"Url" => "http://ftstoo.com/Phone/TheFinalTouchSecurity/forwardToBob.xml",
"Method" => "POST"
));
You then need to update the parent call to forward it on to your original URL and hang up on the client side.
I hope this helps!

Youtube api Where will write this code

Too bad my php knowledge.I'm using YouTube-api.Where will write this code: Retrieve Youtube Channel info for "Vanity" channel
If you are talking about this line :
GET https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC6ltI41W4P14NShIBHU8z1Q&key={YOUR_API_KEY}
You are simply making a get request, you can use file_get_contents to get the response for you :
$response = file_get_contents("https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC6ltI41W4P14NShIBHU8z1Q&key={YOUR_API_KEY}");
Two notes :
You have to replace {YOUR_API_KEY} with the developer key. You can easily request one from youtube: http://code.google.com/apis/youtube/dashboard/
This is just an example in one line of code, I suggest you use a better approach for making this request like the following :
// Encode the parameters of the link
function encode_param($params) {
foreach ($params as $field => $value){
$encoded_params[] = $field . '=' . urlencode($value);
}
return $encoded_params;
}
// Get the response
function get_response($url) {
$response = file_get_contents($url);
// If error, send message back to the client
if ($response === false) {
exit("Couldn't get response from the api");
}
return $response;
}
$params = array(
"part" => "snippet,contentDetails,statistics",
"id" => "UC6ltI41W4P14NShIBHU8",
"key" => "-----------", // Your API key
);
$encoded_params = encode_param($params);
$request_url = "https://www.googleapis.com/youtube/v3/channels?".implode('&', $encoded_params);
$response = get_response($request_url);
//............

Why i don't see my #replies in conversation view in twitter?

I need to reply to one particular twitter status. I'm using following functions. And I've used Abraham's twitteroauth library in php.
public function replyToTwitterStatus($user_id,$status_id,$twitt_reply,$account_name)
{
$connection= $this->getTwitterConnection($user_id,$account_name);
try{
$responce = $this->postApiData('statuses/update', array('status' => $twitt_reply,'in_reply_to_status_id '=> $status_id),$connection);
}
catch(Exception $e){
echo $message = $e->getMessage();
exit;
}
}
// this function will handle all post requests
// To post/update twitter data
// To post/update twitter data
public function postApiData($request,$params = array(),$connection)
{
if($params == null)
{
$data = $connection->post($request);
}
else
{
$data = $connection->post($request,$params);
}
// Need to check the error code for post method
if($data->errors['0']->code == '88' || $data->errors['0']->message == 'Rate limit exceeded')
{
throw new Exception( 'Sorry for the inconvenience,Please wait for minimum 15 mins. You exceeded the rate limit');
}
else
{
return $data;
}
}
But the issue is that it is not maintaining the conversation view and it is update like normal status for e.g #abraham hello how are you. but that "View conversation" is not coming. Like expanding menu is not coming.
Please do needful
Thanks
You've got an unwanted space in your in_reply_to_status_id key which causes that parameter to be ignored.
This call:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id ' => $status_id
), $connection);
should look like this:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id' => $status_id
), $connection);
Also, make sure that the $status_id variable is being handled as a string. Although they look like numbers, most ids will be too big to be represented as integers in php, so they'll end up being converted to floating point which isn't going to work.
Lastly, make sure you have include the username of the person you are replying to in the status text. Quoting from the documentation for the in_reply_to_status_id parameter:
Note:: This parameter will be ignored unless the author of the tweet this parameter references is mentioned within the status text. Therefore, you must include #username, where username is the author of the referenced tweet, within the update.

Resources