I'm trying to set a php session onload
$_SESSION["tusername"] = $_POST['ttuser'];
however my value is being set in jQuery on $(function() {
$('#ttuser').val(tusername);
When the page is loaded, the session is not set as I believe the session is being set before the textbox value is set by jQuery. I tried using ajax to post a value to the page, but it doesn't retrieve it.
The only way I am setting the session now is on a button click, the exact same way.
Any ideas?
Thanks in advance
EDIT
Here is the Function at the start where everything is set, as requested
$(function() {
// Initialize. If we are already logged in, there is no
// need for the connect button
Twitch.init({clientId: CLIENT_ID}, function(error, status) {
if (status.authenticated) {
// we're logged in :)
$('.authenticatedd').removeClass('hidden');
} else {
$('.welcometitle').html('<strong>Not yet connected with Twitch?</strong>');
// Show the twitch connect button
$('.authenticate').removeClass('hidden');
}
});
var token = Twitch.getToken();
$('.twitch-connect').click(function() {
Twitch.login({
scope: ['user_read', 'channel_read', 'channel_editor', 'channel_commercial', 'user_subscriptions', 'channel_check_subscription']
});
})
Twitch.api({method: 'channel'}, function(error, channel) {
$('#streamkey').text(channel.stream_key);
});
Twitch.api({method: 'user'}, function(error, user) {
var tusername = user.display_name;
var tlogo = user.logo;
$('#twitchname').text(tusername);
$('#ttuser').val(tusername);
$.get("setsession.php?ttuser="+tusername, function(){
});
console.log(tlogo);
if (tlogo != null)
$('#twitchlogo').attr('src', tlogo);
$.cookie('logo', tlogo, { expires: 14, path: '/'});
$('.sidename').html('<strong>' + tusername + '</strong> Logged in');
var currentdate = new Date();
var datetime = currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
var items = [];
items.push('<li><div class="xe-comment-entry"><div class="xe-comment"><span class="label label-success">Status</span><p><span class="label label-danger">' +datetime+ '</span> Logged in</p></div></div></li>')
$('#eventlog').prepend( items.join('') );
});
});
Why dont you just make a request to a php file which will initiate the session.
myfile.php
<?php
session_start();
$_SESSION["tusername"] = $_REQUEST['ttuser'];
echo "Session is : "+$_SESSION["tusername"];
?>
HTML
$(function(){
$.get("myfile.php?ttuser="+tusername, function(data){
console.log(data);
});
$('#ttuser').val(tusername);
});
Related
I have searched quite a lot regarding my problem and I couldn't find any relevant tutorial. Moreover, I am not even sure if it is possible using client side technology.
Problem statement: For e.g I have many pages in my web app and if a user switch from index page to page 1 and then page 2. Now the user decides to login to my web site. I want to redirect the user to page 2 once the login is successful.
Current outcome: Once the login is successful user always seems to get redirected to the index page.
Desired outcome: Once the login is successful the user should stay on page 2.
Is it possible using client side technology? In PHP we could use sessions and all. But I am confined on using client side technology to achieve that.
Here is my login function
function login(params) {
if(checkEmpty("loginEmail") && checkEmpty("password")) {
var emailField = $("#loginEmail").val(),
passwordField = $("#password").val(),
data = "login=" + emailField + "&password=" + passwordField;
for (var key in params) {
data += "&" + key + "=" + params[key];
}
// Hide errors as default
$("#loginErrorWrapper").hide();
// Try to launch the "normal" submit operation to make browser save email-field's value to cache
$('#loginSubmitHidden').click();
// Send data to server and refresh the page if everything is ok
$.when(loginPost(data)).done(function(map) {
if(!hasErrors(map)) {
var lang = map.language;
if (lang != "") {
changeLanguage(lang)
}
else {
lang = 'en';
}
redirect("/" + lang + "/");
} else {
if (map.errorCode == "155") {
$.fancybox({
href : '#termsAcceptancePopup',
title : '',
beforeLoad : function() {
$('#acceptTermsButton').attr('onclick','javascript:login({policyChecked:true});$.fancybox.close();');
},
helpers : {
overlay : { closeClick: false }
}
});
} else {
var errorString = getErrorMessage(map);
$("#loginErrorWrapper").show();
$("#loginErrorWrapper").html(errorString);
}
}
});
}
}
Ajax request
function loginPost(data) {
return $.ajax({
url: "/some-api/login",
type: "POST",
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: true,
data:data
});
}
P.S -> I am not using PHP at all. I am working on a Java based web app.
So I have tried all the methods suggested in the comment section and all of them worked.
1) Using location.reload()
Once the user is logged in it just refresh the page.
2) Saving the last URL in a cookie
Calling the below function before calling redirect.
createCookie(value1, value2, value3);
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
3) Removing redirect("/" + lang + "/"); from my function since I am using ajax for login. However this method is not useful because once the user is logged in he/she will never know whether everything went fine or not unless he/she refresh the page manually or go to another page.
I am not certain which method is better (performance and loading time) - method 1 or method 2.
In my app, I have two types of profile for organisations. When a user click on a profile name, I first need to check whether I have a premium profile for that organisation, and if so, route the user in that direction. If there is no premium profile, the user is sent to the standard profile.
I'm doing this using ng-click, which send id and a resource (in this case, organisation) parameters to a controller, where the conditions are evaluated and then the user is routed in the correct direction. All of this works correctly when a user clicks as normal.
However, when a user tries to open the link in a new tab, by right clicking and selecting that option, the new tab opens with the url of the current page. So the ng-click and controller has not fired or evaluated the request before opening the new tab.
How can I change by code so that Angular processes the ng-click request before opening the new tab? Or more broadly, how can I allow my users to open one of these links in a new tab so that they are not just displayed the page they are currently on?
HTML
<div ng-controller="ProfileRouter">
<div ng-repeat="org in orgs | orderBy:'org.name'">
{{ org.name }}
</div>
</div>
Inside ProfileRouter controller
$scope.profileCheck = function (id, resource) {
$http({method: 'GET', url:'/IdCheck', params:{'id': id})
.success(function(data) {
var count = data.hits.found;
if (count) {
var hash = data.hits.hit[0].id;
}
if (resource == 'organisation') {
theResource = 'universities';
page = 'overview';
}
if (count == 1) {
window.location.href = "/" + theResource + "/profile/" + hash + "/" + page;
}
if (count == 0) {
window.location.href = "/" + resource + "/" + id;
}
})
.error(function(data) {
$scope.data = data || "Can't get resource";
});
}
I know this is an old question. But I found out a solution to this & posting it here might help someone else.
First of all I have created a custom directive for right click:
module.directive('tabRightClick',['$parse', function($parse) {
return function(scope, element, attrs) {
var fn = $parse(attrs.tabRightClick);
element.bind('contextmenu', function(event) {
scope.$apply(function() {
// event.preventDefault();
fn(scope, {$event:event});
});
});
};
}]);
Then applied this directive as an attribute in the HTML file and call the same method that is being called on ng-click:
<div ng-controller="ProfileRouter">
<div ng-repeat="org in orgs | orderBy:'org.name'">
{{ org.name }}
</div>
</div>
Here locationPath is a $scope bound variable, which we need to implement in the controller.
Its value should be updated in the profileCheck function based on the various conditions.
$scope.profileCheck = function (id, resource) {
$http({method: 'GET', url:'/IdCheck', params:{'id': id})
.success(function(data) {
var count = data.hits.found;
if (count) {
var hash = data.hits.hit[0].id;
}
if (resource == 'organisation') {
theResource = 'universities';
page = 'overview';
}
if (count == 1) {
window.location.href = "/" + theResource + "/profile/" + hash + "/" + page;
$scope.locationPath = "/" + theResource + "/profile/" + hash + "/" + page;
}
if (count == 0) {
window.location.href = "/" + resource + "/" + id;
$scope.locationPath = "/" + resource + "/" + id;
}
})
.error(function(data) {
$scope.data = data || "Can't get resource";
});
}
Hope it's helpful.
I'm using a framework called PartialJS that follows a MVC architecture to build a webApp that will verify a user's input and make a request to an API and render the API response.
I'm not sure how to redirect the user to the rendered page after verification and API call has finished. Where should the page redirect and API calls be made?
Here's a quick breakdown of what the user will see with 'bullet' marks denoting what happens in the backend:
User presented with a form and fills information
exports.onValidation() called via a serialized JSON to verify that
all fields completed accurately (triggered by a button), done without
a page refresh.
API call is made with user's information, will not return until response is received and parsed
Form rendered with decoded JSON response from external API
I have tried using this in the 'view.html' page but the page redirects before verification.
<buttononclick="window.location='http://www.CaliCoder.com/results';">Submit</button>
<script type="text/javascript">
$(document).ready(function() {
$('button').bind('click', function() {
$.post('/', $('#f').serialize(), function(d) {
var err = $('#error');
if (d instanceof Array) {
err.empty();
d.forEach(function(o) {
err.append('<div>' + o.error + '</div>');
});
err.show();
return;
};
$('#f').trigger('reset');
err.empty();
err.show().html('SUCCESS! Please wait while the request is being made')
});
});
});
</script>
Here's what happens in the 'controller.js' end of things.
function json_form() {
var self = this;
var error = self.validate(self.post, ['intersection', 'hours', 'minutes', 'phone'])
if (error.hasError()) {
self.json(error);
return;
}
// save to database
var db = self.database('forms');
db.insert(self.post);
self.json({ r: true });
}
function get_routes(hours, minutes, intersection) {
//The following code makes a call that returns an array with data to be rendered by another view controller.
var stops = this.module('cumtd').GetStopsBySearch('springfied busey');
}
Thanks for reading! Sorry for sounding confusing, I'm new to JS and Node programming. :(
You have problem in clide-side JavaScript, solution:
HTML:
<button>Submit</button>
JavaScript:
$(document).ready(function() {
$('button').bind('click', function() {
$.post('/', $('#f').serialize(), function(d) {
var err = $('#error');
if (d instanceof Array) {
err.empty();
d.forEach(function(o) {
err.append('<div>' + o.error + '</div>');
});
err.show();
return;
};
$('#f').trigger('reset');
err.empty();
err.show().html('SUCCESS! Please wait while the request is being made');
// HERE REDIRECT:
setTimeout(function() {
window.location.href = 'http://www.CaliCoder.com/results';
}, 3000);
});
});
});
This is code which shows URL and delete image for delete cookie. add and display function is working but how to delete ??
function backLinks(){
var pathname = window.location;
var patientName = document.getElementById("general:patientDetailName").value;
var cookieTimeVal = jQuery.cookie('PCC_Back_Button');
if( cookieTimeVal== null){
cookieTimeVal ="";
}
// for writing Cookie
var stringCookie = "<span class='backLinkText1'><img src='../images/deleteImg.png' alt='' class='backLinkDeleteButton' onClick='deleteBackLink()'/></span><a class='backLinkText' href=\""+pathname+"\"> Patient History For \""+patientName+"\"</a>"+cookieTimeVal;
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
// read Cookie and set in HTML
jQuery('#backButtonSpan').append(
jQuery('<div>').attr({style:'padding-top:-10px;' }).append(cookieTimeVal)
);
}
**
function deleteBackLink(val){
jQuery.cookie(val, null);
}
**
How can I create a delete function and what parameter will I pass to it?
got a correct answer ...
in this i will replace cookie and delete inner html
function backLinks(stringValueAndName, patientName, patientDOB){
var pathname = window.location;
var cookieTimeVal = jQuery.cookie('PCC_Back_Button');
if( cookieTimeVal== null){
cookieTimeVal ="";
}
var time = new Date();
var spanId = time.getTime();
// for wright in Cookie
var stringCookie = "<span id ="+spanId+"> <img src='../images/deleteImg.png' class='backLinkDeleteButton' onClick='deleteBackLink("+spanId+")'/><a class='backLinkText' href=\""+pathname+"\">"+stringValueAndName +patientName+' ('+patientDOB +')'+"\</a></span>"+cookieTimeVal;
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
// read Cookie and set in HTML
jQuery('#backButtonSpan').append(
jQuery('<div>').attr({style:'padding-top:-10px;' }).append(cookieTimeVal)
);
}
function deleteBackLink(val){
jQuery('#'+val).remove();
var stringCookie = jQuery('#backButtonSpan div').html();
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
}
To delete a cookie with jQuery, set the value to null:
jQuery.cookie("name", null);
So your function will work - just pass the cookie name as a parameter:
deleteBackLink("name");
It doesn't. A cookie is a cookie.
The closest it comes is the HTTP Only flag, which allows a cookie to be hidden from JavaScript(mean client side). (This provides a little defence against XSS cookie theft).
A cookie is a cookie. (Again, client side code can't touch an HTTP only cookie)
I am using jquery-cookie library to create cookie with JQuery. How can I update value of the cookie? I need it create new cookie and if the cookie exists to update it. How can I do this?
Code that I got:
v.on('click', function(){
var d = $(this).attr('role');
if(d == 'yes')
{
glas = 'koristan.'
}else {
glas = 'nekoristan.'
};
text = 'Ovaj komentar vam je bio ' + glas;
//This part here create cookie
if(id_u == 0){
$.cookie('010', id + '-' + d);
}
$.post('<?php echo base_url() ?>rating/rat_counter', {id : id, vote : d, id_u : id_u}, function(){
c.fadeOut('fast').empty().append('<p>' + text).hide().fadeIn('fast');
});
})
To update a cookie all you need to do is create a cookie with the same name and a different value.
Edit
To append your new value to the old...
//Im not familiar with this library but
//I assume this syntax gets the cookie value.
var oldCookieValue = $.cookie('010');
//Create new cookie with same name and concatenate the old and new desired value.
$.cookie('010', oldCookieValue + "-" + id);
watch out for this link
http://www.electrictoolbox.com/jquery-cookies/
here you see all important thing you can do with cookies.
if you want to know if an cookie already exists, just use this
if($.cookie("example") != null)
{
//cookie already exists
}