Ajax Login that refresh only the logged div - javascript

Using Zoo Visitor ajax login or Ajax Auth, i manage well the ajax login witn EE.
When the user is logged, how to refresh only the div that contains: welcome user you are logged.
<div class="Welcome"><span>{username}</span> Logout</div><br />
Here is the Zoo Visitor Ajax login script:
$(document).ready(function(){
$('#loginForm').ajaxForm({
dataType: 'json',
success: function(data) {
if (data.success) {
alert('You are now logged in. You can add additional actions in the js script.');
} else {
alert('Failed with the following errors: '+data.errors.login);
}
}
});
});
I guess i have to insert a javascript code inside:
alert('You are now logged in. You can add additional actions in the js script.');
I'm still learning javascript, using
setInterval(function(){
document.getElementById('info').innerHTML =
It's a good method??Does someone has some tips??
It is possible to use a Expression Engine function??
thanks,
Stéphane

Assuming your <div class="Welcome">...</div> already exists on the page you would replace
alert('You are now logged in. You can add additional actions in the js script.');
With
$('div.Welcome').html('<span>Welcome...</span> Logout');
However, note that I removed {username}. When the user visits the page while logged out they do not have a username. When they log in via AJAX the page is not refreshed, therefore the username still remains on the server side. Zoo Visitor does not return any member data with it, either.
It might be better for you to just use a regular log in process than use AJAX if you're trying to do app-like stuff.
If you still want to stick to JavaScript for this then one thing you could do is create a template that returns the data via JSON, e.g.
{exp:http_header content_type="application/json"}
{ "username": "{username}" }
(Note the use of the http_header plugin.)
Right after a successful login you would use AJAX to check that template, then confirm the results. If username has a length then you know the person is logged in and you can update your Welcome div.
Or... you may want to try logging in via Open API by Ben Croker. Apparently its authentication returns the member data you're looking for, see http://docs.eeopenapi.apiary.io/#authentication

Related

how to show a "login failed" message in html, depending on servlet response

simple layout (going to be implemented in a complex project)
I've got a simple user-password Login Page.
clicking submit sends a request with those parameters to a LoginServlet.
this servlet checks the database for a match- if it ends positivley the user is being re-directed to the next page.
However, if this ends badly- the user is re-directed to the same page, Login.html
I'm looking for a way to "add" some extra-weight to this re-direction, that as the user gets to the login page more than once, a warning appears along the form stating "the login details are wrong" or something...
how can I achieve this?
from the servlet- response.SendRedirect?
or Forward(request,response)?
on the html, how can I achieve this behavior with java script?
I tried exploring the XMLHttpRequest object, but his method dont seem to appear to retrieve anything useful i'm trying to attach to the response headers.
attaching here my servlet code- just to give you some refernce- but I'm open to suggestions, thanks.
try {
AdminFacade af = (AdminFacade) CouponSystem.getInstance().login(name, password, type);
HttpSession session = request.getSession();
System.out.println("LOGIN SERVLET:session id: " + session.getId());
session.setAttribute("facade", af);
System.out.println("LOGIN SERVLET:facade id: " + af);
session.setAttribute("userType", "admin");
response.setHeader("test1", "this is a test header");
response.sendRedirect(response.encodeRedirectURL("login.html"));
In the servlet, if login credentials are wrong then you do :
request.setAttribute("messageResponse","Login failed: wrong login credentials");
And this you need to check this value in your page like this :
if(request.getAttribute("messageResponse")!=null){
out.println(request.getAttribute("messageResponse"));
}
You need to write above java code in your page.

Conceal URL in javascript code ( URL generated by PHP )

I am looking for a solution to the following:
I have a piece of JS code, that performs a redirection to a URL that is constructed with PHP, and that redirection is only done when the user presses a button on a confirmation dialog.
The code is, as follows:
function one() {
window.location.replace("<?php
if($new_redir == "1") {
echo "$new_second_redirect_URL/?token=$hash";
}
else {
echo "$second_redirect_URL/?token=$hash";
}
?>");
}
It works perfectly fine. What I wanna do is conceal the URL that is displayed in the source code when a user opens the page.
What would be the best way to do that?
You're thinking too much into this to be honest.
If they want to avoid the confirmation screen and get the URL from the source, there's not really much you could do.
The best really is possibly performing an AJAX request on confirmation and getting a CSRF token based URL from the response and using that, but that could end up being overkill as well.
You could also make it into an actual <form></form> form with a few hidden fields (again, such as a CSRF token), and perform the post validation onclick. If it a success - redirect them.
UPDATE:
Use robots.txt to stop bots
Build the QS with JS to stop most bots, something like:
var csrftoken='XJIWHEOU324uipHFOFUHR';
var url="http://url.com/page.php?token=";
url=url+csrftoken;
What you could also do, is something like us actually, although for your use case it could be too much.
Log every single page load into the DB, and check if if they're a first time visitor to the page after confirmation.
AJAX call (jQuery example):
$.post( "url_to_backend_page_to_get_url", {hasSubmittedForm:"true"}, function( data ) {
window.location.href = data;
});

global variables doesn't change value in Javascript

My project is composed by 2 html pages:
index.html, which contains the login and the registration form.
user_logged.html, which contains all the features of a logged-in user.
Now, what I want to do is a control if the user is really logged in, to avoid the case where a user paste a url in the browser and can see the pages of another user.
hours as now, if a user paste this url in the browser:
www.user_loggato.html?user=x#profile
is as if logged in as user x and this is not nice.
My html pages both use js files that contains scripts.
I decided to create a global variable called logged inizialized to false and change the variable to true when the login is succesful.
The problem is that the variable, remains false.
here is the code:
var logged=false; (write in the file a.js)
while in the file b.js I have:
function login() {
//if succesfull
logged=true;
window.location.href = "user_loggato.html?user="+ JSON.parse(str).username + #profilo";
Now with some alerts I found that my variable logged is always false. Why?
Javascript is not the way to go, as it runs on the client side. Even if there would be a way to share javascript variables between different requests, the user could manipulate them.
You have to take a server side technique for this (maybe PHP with sessions).
JS variables will reset on every submit/refresh. You could use sessionStorage or cookies for this purpose. For example:
Put this in your login form:
function login() {
window.sessionStorage[logged] = true;
window.location.href = "user_loggato.html?user="+ JSON.parse(str).username + #profilo";
}
And in your user_loggato.html, you can retrive it like:
function getLoginStatus() {
return window.sessionStorage['logged'];
}
Hope this helps.

How to verify signout and redirect to sign in page

In order to signout from my webapp, I need to call a json to signout (clear all cookies)
logout:->
$.get('/signout.json')
However, I am unsure how I can refresh the page + redirect the web page to the address i want e.g. /#!/signin? after the signout is successful.
if you want to solve it in javascript just use window.location = "yourlinkhere"
I use the same sort of thing to determine if I have to show a push notification.
I also use asp.net and vb.net so not sure if it will help you but you will get a basic idea of what to do :)
//admin is the controller the second is the function.
$.post("/admin/UpdateBrainBattle/
That function will return a json. in this case its about submitting a form. so you check if the form is valid or not.
in the end it shows this:
Return Json(New With {.status = "error"})
or when its good its with .status = "ok"
Then I get the json back on my page.
This is the whole function(including the post function)
$.post("/admin/UpdateBrainBattle/" + sessionId, { questionId: key, startTimeField: startTimeField, startDateField: startDateField },
function(data) {
if (data.status == 'ok'){
parentLi.find('li.onedit').hide();
parentLi.find('li.onview').show();
parentLi.find('div.dateTimeBlock div.view').html(data.value).show();
parentLi.find('div.dateTimeBlock div.edit').hide();
$('.errorBlockSummary').hide();
}
else
{
parentLi.find('span.errorBlock').show();
$('.errorBlockSummary').show();
}
});
This way you can tell your page, if everything was succesful go to this page, otherwise take this action.
Hope this helped you a bit on your way :)
Edit: noted you used a $.get instead, it can work exactly the same way as long as the function you call to has a return value you should be fine.

How do I search results from jquery GET

I'm having a bit of a problem investigating the result from my get in my script. I got the following code to check if a user is still logged in:
$.get("nowhereGet", function(result){
if($(result).find('[id="loginInput"]'))
{
//HTML is in the response then we have been logged out and the user needs to go to
window.location.href = "login";
}
});
Now if the user is logged in Struts will return one html-page in result from my get. If the user has been logged out different page will be returned one with and element id="loginInput"in it.
I thought the above would do the trick but no love. What am I doing wrong?
Is there a better way to do this than to ping the server with a random get? I need a method that performes this check using ajax and any get or post done while logged out will get intercepted and the result will be the login-page instead of the intended page
$('#result').get(......); ???
UPDATE
so the element #result would have what ever the #loginInput has
$('#result').load('login.php #loginInput');
Otherwise look for a json option because the way you are doing it, its kinda messy
Unless you are looking for this
$.get("nowhereGet", function(result){
if(result && $(result).find('#loginInput').length)
{
//HTML is in the response then we have been logged out and the user needs to go to
window.location.href = "login";
}
});
I found an other soloution and with help from Steven Benitez I got it working. Follow the link for more information but in short I let my interceptor do the work instead. If a certain path/action is called the interceptor will return a text stream that I can read from my script.

Categories