Worklight: Challenge-handler not working as expected - session

I used sample challenge handler that comes with Form Based Authentication module. I modified it as per my requirements. In my App, I have one Landing (home) page , where i have link to a login page. Now i want it to function when user click on the login button. I face various problems here:
On first click on Login button, it does authenticate with WL
Server but then it is unable to proceed further to execute login
function logic.
after first click, i have to 2nd time click on
Login button. At 2nd login click it execute login function
perfectly.
When I log out,either it is NOT
removing session from server or what? It only execute log-out
function code (given below). But again after the specified session
time out, it prompts 2nd/3rd time and shows "time out message".
Although user is not loged in again. he is already log-out.
Purpose: I want App to only login when user click on Log-in button, but with just one click. and when i log-out Or time out, it should not keep session active OR shows "session timeout" message after the specified time again & again.
My Challenge Handler:
var aahadAppRealmChallengeHandler = WL.Client.createChallengeHandler("myAppRealm");
var isLandingPage=false , islogout=false;
aahadAppRealmChallengeHandler.isCustomResponse = function(response) {
WL.Logger.debug("I am here >> 1");
if (!response || response.responseText === null) { return false; }
var indicatorIdx = response.responseText.search('j_security_check');
if (indicatorIdx >= 0){ WL.Logger.debug("return true "); return true; }
else {
if(isLandingPage && $.trim($('#fldloginUserID').val()) !="" && $.trim($('#fldloginUserPassword').val()) !="" ) {
WL.Logger.debug("WL.Client.isUserAuthenticated()=" + WL.Client.isUserAuthenticated("myAppRealm"));
if(WL.Client.isUserAuthenticated("myAppRealm")) { WL.Logger.debug("return false "); return false; }
else { WL.Logger.debug("return true "); return true; }
}
WL.Logger.debug("return false "); return false;
}
};
aahadAppRealmChallengeHandler.handleChallenge = function(response) {
WL.Logger.debug("I am here >> 2");
var indicatorIdx = response.responseText.search('j_security_check');
var suc = response.responseText.search('success');
WL.Logger.debug("I am here >> 3 - indicatorIdx =" + indicatorIdx + " Success =" + suc + " - isLandingPage=" + isLandingPage +" islogout=" +islogout);
if (isLandingPage){
if (suc >= 0 ){
WL.Logger.debug("I am here >> 4 - isLandingPage=" + isLandingPage +" suc="+suc);
var reqURL = '/j_security_check'; var options = {};
options.parameters = {
j_username : $.trim($('#fldloginUserID').val().toLowerCase()),
j_password : $.trim($('#fldloginUserPassword').val())
};
options.headers = {};
aahadAppRealmChallengeHandler.submitLoginForm(reqURL, options, aahadAppRealmChallengeHandler.submitLoginFormCallback);
}else {
WL.Logger.debug("I am here >> 5");
WL.SimpleDialog.show(DialogMessages_en.SessionExpired_Tile, DialogMessages_en.SessionExpired_Description ,
[ { text : 'Close', handler : function () {
if(busyIndicator.isVisible())
busyIndicator.hide();
isLandingPage = false; userLogout();islogout=true;
$.mobile.changePage("#landingPage" , { transition: "slide"});
} } ]);
}
}
else {
WL.Logger.debug("I am here >> 6 - isLandingPage=" + isLandingPage +" re-Login Again");
if(indicatorIdx < 1) {
var reqURL = '/j_security_check'; var options = {};
options.parameters = {
j_username : $.trim($('#fldloginUserID').val().toLowerCase()),
j_password : $.trim($('#fldloginUserPassword').val())
};
options.headers = {};
aahadAppRealmChallengeHandler.submitLoginForm(reqURL, options, aahadAppRealmChallengeHandler.submitLoginFormCallback);
}
}
};
aahadAppRealmChallengeHandler.submitLoginFormCallback = function(response) {
var isLoginFormResponse = aahadAppRealmChallengeHandler.isCustomResponse(response);
if (isLoginFormResponse){ isLandingPage=false; aahadAppRealmChallengeHandler.handleChallenge(response); }
else {isLandingPage=true; aahadAppRealmChallengeHandler.submitSuccess(); WL.Logger.debug("aahadAppRealmChallengeHandler.submitSuccess()"); }
};
$('#logindone').bind('click', function () {
WL.Logger.debug(" Button Clicked -Before isLandingPage=" +isLandingPage);
isLandingPage=true;
var reqURL = '/j_security_check'; var options = {};
options.parameters = {
j_username : $.trim($('#fldloginUserID').val().toLowerCase()),
j_password : $.trim($('#fldloginUserPassword').val())
};
options.headers = {};
aahadAppRealmChallengeHandler.submitLoginForm(reqURL, options, aahadAppRealmChallengeHandler.submitLoginFormCallback);
loginAuthenticateUser();
});
my Login Function
function loginAuthenticateUser() {
WL.Logger.debug("Calling loginAuthenticateUser()....");
busyIndicator.show();
if ($.trim( $("#fldloginUserID").val()) !="" && $.trim( $("#fldloginUserPassword").val()) !="") {
authenticateLDAPUsers( $.trim( $("#fldloginUserID").val().toLowerCase() ) , $.trim( $("#fldloginUserPassword").val() ));
}else {
if(busyIndicator.isVisible())
busyIndicator.hide();
simpleDialogDemo(DialogMessages_en.LoginFailed_MsgTitle , DialogMessages_en.LoginFailed_MsgDescription);
}
}
Log-out Function
function userLogout() {
WL.Logger.debug("Logout....");
WL.TabBar.setVisible(false);
WL.Client.logout('myAppRealm', {onSuccess: function(){} });
$.mobile.changePage("#landingPage" , { transition: "slide"});
var options = {onSuccess: function() {WL.Logger.debug("collection closed");}, onFailure: function() { WL.Logger.debug("collection closing failed"); } };
WL.JSONStore.closeAll(options);
}
authenticationConfig.xml (Realms)
<realm loginModule="Strongme" name="myAppRealm">
<className>com.worklight.core.auth.ext.FormBasedAuthenticator</className>
<parameter name="login-page" value="login.html" />
</realm>
Worklight.properties
serverSessionTimeout=5
Any suggestion please.
Thanks

In case of FormBasedAuthentication you need to trigger authentication before actually submitting credentials. Therefore you need to call WL.Client.login("realm-name") in your app.
In case authentication requires immediately on app startup - call WL.Client.login(..) in your wlEnvInit or wlCommonInit function. In case it is requires on a later stage - call it once you need it.

Related

Ajax request does not work if i dont write return false at the end

This is my validation function written on button click.
function chk_add_area()
{
var areaCountry=$('#areaCountry').val();
var areaCity=$('#areaCity').val();
var area=$('#area').val();
if(areaCountry.trim()=="")
{
$('#err_areaCountry').fadeIn('slow');
$('#err_areaCountry').html("Please Select Country");
$('#areaCountry').focus();
$('#err_areaCountry').fadeOut(3000);
return false;
}
else //if(areaCountry.trim()!="" && areaCity.trim()!="" && area.trim()!="")
{
$.ajax({
url:'ajax.php?action=duplicatearea&areaCountry='+areaCountry+'&areaCity='+areaCity+'&area='+area,
type:'get',
success:function(res)
{
if(res=="exists")
{
$('#err_div').html("Area already exists");
}
}
});
//return false;
}
/* else
{
return true;
} */
}`
if i uncomment return false,it works properly but then the form does not submit on success & i cant proceed further.
Can anyone tell me why?
You need a return false if the area already exists, otherwise drop through.
You don't need to return true; just exiting from the function works fine.
function chk_add_area() { // onsubmit handler
var areaCountry = $('#areaCountry').val().trim();
var areaCity = $('#areaCity').val().trim();
var area = $('#area').val().trim();
if ( areaCountry == "" ) {
$('#err_areaCountry').fadeIn('slow');
$('#err_areaCountry').html("Please Select Country");
$('#areaCountry').focus();
$('#err_areaCountry').fadeOut(3000);
return false;
}
if ( areaCity == "" || area == "" ) {
$('#err_div').html("Please Select City and Area");
return false;
}
$.ajax({
url: 'ajax.php?action=duplicatearea&areaCountry=' + areaCountry +
'&areaCity=' + areaCity + '&area=' + area,
type: 'get',
async: false, // EDIT: added Dec 30
success: function(res) {
if ( res == "exists" ) {
$('#err_div').html("Area already exists");
return false;
}
}
// allow form submit to proceed
}
Also, I recommend using POST instead of GET because GET is cacheable. Someone might add the same area twice.

Return user id along with Ajax Success response

I have Ajax login submit that works just fine. Now i need to send the $user_id back to the login page on success. But cant figure out how.
Below is what i have.
This is the php page
<?
if (!securePage($_SERVER['PHP_SELF'])){die();}
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: account.php"); die(); }
//Forms posted
if(!empty($_POST))
{
$errors = array();
$username = sanitize(trim($_POST["user"]));
$password = trim($_POST["password"]);
//Perform some validation
//Feel free to edit / change as required
if($username == "")
{
$response['success'] = false;
}
if($password == "")
{
$response['success'] = false;
}
if(count($errors) == 0)
{
//A security note here, never tell the user which credential was incorrect
if(!usernameExists($username))
{
$response['success'] = false;
}
else
{
$userdetails = fetchUserDetails($username);
//See if the user's account is activated
if($userdetails["active"]==0)
{
$response['success'] = false;
}
else
{
//Hash the password and use the salt from the database to compare the password.
$entered_pass = generateHash($password,$userdetails["password"]);
if($entered_pass != $userdetails["password"])
{
//Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing
$response['success'] = false;
}
else
{
//Passwords match! we're good to go'
$response['success'] = true;
}
}
}
}
}
//$user_id = $loggedInUser->user_id;
echo json_encode($response);
?>
Here is the ajax that calls the php page. And also where i need to retrieve the ID from php page.
<script type="text/javascript">
//login ajax to send over user and pass LS
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
$("#submitButton",form).attr("disabled","disabled");
var e = $("#user", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
var str = form.serialize();
//McDOn(str);
$.ajax({
type: 'POST',
url: 'http://vsag.actualizevps.com/loginmobile.php',
crossDomain: true,
data: {user: e, password :p},
dataType: 'json',
async: false,
success: function (response){
//alert ("response");
if (response.success) {
//alert("you're logged in");
window.localStorage["user"] = e;
//window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location = "create.html";
}
else {
alert("Your login failed");
//window.location("main.html");
location.reload();
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter user and password");
}
return false;
}
</script>
the $response value is just true or false at the moment, you could return an array:
$response = array("Success" => true, "UserId" => $user_id);
and on you AJAX response, the response variable
response.UserId
will contain the user id

Synchronizing jQuery idle timeout in multiple tabs

I am using jQuery idle timeout plugin by Eric Hynds
My question is simple but I know there won't be any simple answer to this.
The plugin works great when the website is opened in only one tab. What I want to do is when user opens the website in any number of tabs it should there should only one background timer but the info message should be shown on all tabs.
Consider for example user opens a website in 3 different tabs but actively uses only one tab(obviously) so currently the plugin senses that user is inactive on that tab for specified time and logs him out which is not correct as user still actively using other tab.
I know I have to put some hacks somewhere but really dont understand where and how. If anyone had already done this it would really help me alot. Also any suggestions are most welcome. Pls help guys.
I had the same issue! An idle timer can communicate (stay in sync) across multiple windows & tabs using localStorage variables. Most modern browsers support this feature. On github, marcuswestin/store.js provides good functionality with 'fallback' behavior for older browsers.
Here is the 'testing' code for an idleTimer plugin which provides synchronized windows/tabs (must all be within the same domain). It sets 2 localStorage variables to track the state of the user's session.
You can see a demo of this code here. Open multiple windows/tabs and observe.
http://jillelaine.github.io/jquery-idleTimeout/
/**
* This work is licensed under the MIT License
*
* Configurable idle (no activity) timer and logout redirect for jQuery.
* Works across multiple windows, tabs and iframes from the same domain.
*
* Dependencies: JQuery v1.7+, JQuery UI, store.js from https://github.com/marcuswestin/store.js - v1.3.4+
*
* Commented and console logged for debugging with Firefox & Firebug or similar
* version 1.0.6
**/
/*global jQuery: false, document: false, store: false, clearInterval: false, setInterval: false, setTimeout: false, window: false, alert: false, console: false*/
/*jslint indent: 2, sloppy: true, plusplus: true*/
(function ($) {
$.fn.idleTimeout = function (options) {
console.log('start');
//##############################
//## Configuration Variables
//##############################
var defaults = {
idleTimeLimit: 30000, // 30 seconds for testing. 'No activity' time limit in milliseconds. 1200000 = 20 Minutes
dialogDisplayLimit: 20000, // 20 seconds for testing. Time to display the warning dialog before redirect (and optional callback) in milliseconds. 180000 = 3 Minutes
redirectUrl: '/logout', // redirect to this url on timeout logout. Set to "redirectUrl: false" to disable redirect
// optional custom callback to perform before redirect
customCallback: false, // set to false for no customCallback
// customCallback: function () { // define optional custom js function
// perform custom action before logout
// },
// configure which activity events to detect
// http://www.quirksmode.org/dom/events/
// https://developer.mozilla.org/en-US/docs/Web/Reference/Events
activityEvents: 'click keypress scroll wheel mousewheel', // separate each event with a space
//dialog box configuration
dialogTitle: 'Session Expiration Warning',
dialogText: 'Because you have been inactive, your session is about to expire.',
// server-side session keep-alive timer
sessionKeepAliveTimer: 600000 // Ping the server at this interval in milliseconds. 600000 = 10 Minutes
// sessionKeepAliveTimer: false // Set to false to disable pings
},
//##############################
//## Private Variables
//##############################
opts = $.extend(defaults, options),
checkHeartbeat = 2000, // frequency to check for timeouts - 2000 = 2 seconds
origTitle = document.title, // save original browser title
sessionKeepAliveUrl = window.location.href, // set URL to ping to user's current window
keepSessionAlive, activityDetector,
idleTimer, remainingTimer, checkIdleTimeout, idleTimerLastActivity, startIdleTimer, stopIdleTimer,
openWarningDialog, dialogTimer, checkDialogTimeout, startDialogTimer, stopDialogTimer, isDialogOpen, destroyWarningDialog,
countdownDisplay, logoutUser,
checkForIframes, includeIframes, attachEventIframe; // iframe functionality
//##############################
//## Private Functions
//##############################
keepSessionAlive = function () {
if (opts.sessionKeepAliveTimer) {
var keepSession = function () {
if (idleTimerLastActivity === store.get('idleTimerLastActivity')) {
console.log('keep session alive function');
$.get(sessionKeepAliveUrl);
}
};
setInterval(keepSession, opts.sessionKeepAliveTimer);
}
};
activityDetector = function () {
$('body').on(opts.activityEvents, function () {
if (isDialogOpen() !== true) {
console.log('activity detected');
startIdleTimer();
} else {
console.log('dialog open. activity ignored');
}
});
};
checkIdleTimeout = function () {
var timeNow = $.now(), timeIdleTimeout = (store.get('idleTimerLastActivity') + opts.idleTimeLimit);
if (timeNow > timeIdleTimeout) {
console.log('timeNow: ' + timeNow + ' > idle ' + timeIdleTimeout);
if (isDialogOpen() !== true) {
console.log('dialog is not open & will be opened');
openWarningDialog();
startDialogTimer();
}
} else if (store.get('idleTimerLoggedOut') === true) { //a 'manual' user logout?
logoutUser();
} else {
console.log('idle not yet timed out');
if (isDialogOpen() === true) {
console.log('dialog is open & will be closed');
destroyWarningDialog();
stopDialogTimer();
}
}
};
startIdleTimer = function () {
stopIdleTimer();
idleTimerLastActivity = $.now();
store.set('idleTimerLastActivity', idleTimerLastActivity);
console.log('start idle timer: ' + idleTimerLastActivity);
idleTimer = setInterval(checkIdleTimeout, checkHeartbeat);
};
stopIdleTimer = function () {
clearInterval(idleTimer);
};
openWarningDialog = function () {
var dialogContent = "<div id='idletimer_warning_dialog'><p>" + opts.dialogText + "</p><p style='display:inline'>Time remaining: <div style='display:inline' id='countdownDisplay'></div></p></div>";
$(dialogContent).dialog({
buttons: {
"Stay Logged In": function () {
console.log('Stay Logged In button clicked');
destroyWarningDialog();
stopDialogTimer();
startIdleTimer();
},
"Log Out Now": function () {
console.log('Log Out Now button clicked');
logoutUser();
}
},
closeOnEscape: false,
modal: true,
title: opts.dialogTitle
});
// hide the dialog's upper right corner "x" close button
$('.ui-dialog-titlebar-close').css('display', 'none');
// start the countdown display
countdownDisplay();
// change title bar to warning message
document.title = opts.dialogTitle;
};
checkDialogTimeout = function () {
var timeNow = $.now(), timeDialogTimeout = (store.get('idleTimerLastActivity') + opts.idleTimeLimit + opts.dialogDisplayLimit);
if ((timeNow > timeDialogTimeout) || (store.get('idleTimerLoggedOut') === true)) {
console.log('timeNow: ' + timeNow + ' > dialog' + timeDialogTimeout);
logoutUser();
} else {
console.log('dialog not yet timed out');
}
};
startDialogTimer = function () {
dialogTimer = setInterval(checkDialogTimeout, checkHeartbeat);
};
stopDialogTimer = function () {
clearInterval(dialogTimer);
clearInterval(remainingTimer);
};
isDialogOpen = function () {
var dialogOpen = $("#idletimer_warning_dialog").is(":visible");
if (dialogOpen === true) {
return true;
}
return false;
};
destroyWarningDialog = function () {
console.log('dialog destroyed');
$(".ui-dialog-content").dialog('destroy').remove();
document.title = origTitle;
};
// display remaining time on warning dialog
countdownDisplay = function () {
var dialogDisplaySeconds = opts.dialogDisplayLimit / 1000, mins, secs;
remainingTimer = setInterval(function () {
mins = Math.floor(dialogDisplaySeconds / 60); // minutes
if (mins < 10) { mins = '0' + mins; }
secs = dialogDisplaySeconds - (mins * 60); // seconds
if (secs < 10) { secs = '0' + secs; }
$('#countdownDisplay').html(mins + ':' + secs);
dialogDisplaySeconds -= 1;
}, 1000);
};
logoutUser = function () {
console.log('logout function');
store.set('idleTimerLoggedOut', true);
if (opts.customCallback) {
console.log('logout function custom callback');
opts.customCallback();
}
if (opts.redirectUrl) {
console.log('logout function redirect to URL');
window.location.href = opts.redirectUrl;
}
};
// document must be in readyState 'complete' before looking for iframes
checkForIframes = function () {
var docReadyCheck, isDocReady;
docReadyCheck = function () {
if (document.readyState === "complete") {
console.log('check for iframes, now that the document is complete');
clearInterval(isDocReady);
includeIframes();
}
};
isDocReady = setInterval(docReadyCheck, 1000);
};
// look for iframes
includeIframes = function () {
console.log('include iframes start');
var foundIframes = document.getElementsByTagName('iframe'), index, iframeItem;
if (foundIframes.length > 0) { //at least one iframe found
console.log('iframes found: ' + foundIframes.length);
// attach events to each iframe found
for (index = 0; index < foundIframes.length; index++) {
iframeItem = foundIframes.item(index);
if (iframeItem.attachEvent) { // IE < 11. Returns a boolean true/false
console.log('attach event to iframe. Browser IE < 11');
iframeItem.attachEvent('onload', attachEventIframe(index));
} else { // IE >= 11 and FF, etc.
console.log('attach event to iframe. Browser NOT IE < 11');
iframeItem.addEventListener('load', attachEventIframe(index), false);
}
} // end for loop
} // end if any iframes
};
// attach events to each iframe
attachEventIframe = function (index) {
var iframe = $('iframe:eq(' + index + ')').contents().find('html');
iframe.on(opts.activityEvents, function (event) {
console.log('bubbling iframe activity event to body of page');
$('body').trigger(event);
});
};
//###############################
// Build & Return the instance of the item as a plugin
// This is your construct.
//###############################
return this.each(function () {
if (store.enabled) {
idleTimerLastActivity = $.now();
store.set('idleTimerLastActivity', idleTimerLastActivity);
store.set('idleTimerLoggedOut', false);
} else {
alert('Please disable "Private Mode", or upgrade to a modern browser. Or perhaps a dependent file missing. Please see: https://github.com/marcuswestin/store.js');
}
activityDetector();
keepSessionAlive();
startIdleTimer();
checkForIframes();
});
};
}(jQuery));

Facebook check in and windows phone

I've got a script that essentially gives the user the ability to check in to a specific location when they click it. Upon clicking it, it checks them into the same location each time.
On desktop this works fine and I suspect it works on Android too. I have a WP and thus obviously I want to get it working on there. This feature is pretty much going to be used exclusively on mobile so getting it working cross-device is important.
Now, to the actual issue. Upon clicking the check in button on WP it loads a blank page and hangs there. Whilst this may be a signal that it perhaps has checked in, when I look it hasn't. So it's hanging there and doing nothing.
This is the URL it's hanging on: https://m.facebook.com/dialog/oauth?display=touch&domain=www.staffscuesociety.com&scope=publish_stream&api_key=API_KEY&app_id=APP_ID&locale=en_US&sdk=joey&access_token=ACCESS_TOKEN&client_id=CLIENT_ID&redirect_uri=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter.php%3Fversion%3D18%23cb%3Df35fef827217048%26origin%3Dhttp%253A%252F%252Fwww.staffscuesociety.com%252Ff166245837c3b6e%26domain%3Dwww.staffscuesociety.com%26relation%3Dopener%26frame%3Df398a7113310e64&origin=2&response_type=token%2Csigned_request
and this is the code:
var button;
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
window.fbAsyncInit = function() {
FB.init({
appId : '260445377421174',
channelUrl : '//www.staffscuesociety.com/checkin/channel.html'
});
button = document.getElementById('checkinWidget');
if (!button) return;
if (!getPost()) {
allowCheckin();
} else {
allowUndo();
}
};
function setPost(value) {
var d = new Date();
d.setDate(d.getTime() + (10 * 60 * 1000));
document.cookie = 'post=' + escape(value) + ';expires=' + d.toUTCString();
}
function getPost() {
return getCookie('post');
}
function getCookie(key) {
currentcookie = document.cookie;
if (currentcookie.length > 0) {
firstidx = currentcookie.indexOf(key + '=');
if (firstidx != -1) {
firstidx = firstidx + key.length + 1;
lastidx = currentcookie.indexOf(';', firstidx);
if (lastidx == -1) {
lastidx = currentcookie.length;
}
return unescape(currentcookie.substring(firstidx, lastidx));
}
}
return '';
}
function checkin() {
allowNothing();
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me/permissions', function (permissions) {
if (permissions.data.length > 0 && permissions.data[0].publish_stream) {
FB.api('/me/feed', 'post', { message: null, place: '117072761683514' }, function(post) {
if (!post || post.error) {
showError();
} else {
setPost(post.id);
allowUndo();
}
});
} else {
allowCheckin();
}
});
} else {
allowCheckin();
}
}, {scope : 'publish_stream'});
}
function undo() {
allowNothing();
FB.api('/' + getPost(), 'delete', function(response) {
setPost('');
allowCheckin();
});
}
function allowNothing() {
button.onclick = function() { };
button.className = 'pressed';
}
function allowCheckin() {
button.onclick = checkin;
button.className = '';
}
function allowUndo() {
button.onclick = undo;
button.className = 'pressed tick';
}
function showError() {
button.className = 'pressed error';
}
}

AJAX to submit to page using POST method

I have this piece of AJAX that validates the login credentials by sending the username and password via GET method. I want to update this code to use POST method, but I don't know where to start or what to change.
The reason I'm doing this is the data that will be sent to another page will be big and GET doesn't send it all.
This is the code I have:
function createObject()
{
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var usr;
var psw;
function login()
{
usr = encodeURI(document.getElementById('username').value);
psw = encodeURI(document.getElementById('password').value);
http.open('get', 'login.php?user='+usr+'&psw='+psw);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply()
{
if(http.readyState == 4)
{
var response = http.responseText;
if(response == 0)
{
alert('Login failed! Verify user and password');
}
else
{
alert('Welcome ' + usr);
document.forms["doSubmit"].elements["usr"].name = "usr";
document.forms["doSubmit"].elements["usr"].value = usr;
document.forms["doSubmit"].elements["pwd"].name = "pwd";
document.forms["doSubmit"].elements["pwd"].value = psw;
document.forms["doSubmit"].action = location.pathname + "user/";
document.forms["doSubmit"].submit();
}
}
}
This code uses GET and send the parameters in the URL and waits for the reply. I want to send the parameters via POST due to size.
The data that will be sent is for a <textarea name='taData' id='taData'></textarea>
Change the line of code as described below:
From:
http.open('get', 'login.php?user='+usr+'&psw='+psw);
To:
http.open('post', 'login.php');
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.send('user=' + usr + '&psw=' + psw + '&tboxName=' + yourTextBoxValue);
More on the topic:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849(v=vs.85).aspx

Resources