$location.path not working in angularjs - php

$location.path not redirecting after successful return from php. Data returned from php page is not empty . No problem with php file its returning correct data .The problem is $location.path is not working I referred many sites but I could not find solution help me..
angular.module(MyApp).controller(Part3Controller, function ($scope, LoginService) {
$scope.IsLogedIn = false;
$scope.Message = '';
$scope.Submitted = false;
$scope.IsFormValid = false;
$scope.MyLogin = {
USER_ID:'' ;
Password: '';
};
//Check is Form Valid or Not // Here f1 is our form Name
$scope.$watch(f1.$valid, function (newVal) {
$scope.IsFormValid = newVal;
});
$scope.Login = function () {
$scope.Submitted = true;
if ($scope.IsFormValid) {
LoginService.GetUser($scope.MyLogin).then(function (d) {
if (d.data.USER_ID != null) {
$scope.IsLogedIn = true;
$location.Path(/LandingPage/FetchMenu);
}
else {
alert('Invalid Credential!');
}
});
}
};
})
.factory('LoginService, function ($http) {
var fac = {};
fac.GetUser = function (d) {
return $http({
url:/Data/UserLogin,
method: POST,
data: JSON.stringify(d),
headers: {content-type:application/json}
});
};
return fac;
});

You haven't injected $location:
angular.module(MyApp).controller(Part3Controller,
function ($scope, LoginService) {
Should be:
angular.module(MyApp).controller(Part3Controller,
function ($location, $scope, LoginService) {

Related

ionic v3 when make and update in the app to the data it is updating in the database but not in the app

I am new to ionic and I am trying to understand an app that has basic http query to communicate with the database, but I am facing a problem.
There is a page that show a list which has been taken from the database. There are two operations that can be performed on this list - insert and update. The problem occurres when I try to make an update. The record in the database is updated but not the list in the application is not. However, when I insert a new record the list got updated with the new record including all previous changes, that were not shown in the list.
Here is the type script for the list page:
export class CrudHttpListPage {
items: any;
constructor(public loading: LoadingProvider, private toast: ToastProvider, public modal: ModalController, private crud: CrudHttpProvider) { }
ionViewDidLoad() {
this.load();
}
load() {
this.loading.present();
this.crud.read.then(res => {
this.items = res;
if (res) this.loading.dismiss();
});
}
add() {
let modal = this.modal.create('CrudHttpDetailPage', { action: 1 });
modal.present();
modal.onDidDismiss(data => {
console.log(data);
if (data) this.load();
});
}
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
if (data) this.load();
});
}
Here is the typescript code for the add and edit page:
export class CrudHttpDetailPage {
private form: FormGroup;
action: number;
data: any = { title: '', text: '' };
constructor(private view: ViewController, private toast: ToastProvider, private loading: LoadingProvider, private crud: CrudHttpProvider, private fb: FormBuilder, public params: NavParams) {
this.action = params.data.action;
this.data = params.data && params.data.data || this.data;
console.log(params.data);
this.form = this.fb.group({
id: [this.data && this.data.id],
title: [this.data && this.data.title, Validators.required],
text: [this.data && this.data.text, Validators.required]
});
}
submit() {
this.loading.present();
console.log(this.form.value);
this.crud.save(this.form.value).then(data => {
// this.dataNotes.id = data;
console.log(data);
this.loading.dismiss();
this.view.dismiss(this.form.value);
}, err => {
console.log(err);
this.loading.dismiss();
this.toast.showWithClose(err);
this.close();
});
}
close() {
this.view.dismiss();
}
}
Here are the http operations:
const SERVER_URL: any = {
getNormal: ConstantVariable.APIURL + 'index.php/tbl_note',
getLimit: ConstantVariable.APIURL + 'limit.php',
};
#Injectable()
export class CrudHttpProvider {
limitData: number = 10;
datas: any = [];
constructor(public http: Http) {
this.datas = null;
}
get read() {
return new Promise(resolve => {
this.http.get(SERVER_URL.getNormal).map(res => res.json()).subscribe(data => {
console.log(data.dataNotes);
resolve(data.dataNotes);
});
});
}
save(item) {
let headers: any = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }),
options: any = new RequestOptions({ headers: headers });
if (item.id) {
return new Promise((resolve, reject) => {
this.http.post(SERVER_URL.getNormal + '/' + item.id, item, options).map(res => res.json()).subscribe((data) => {
console.log(data);
resolve(data.dataNotes);
}, (err) => {
reject(err);
console.log("error: " + err);
});
});
}
else {
return new Promise(resolve => {
this.http.post(SERVER_URL.getNormal, item, options)
.map(res => res.json())
.subscribe(data => {
// console.log(data);
resolve(data.dataNotes[0].id);
}, error => {
console.log("error " + error);
});
});
}
}
and last here is the PHP file:
<?php
header('Access-Control-Allow-Origin: *');
require_once('config.php');
// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;
// escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
if ($value===null) return null;
return mysqli_real_escape_string($link,(string)$value);
},array_values($input));
// build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
$set.=($i>0?',':'').'`'.$columns[$i].'`=';
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}
// create SQL based on HTTP method
if ($method == "POST" AND $key != "") { $method = 'PUT'; }
if ($method == "GET" AND $key != "") { $method = 'DELETE'; }
switch ($method) {
case 'GET':
$sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
case 'PUT':
$sql = "update `$table` set $set where id=$key"; break;
case 'POST':
$sql = "insert into `$table` set $set"; break;
case 'DELETE':
$sql = "delete from `$table` where id=$key"; break;
}
// excecute SQL statement
$result = mysqli_query($link,$sql);
// die if SQL statement failed
if (!$result) {
http_response_code(404);
die(mysqli_error());
}
// print results, insert id or affected row count
echo "{\"status\":\"ok\", \"dataNotes\":";
if ($method == 'GET') {
if (!$key) echo '[';
for ($i=0;$i<mysqli_num_rows($result);$i++) {
echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
}
if (!$key) echo ']';
} elseif ($method == 'POST') {
$set = '"id":"'.mysqli_insert_id($link).'"';
for ($i=1;$i<count($columns);$i++) {
$set.=($i>0?',':'').'"'.$columns[$i].'":';
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}
echo "[{".$set."}]";
} elseif ($method == 'DELETE') {
echo '[{"id":"'.$key.'"}]';
} else {
echo mysqli_affected_rows($link);
}
echo "}";
// close mysql connection
mysqli_close($link);
The issue might be here:
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
if (data) this.load(); // <---- seems this.load() is not executing
});
}
Seems this.load() is not executing after modal.onDidDismiss:
- check modal is dismissing
- check if data is not null/undefined
- check running this.load(), with no if() statement, does it run?
you may be able to find the answer there
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
console.log('Modal has dismissed!!');
// if (data) this.load(); // comment for check
this.load();
});
}
i finally solved the problem. what cause the issue is that i have two files to make a connection to the database one for the website and the other is for the mobile application and it seems the one which i use in the mobile application is broken so i remove this file and connect to the old file and the problem solved

How to get the values from multiple form in one post request using laravel?

Ajax:
<script type="text/javascript">
$(document).ready(function () {
$('#finalSubmit').click(function() {
var form1 = $('#priceform').serialize();
var form2 = $('#formdescription').serialize();
var form3 = $('#additionaldescription').serialize();
//var form4 = new FormData($("#imagesform").get(0));
//alert(form4);
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content') }
});
$.ajax({
url :"{{url('/dbvalue')}}",
type: 'POST',
data: {form1: form1, form2: form2,form3: form3},
dataType:'json',
success:function(data){
alert(data);
}
});
});
});
</script>
This is my ajax code.Here I'm passing the values of four forms
Controller:
public function finalSubmit(Request $request)
{
var_dump($_POST);
$var1 = $this->addPriceDetails1($request->form1);
$var2 = $this->addProductDetails1($request->form2);
$var3 = $this->addAdditionalInformation1($request->form3);
//$var4 = $this->addImages($imagesform);//you dont't have
$imagesform
return response()->json(["response"=>"success"]);
}
Eg. for function:
public function addPriceDetails1($request)
{
$priceInfo = new priceInfo ;
$priceInfo->id=$this->getpriceDetailsId();
$priceInfo->SKUID=$request->input('skuid');
echo($priceInfo->id);
//return $request->all();
}
Also here when I'm trying to echo the values of $priceInfo->Id it echoes '0'.I don't know why
With this I'm getting FatalErrorException..call to member function input() on string
var_dump($_POST) gives me an array of forms values.
UPdate:
public function getpriceDetailsId()
{
$id = mt_rand(1000000, 9999999);
$id="PD".$id;
$count=priceInfo::select('id')->where('id',$id)->count();
if($count==0)
{
return $id;
}
else
{
$this->getpriceDetailsId();
}
}
here is my function for getpriceDetailsId().
You get that error because your input query when you access as object when it is string, you can convert your query string to an array to access like so.
public function addPriceDetails1($request)
{
parse_str($request, $input);
$priceInfo = new priceInfo ;
$priceInfo->id = $this->getpriceDetailsId();
$priceInfo->SKUID = $input['skuid'];
echo($priceInfo->id);
}
Hope this help

How do I get my user_id from the authorised client

I want to retrieve the id of the user that's currently online. But I CANNOT do it with the following code:
Route::middleware('auth:api')->post('/optionelections', function (Request $request) {
return $request->user();
});
The reason is that I keep getting the same unauthorised error from Laravel. I've been trying to fix this error for days and I can't seem to find a solution. So I'm trying to do it in a different way but I don't know how. I'm currently using Passport to store my token and my client_id in local storage.
this is my apply_election.vue
import {apiDomain} from '../../config'
export default {
name: 'applyForElection',
data () {
return {
election: {},
newOption: {'election_id': ''},
//this is where the user_id should come
newOption: {'user_id': ''}
}
},
methods: {
createOption: function () {
var itemId = this.$route.params.id
this.newOption.election_id = itemId
this.$http.post(apiDomain + 'optionelections', this.newOption)
.then((response) => {
this.newOption = {'election_id': itemId}
alert('you applied!')
this.$router.push('/electionsnotstarted')
}).catch(e => {
console.log(e)
alert('there was an error')
this.$router.push('/electionsnotstarted')
})
}
},
created: function () {
var itemId = this.$route.params.id
this.$http.get('http://www.nmdad2-05-elector.local/api/v1/elections/' + itemId)
.then(function (response) {
this.election = response.data
})
}
}
And this in my OptionElectionsController.php
public function store(Request $request)
{
$optionElection = new OptionElection();
$optionElection->user_id = $request['user_id'];
$optionElection->option = "something";
$optionElection->votes = 0;
$optionElection->election_id = $request['election_id'];
$optionElection->accepted = 0;
if ($optionElection->save()) {
return response()
->json($optionElection);
}
}
This is my Auth.js
export default function (Vue) {
Vue.auth = {
setToken (token, expiration) {
localStorage.setItem('token', token)
localStorage.setItem('expiration', expiration)
},
getToken () {
var token = localStorage.getItem('token')
var expiration = localStorage.getItem('expiration')
if (!token || !expiration) {
return null
}
if (Date.now() > parseInt(expiration)) {
this.destroyToken()
return null
} else {
return token
}
},
destroyToken () {
localStorage.removeItem('token')
localStorage.removeItem('expiration')
},
isAuthenticated () {
if (this.getToken()) {
return true
} else {
return false
}
}
}
Object.defineProperties(Vue.prototype, {
$auth: {
get: () => {
return Vue.auth
}
}
})
}
You are using the TokenGuard of Laravel, There many way to let the guard recognise the authentication, the best methods:
Send the token in api_token attribute in the request's query.
this.newOption.api_token = token;
Send the token in Authorization header with Bearer prefix.
{
headers: {
Authorization: 'Bearer THE_TOKEN'
}
}

avoiding duplicate mysql injection

I created a controller and called the function for one time.But it call two times and inserted the value two times.I call the service upload_album in controller.Now value got inserted for two times.one with original value and another with dummy value
Controller
$scope.savealbum = function() {
$scope.album_pids = $routeParams.id;
$timeout(function () {
//console.log($scope.justapp);
for (tt in $scope.justapp) {
if ($scope.justapp[tt].id == $scope.album_pids) {
for (var i = 0; i < $rootScope.media_lib.length; i++) {
}
}
}
$scope.promise=AlbumServices.upload_album($scope.album_pids,$scope.images,$scope.videos);
$scope.promise.then(function(data) {
console.log(data);
alert('Photos Added to Album Successfully');
// $location.path('album_details/' + $routeParams.id);
}, function(reason) {
console.log(reason);
});
}, 1500, false);
};
Service
upload_album: function (alb,img,vid) {
var deferred = $q.defer();
var data = {};
data.pagename = "upload_album";
data.album = alb;
data.photo = img;
data.video = vid;
$http.post('js/data/album.php', data)
.success(function (data, status, headers, config)
{
console.log(status + ' - ' + data);
deferred.resolve(data);
})
.error(function (data, status, headers, config)
{
deferred.reject(data);
console.log('error');
});
return deferred.promise;
}
php
function upload_album ($prefix) {
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$sub_id=$request->album;
$val=$request->photo;
$photo = json_encode($val);
$video = json_encode($request->video);
$now = date('Y-m-d H:i:s');
$count_pho = sizeof($photo);
$count_vid = sizeof($video);
$test = '';
if($count_pho != '0' ) {
$test .= "('".$sub_id."','".$content_type."','".$photo."','".$website_id."','".$now."'),";
$demo = substr($test, 0, -1);
$sql="INSERT INTO `album_details` (SUB_ID,CONTENT_TYPE,CONTENT_VALUE,WEBSITE_ID,CreatedTime)VALUES".$demo;
$query = mysql_query($sql) or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $sql, __LINE__);
}
if ($query) {
echo $msg = true;
} else {
echo $msg = false;
}
}
Because we cannot se the whole code (including the HTML) my suggestions are these:
check your html and/or run method inside angular to be sure that your controller was not instanciated twice
create a unique key pair in your database (it could help not have double records)
create a debouncer when using timeout so that if the timeout is always launched once. something like this:
var t = null;
var mySaveFunction = function () {
if (t) {
clearTimeout(t);
}
t = setTimeout(function () {
/* do saving here */
}, 2000);
};

Angularjs page reloading help inside controller

i am trying to implement the login system in angularjs and php.
$scope.signForm = function() {
$scope.loading = true;
$scope.remember=true;
$http.post('user/action/signin.php', $scope.formData)
.success(function(data) {
console.log(data);
$scope.error = false;
$scope.message = false;
if (!data.success) {
$scope.error = data.error;
$scope.loading = false;
} else {
$location.url('/userprofile.php'); //
$scope.loading = false;
}
});
};
i am checking for user login if success i need to load the userprofile.php. my userprofile.php page is different and not using angularui.
thanks.
Use $window.location.href = '/userprofile.php'

Categories