Get a return value from http.post - angularjs

My question is the following I have this code here:
$http.post("dologin", data).then(function(resposta)
When I give a console.log (response.data) it returns the following:
string(40) "7f9870111b7c032f6203d144c97b8aa5a3e3f0c5"
{"status":"success","type_user":"secretary"}
I need to get the "status" value. Before I was using the following and it worked fine
if (response.data.status === 'success') {
if (answer.data.type_user === 'teacher') {
$ location.path ('teacher_view');
} else if (response.data.type_user === 'candidate') {
$ location.path ('candidate_view');
} else if (answer.data.type_user === 'secretary') {
$ location.path ('secretaria_view');
}
Now it does not work anymore and when I give console.log (response.data.status); it returns undefined
My backend php
public function do_login(){
$this->load->model('LoginM');
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
$cpf = trim($data->cpf);
$senha = trim($data->senha);
$tipo = trim($data->tipo);
$response = $this->LoginM->do_login($cpf, $senha, $tipo);
if ($response["status"] === "success"){
if ($tipo == 'admin') {
$data = array(
'logged_in' => true,
'cod_user' => $response["cod_user"]
);
$message = array("status"=>"success", "tipo_user"=>"secretaria");
}elseif ($tipo == 'professor') {
$data = array(
'logged_in' => true,
'cod_professor' => $response["cod_professor"]
);
$message = array("status"=>"success", "tipo_user"=>"professor");
}elseif ($tipo == 'candidato') {
$data = array(
'logged_in' => true,
'cod_candidato' => $response["cod_candidato"]
);
$message = array("status"=>"success", "tipo_user"=>"candidato");
}
$this->session->set_userdata($data);
}else{
$message = array("status"=>"error","message"=>"CPF ou senha incorretos");
}
echo json_encode ($message);
}
Test with response from console.log (response.data) and console.log (response.data.status)
Image console.log

Below thing should do the trick:
var state = JSON.parse('{'+res.data.split("{")[1]);
if (state.status === 'success') {
if (state.type_user === 'teacher') {
$ location.path ('teacher_view');
} else if (state.type_user === 'candidate') {
$ location.path ('candidate_view');
} else if (state.type_user === 'secretary') {
$ location.path ('secretaria_view');
}
But, i would strongly suggest you to fix your server response from string which you are getting right now, to the JSON which you were getting earlier

Related

TypeError: Cannot read property 'user' of undefined. I dont know what to do

static description = 'Get information on a mentioned user.';
static usage = '<#user|id>';
static names = ['userinfo', 'ui'];
static userPerms = [];
static botPerms = [];
async execute(client, message) {
var permissions = [];
var acknowledgements = 'None';
const args = this.message.content.trim().split(/ +/g);
var user = this.message.mentions.users.first() || this.message.author;
const member = this.message.mentions.members.first() || this.message.guild.members.cache.get(args[0]) || this.message.member;
const randomColor = "#000000".replace(/0/g, function () { return (~~(Math.random() * 16)).toString(16); });
if(this.message.member.hasPermission("KICK_MEMBERS")){
permissions.push("Kick Members");
}
if(this.message.member.hasPermission("BAN_MEMBERS")){
permissions.push("Ban Members");
}
if(this.message.member.hasPermission("ADMINISTRATOR")){
permissions.push("Administrator");
}
if(this.message.member.hasPermission("MANAGE_MESSAGES")){
permissions.push("Manage Messages");
}
if(this.message.member.hasPermission("MANAGE_CHANNELS")){
permissions.push("Manage Channels");
}
if(this.message.member.hasPermission("MENTION_EVERYONE")){
permissions.push("Mention Everyone");
}
if(this.message.member.hasPermission("MANAGE_NICKNAMES")){
permissions.push("Manage Nicknames");
}
if(this.message.member.hasPermission("MANAGE_ROLES")){
permissions.push("Manage Roles");
}
if(this.message.member.hasPermission("MANAGE_WEBHOOKS")){
permissions.push("Manage Webhooks");
}
if(this.message.member.hasPermission("MANAGE_EMOJIS")){
permissions.push("Manage Emojis");
}
if(!permissions.length == 0){
permissions.push("No Key Permissions Found");
}
if(this.member.user.id == message.guild.ownerID){
acknowledgements = 'Server Owner';
}
const embed = new Discord.MessageEmbed()
.setDescription(`<#${member.user.id}>`)
.setAuthor(`${member.user.tag}`, member.user.displayAvatarURL)
.setColor(randomColor)
.setFooter(`ID: ${message.author.id}`)
.setThumbnail(member.user.displayAvatarURL)
.setTimestamp()
.addField("Status",`${status[member.user.presence.status]}`, true)
.addField('Joined at: ',`${moment(member.joinedAt).format("dddd, MMMM Do YYYY, HH:mm:ss")}`, true)
.addField("Created at: ",`${moment(message.author.createdAt).format("dddd, MMMM Do YYYY, HH:mm:ss")}`, true)
.addField("Permissions: ", `${permissions.join(', ')}`, true)
.addField(`Roles [${member.roles.cache.filter(r => r.id !== message.guild.id).map(roles => `\`${roles.name}\``).length}]`,`${member.roles.cache.filter(r => r.id !== message.guild.id).map(roles => `<#&${roles.id }>`).join(" **|** ") || "No Roles"}`, true)
.addField("Acknowledgements: ", `${acknowledgements}`, true);
this.message.channel.send({embed});
}
}
**I have tried to define user but it's not working. error:
TypeError: Cannot read property 'user' of undefined.
Whenever i used ,userinfo it's not responding anything. I don't know why this happend, but if you find any other error in the code, can you help me fix it too? Thank you.
but that didn't do anything to help.
What am i missing here?**
this.member.user.id
Should be
member.user.id
Look for “something”.user for errors like that. Then figure out why the something is undefined.

save the record of bulk sms sent into db laravel

i have taken the id and mobile_num from users table.i have to insert that id name in this table as user_id,mobile_num,and status(0,1) into another table(wc_sms_status).sendSMSFunction is working fine.
public function SendBulkSms()
{
$usersNumber = User::select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
}
elseif($userNumber->mobile_num == exist && status == 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
}
else{
}
}
}
Do this :
public function SendBulkSms()
{
//assuming there is a relationship between your model users and wc_sms_status called wcSmsStatus
$usersNumber = User::with('wcSmsStatus')->select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
'user_id' => $userNumber->id,
'mobile_num' => $userNumber->mobile_num,
'status' => 1,
]);
} elseif ($userNumber->mobile_num && $userNumber['wcSmsStatus']->status === 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
} else {
}
}
}
public function SendBulkSms()
{
$users = User::select('id','mobile_num')
->whereIn('id', [5,6,7,8])
->whereNotNull('mobile_num')
->get();
$bulkData = [];
foreach ($users as $user)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
$bulkData[] = [
'user_id' => $user->id,
'mobile_num' => $user->mobile_num,
];
}
if (!empty($bulkData)) {
WcSmsStatus::insert($education); // change to your model name
unset($bulkData);
}
}
try to use in this way, it will insert bulk data, dont fergot to mention protected $fillable[] in model

How to apply datatable filter when my table is passed from js?

I have js code which gets results from a query and pastes table to a div.So table is created in js and set with js.how do I apply datatables filter in such a case?
if you are using ajax request filter ,So url parameter filter may help :
for example :
This is your ajax get request url :
$.get(root_url+'index/user?id='+id+'&name='+name+'&gender='+gender, function(response){
console.log(response);
});
And this how you can caught those parameter in cakephp
public function user(){
if ($this->request->is('ajax')) {
$id = $this->request->getQuery('id');
$name = $this->request->getQuery('name');
$gender = $this->request->getQuery('gender');
$condition = [];
if ($id){
$condition = ['Users.id' => $id];
}
if (name) {
$condition = ['Users.name' => $name];
}
if (gender) {
$condition = ['Users.gender' => $gender];
}
$user = $this->Users->find()
->select([
'Users.id',
'Users.name',
'Users.gender',
'Users.create_date',])
->where(condition);
response = ['user' => $user];
return $this->response->withType('application/json')
->withStringBody(json_encode($response));
} else {
return $this->redirect(['controller' => 'pages','action' => 'error404']);
}
}

How to stop any particular service in laravel 5.2?

If I want to upload 3 file into server then I just select 3 files.
then called 3 services like :
1 something/api/uploadFile (uplodaing first file)
2 something/api/uploadFile (uplodaing second file)
3 something/api/uploadFile (uplodaing third file)
Now my question is how can cancel only second service (stop second file to upload into server)?
I am using Angular js for frontend
HTML Code :
<button type="button" ngf-select="uploadFiles($files)" ng-model="files" ngf-model-invalid="invalidFiles" ngf-model-options="modelOptionsObj" ngf-multiple="true" ngf-pattern="pattern" ngf-accept="acceptSelect" ngf-capture="capture" ngf-drag-over-class="dragOverClassObj" ngf-validate="validateObj" ngf-resize="resizeObj" ngf-resize-if="resizeIfFn($file, $width, $height)" ngf-dimensions="dimensionsFn($file, $width, $height)" ngf-duration="durationFn($file, $duration)" ngf-keep="keepDistinct ? 'distinct' : keep" ngf-fix-orientation="orientation" ngf-max-files="maxFiles" ngf-ignore-invalid="ignoreInvalid" ngf-run-all-validations="runAllValidations" ngf-allow-dir="allowDir" class="drop-box ng-dirty ng-valid ng-valid-max-size ng-valid-min-height ng-valid-min-width ng-valid-ratio ng-valid-max-ratio ng-valid-min-ratio ng-valid-max-duration ng-valid-min-duration ng-valid-duration ng-valid-validate-async-fn ng-valid-max-height ng-valid-max-width ng-valid-dimensions btn btn-save" ngf-drop-available="dropAvailable" >Upload File or Drag File</button>
angular controller code:
$scope.fileUpload = true;
$scope.uploadFiles = function (files, singleRelease) {
$scope.getFileFormat(files);
$scope.files = files;
$scope.fileUpload = false;
if ($scope.releaseCheck == false || $scope.releaseCheck == undefined) {
angular.forEach(files, function (uploadFile, index) {
$scope.uploadSingleFile(uploadFile);
});
}
angular.forEach($scope.files, function (file, index) {
$scope.uploadFile(file);
})
};
$scope.uploadFiles = function (files, singleRelease) {
$scope.getFileFormat(files);
$scope.files = files;
$scope.fileUpload = false;
if ($scope.releaseCheck == false || $scope.releaseCheck == undefined) {
angular.forEach(files, function (uploadFile, index) {
$scope.uploadSingleFile(uploadFile);
});
}
angular.forEach($scope.files, function (file, index) {
$scope.uploadFile(file);
})
};
LARAVEL Controller function code
public function uploadDirectFile(Request $request) {
$uni_msg = \CmsMessage::getUniMessage();
$postData = $request->all();
$mediaName = 'file_' . md5(uniqid(rand(), true));
$fileData = [];
$destinationPath = \CmsHelper::createFolderIfNotExists('directFileUploads/');
if (null !== $postData['file'] && $postData['file']->getFilename() != '') {
$uploadeImage = \CmsHelper::handleMedia($postData['file'], $destinationPath, $mediaName);
$fileData['original_name'] = $postData['file']->getClientOriginalName();
$fileData['mediaName'] = $uploadeImage['mediaName'];
$fileData['mediaType'] = $uploadeImage['mediaType'];
$fileData['mediaMime'] = $uploadeImage['mediaMime'];
$fileData['file_path'] = url('/') . '/directFileUploads/';
}
if (sizeof($fileData) > 0) {
return Response::json(['status' => 1, 'data' => $fileData, 'fileHashKey' => $postData['fileHashKey'], 'message' => $uni_msg['success']]);
}
return Response::json(['status' => 0, 'message' => $uni_msg['error']]);
}
Thanks Ahead.

Can i convert whole cakephp website to web services?

Hey I m working on project in cakephp. There will also be apps for Android as well as iPhone. How can i convert my web code to web services.
Yes, There is a way to convert complete site in web-services of any version of cakephp.
There is step to follow:
1. Put "Router::parseExtensions("pdf", "json");" this line to your routes.php in config folder before routing rules.
2. Overwrite your "beforeRender" and "Redirect" function in AppController with following:
function beforeRender() {
if (Configure::read("debug") == 0) {
if ($this->name == 'CakeError') {
$this->layout = "error";
}
} else {
if ($this->name == 'CakeError') {
$this->layout = "error";
}
}
if ($this->params["ext"] == "json") {
$paging = $requests = "";
if (isset($this->params["paging"]) && !empty($this->params["paging"])) {
$paging = $this->params["paging"];
}
$this->set(compact("paging"));
if (isset($this->request->data) && !empty($this->request->data)) {
$requests = $this->request->data;
}
$this->set(compact("requests"));
if ($this->Session->check("Message.flash") && is_array($this->Session->read("Message.flash"))) {
foreach ($this->Session->read("Message.flash") as $key => $value) {
$this->set($key, $value);
}
}
if (isset($this->{$this->modelClass}->validationErrors) && !empty($this->{$this->modelClass}->validationErrors)) {
$this->set("formError", $this->{$this->modelClass}->validationErrors);
}
if (isset($this->viewVars["params"])) {
unset($this->viewVars["params"]);
}
if (isset($this->viewVars["request"])) {
unset($this->viewVars["request"]);
}
$response = $this->viewVars;
if (!in_array($this->params["action"], $this->Auth->allowedActions) && !$this->Auth->loggedIn()) {
$response = array("authError" => true, "message" => "Please login to access.");
}
$this->set(compact("response"));
$this->set('_serialize', array("response"));
}
}
public function redirect($url, $status = NULL, $exit = true) {
if ($this->params["ext"] == "json") {
$paging = $requests = "";
if (isset($this->params["paging"]) && !empty($this->params["paging"])) {
$paging = $this->params["paging"];
}
$this->set(compact("paging"));
if (isset($this->request->data) && !empty($this->request->data)) {
$requests = $this->request->data;
}
$this->set(compact("requests"));
if (isset($this->{$this->modelClass}->validationErrors) && !empty($this->{$this->modelClass}->validationErrors)) {
$this->set("formError", $this->{$this->modelClass}->validationErrors);
}
if (!in_array($this->params["action"], $this->Auth->allowedActions) && !$this->Auth->loggedIn()) {
$response = array("authError" => true, "message" => "Please login to access.");
}
$this->set(compact("response"));
$this->set('_serialize', array("response"));
} else {
parent::redirect($url, $status = NULL, $exit = true);
}
}
Note: If you are checking for Ajax request using that request is ajax or not, and you want to response to your ajax, you have to put your response in "IF" condition
if (!isset($this->params["ext"])) {
// echo json_encode($response);
// echo "success";
// die;
}
Otherwise you can render your view in response.
I would start by reading this
You basically need to modify your routes. You also need to modify (serialize) what your controllers return.

Resources