Check localstorage value and pass parameters at state.go in IONIC - php

I have create an ionic app that will set the token value whenever a successful login is made by the user. Then, it will make use of $state.go to redirect the user to another tab "tab.scan".
When user clicked on the "tab.details" tab at the navigation bar, it will redirect the user to "tab.details" without passing any parameters.
However, the "details" page did not manage to get the value of the stored token.
How can I go about doing it?
It works fine when the url is url: '/details' instead of url: '/details/:store_id/:invoice_id'.
Code for login
.controller('LoginCtrl', function ($scope, LoginService, $ionicPopup, $state, $stateParams) {
$scope.data = {};
$scope.token = { token: "" };
$scope.login = function () {
LoginService.loginUser($scope.data.username, $scope.data.password).success(function (data) {
//Set login token
localStorage.setItem("token", $scope.data.username);
//Redirect the user to scan tab
$state.go('tab.scan', { store_id: $scope.data.store_id });
//Popup alert for welcome message
var alertPopup = $ionicPopup.alert({
title: 'Login Success!',
template: 'Welcome ' + localStorage.getItem("token") + '!'
});
}).error(function (data) {
//Failed login, popup error message
var alertPopup = $ionicPopup.alert({
title: 'Login Failed!',
template: 'Please check your credentials!'
});
});
}
})
Code for tabs
.state('tab.details', {
cache: false,
url: '/details/:store_id/:invoice_id',
views: {
'tab-details': {
templateUrl: 'templates/tab-details.php',
controller: 'DetailsCtrl'
}
}
})
Code for detail controller
.controller('DetailsController', function ($scope, $http, $state, $ionicPopup, $stateParams) {
$scope.token = localStorage.getItem("token");
console.log($scope.token);
if ($scope.token == "logOut") {
$state.go('login');
var alertPopup = $ionicPopup.alert({
title: 'Login Required!',
template: 'Please login to access.'
});
}
else {
}
})

$scope is relative to each controller unless login is a parent state $scope will not cascade to child states. You need to set token in a service which can be called from any controller or you can set it on $rootScope so it is available everywhere. Is you want to use $rootScope change $scope.token to $rootScope.token.

Related

Yii, Backbone save(), data did not passed through $_POST

This is my JavaScript in index.php:
MyModel = Backbone.Model.extend({
defaults: {
myID: "",
myName: ""
},
urlRoot: 'testAjaxAdd',
sync: function(method, model, options) {
options = options || {};
options['data'] = {};
options.data["myID"] = model.get("myID");
options.data["myName"] = model.get("myName");
options.data = JSON.stringify(options.data);
return Backbone.sync.apply(this, arguments);
}
});
MyView = Backbone.View.extend({
el: '.page',
render: function(){
var template = _.template($('#add-owner-template').html(), {});
this.$el.html(template);
},
events: {
'submit .create-owner-form': 'saveOwner'
},
saveOwner: function(events) {
var myName= $('input#myName').val();
var owner = new MyModel({
'myID': "111",
'myName': myName
});
owner.save({},{
success: function(model, response, options) {
console.log('success');
console.log(response); // show $_POST from actionSaveOwner in Controller
console.log(model.toJSON()); // show model
console.log(model.get('myID')); // show owner dbcID
console.log(model.get('myName')); // show owner userID
console.log(JSON.stringify(options)); // show options
console.log(options.data["myID"]); // this is shown undefined in console
console.log(options.data["myName"]); // this is shown undefined in console
},
error: function(model, response, options) {
console.log('error');
console.log(response);
console.log(model.toJSON());
}
});
}
});
I have put the code below in very first line within my javascript codes:
Backbone.emulateHTTP = true;
This is my html part of the form, it also a javascript template:
<script type="text/template" id="add-owner-template">
<form class='create-owner-form'>
<label>Name</label>
<input type="text" name="myName" id="myName"/>
<button type="submit" class="btn createcontbutton">Create</button>
</form>
</script>
This is my very simple action in Controller to test out if my backbone works or not:
public function actionTestAjaxAdd()
{
header('Content-type: application/json');
echo CJSON::encode($_POST);
}
However, this is what I see from console in POST tab:
Parameters application/x-www-form-urlencoded Do not sort
{"myID":"111","myName":"i...
But, the $_POST in controller action is nothing when i display it back in console from response.
I finally solved this myself using file_get_contents("php://input") .

how could i retrieve profile data in a modal using ajax in php?

here's the deal, i've created a search results page and i'd like to open a modal and retrieve profile data via ajax in php but i'm not too sure on how i can implement it. I've created the modal but but i don't know how i would go about getting the 'id' from clicking the search result, passing it onto ajax to retrieve the profile details.
Twitter has this kinda feature; when you click a username in a feed and it opens a modal and gives you a brief overview of the profile with a link to the full profile.
It would mean so much to me if someone could help me out or point me in the right direction! :)
P.S. I'm using codeigniter, if anyone is wondering what framework i'm using.
EDIT: here's the code
<?php
/*** PHP Search Results Loop ***/
if ($num > 0){
foreach ($query->result_array() as $row)
{
echo "link to ajax"'>";
}
} else {
echo "<strong>results not found :(</strong>";
}?>
<script> /* jQuery Runs When Result Has Been Clicked */
$('#ResultText').click(function() {
var targetid = {
id: /*Profile Id*/,
ajax: '1'
};
/* Modal Code */
$('.modal-backdrop, .modal-profilebox').css('display', 'block');
$('.modal-backdrop').animate({'opacity':'.50'}, 100, 'linear');
$('.modal-profilebox').animate({'opacity':'1.00'}, 200, 'linear');
$.ajax({
url: "<?php echo site_url('finder/modal'); ?>",
type: 'POST',
data: form_data,
success: function(profileData) {
$('.modal-profilebox').html(profileData);
}
});
return false;
});
</script>
Try something like this
public function ajax_user_profile($user_id)
{
if( !$this->input->is_ajax_request() )
{
redirect('/'); //only allow ajax requests
}
try
{
$user_profile = ''; //grab user object from DB
if( !$user_profile )
throw new Exception("Error Message");
}
catch(Exception $e)
{
log_message('error', $e->getMessage());
echo json_encode(array(
'error' => 1
));
exit;
}
$data = $this->load->view(array(
'some_view' => 'some_view',
'user' => $user_profile
), TRUE); //NO Template, just the view by adding TRUE
echo json_encode(array(
'error' => 0,
'data' => $data
)); //return view data
}
--
<a rel="modal" data-user-id="1" >Joe Bloggs</a>
--
(function($){
var userObj = {
init : function(){
this.getProfile();
},
getProfile : function(){
var modalSearch = $("a[rel='modal']");
modalSearch.on('click', function(){
//trigger the modal window
//request ajax
$.ajax({
url : BASEPATH + 'users/profile/' + $(this).data('user-id'),
type : 'POST',
dataType: 'json',
success : function(callback){
if(callback.error ==0)
{
$('.modal-profilebox').html(callback.data);
}
}
});
});
}
}
$(function(){
userObj.init()
});
})(jQuery);

Redirect in facebook iframe app on multiple pages

small problem with my iframe facebook app. I want to use the app on many fb pages (so I won't know the exact urls of the FB pages) in a tab. But there is a problem with the redirect after the app asks for the permissions. Instead of the fb page, it redirects user to my canvas URL, and that is wrong! How to solve it?
Dont use the redirect method for fan pages aka Tabs ,just call the following method in java script to get permission.
function getPermission(){
FB.ui({
'method': 'permissions.request',
'perms': 'publish_stream,email,user_photos',
},
function(response) {
if (response.perms != null) {
// user is already connected
token=response.session.access_token;
uid=response.session.uid;
}
else if(response.status=="connected")
{
token=response.session.access_token;
uid=response.session.uid;
// new user is now connected
}
else
{
// user has not given a permission hence not connected.
}
});
return false;
}
If you only ask once for login/permissions (this won't handle getting permissions when needed), something like this should work:
function withLogin(callback) {
var ifLogin = function(response, true_cb, else_cb) {
if(response.authResponse)
true_cb(null, response);
else
else_cb(true, null);
};
FB.getLoginStatus(function(response) {
ifLogin(response, callback, function(err, response) {
FB.login(
function(response) {
ifLogin(response, callback, callback);
},
{ scope: "email,user_photos" }
);
});
});
}
...
window.fbAsyncInit = function() {
...
withLogin(function(err, response) {
if(err)
alert("This only works if you log in!");
else
alert("UserId: " + response.authResponse.userID);
});
};

CakePHP 2.0 Ajax login

I have the following method which allows a user to login into my application:
public function login()
{
if($this->Auth->user())
{
$this->Session->setFlash(__('Already logged in...'), 'default', array(), 'auth');
$this->redirect(array('controller'=>'pages','action'=>'display','home'));
}
if ($this->request->is('ajax'))
{
$this->layout = 'ajax';
if ($this->Auth->login())
{
}
else
{
}
}
else if ($this->request->is('post'))
{
if ($this->Auth->login())
{
return $this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
It allows a user to login either using a post request or via an ajax request. However with regards to the ajax requests how do I pass the results back using JSON? So for example if the user enters the wrong details pass back an error message?
I have the jQuery AJAX already setup so I just need to do some extra logic in the success method to deal with the return which will either show the error message from the server or do a redirect again based on the return from the server.
e.g.
$('form').live('submit', function (event) {
// Declare the form
var form = $(this);
// Stop the form from doing a native postback
event.preventDefault();
// Get the data from the form
var data = form.serialize();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: data,
success: function (responseHtml) {
// If correct login details
if(success){
window.location.href('INSERT LOCATION TO REDIRECT TO FROM SERVER');
} else {
alert('INSERT MESSAGE FROM THE SERVER');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error!');
}
});
});
Can anyone help? I'm using CakePHP 2.0 and all of the tutorials I have seen on the net and on here have either been outdated or much too long-winded for what I'm trying to achieve.
Edit: you need to use the following php code
if ($this->Auth->login())
{
$arr = array("login" => "true" , "redirect" => "/redirect_url");
echo json_encode($arr);
}
else
{
$arr = array("login" => "false" , "error" => "Invalid Login Credentials");
echo json_encode($arr);
}
on the javascript side you need to modify your javascript to handle json values using jQuery.getJSON. example of jQuery.getJSON is availabe here http://api.jquery.com/jQuery.getJSON/
use this jQuery code
<script type="text/javascript">
$.getJSON("login.php", function(data) {
if(data.login)
{
//redirect user with data.redirect
}
else
{
//display error with data.error
}
})
</script>

Facebook iframe Graph App Requests

function sendRequest(c_id,page_id,user,g_id) {
// alert(c_id);
// alert(page_id);
FB.ui({
method: 'apprequests',
message: 'Custom messae!',
title: 'Enter in this contest!',
data: +id+','+puid+','+n_id,
},
function (response) {
if (response && response.request_ids) {
var requests = response.request_ids.join(',');
window.location.href = "mysiteurlhere";
} else {
alert('canceled');
}
});
return false;
}
The above code works for multiuser but not single user even after adding TO field,
I changed the code and used to field
method: 'apprequests',
to: sendto,
sendto has uid of user to whom i want to send the app request, I do get the invitation id but
$request_content = json_decode(file_get_contents("https://graph.facebook.com/$request_id?$app_token"), TRUE);
// returns false when i access the url
Am i missing something Multi User is working as smooth as it can be.

Categories