Stuck in login page spinning when submitting logging request? - javascript

I have a website, with some pages like any other website.
It works perfectly on my computer(localhost).
But when I uploaded it to a real server, some problems appeared in login pages..
The problem's after I insert my login information and click submit IT DOESN'T redirect me to main page..
It keeps spinning!
$(document).ready(function() {
end_loader();
$('#ulogin-form').submit(function(e) {
e.preventDefault()
var _this = $(this)
var el = $('<div>')
el.addClass('alert alert-danger err_msg')
el.hide()
$('.err_msg').remove()
if ($('#password').val() != $('#cpassword').val()) {
el.text('Password does not match')
_this.prepend(el)
el.show('slow')
$('html, body').scrollTop(0)
return false;
}
if (_this[0].checkValidity() == false) {
_this[0].reportValidity();
return false;
}
start_loader()
$.ajax({
url: _base_url_ + "classes/Login.php?f=login_user",
method: 'POST',
type: 'POST',
data: new FormData($(this)[0]),
dataType: 'json',
cache: false,
processData: false,
contentType: false,
error: err => {
console.log(err)
alert('An error occurred')
end_loader()
},
success: function(resp) {
if (resp.status == 'success') {
location.href = ('./')
} else if (!!resp.msg) {
el.html(resp.msg)
el.show('slow')
_this.prepend(el)
$('html, body').scrollTop(0)
} else {
alert('An error occurred')
console.log(resp)
}
end_loader()
}
})
})
})

As you have stated that the code and everything else works offline and the responses made by the other programmers, I will continue on that for now by asuming it works offline as you have said.
It might be the case that your local enviroment is more up to date then your online server enviroment. As local you could have PHP 8 but online run 7.0
Example: PHP 7.2 added 'PASSWORD_ARGON2ID' and if you have used that then online enviroment PHP 7.1 will never work since it doesn't know what to do.
Please confirm by:
Create a file that contains the following code:
<?php
phpinfo();
?>
and confirm that your online server is atleast equal to your offline version. Further versions might rollback certain functions so try to have the exact same PHP and ?Linux or Apache? version as offline.
After you confirm that the offline and online versions are the same, let's then try the other issue such as "undefined mysqli_stmt::$get->result in class/login.php line50", it would help if you would provide code.
Also, if you upload your work (code) directly to git->to online server, make sure your .gitignore doesn't ignore the files that you need.
Let's hope this helps.

Related

Trying to catch Log failure and 404 with JQuery

I am working on a web Spring MVC 4 application for my end of studies project, the application should connect web and android clients.
I used #RestController to help android app communicate easily via json. I am trying to catch connection failure ex:404 in both web or mobile app, even in the web application i tried to make almost all communication with the server via Ajax hoping to make user more relaxed (Progress bars, Live info hints...) but, one of the problems in countries that after using event.preventDefault() from jQuery, i can't get over it in next actions and the response pages loaded and kept unseen! for example here is my login page example:
login.js
jQuery(document).ready(function ($) {
$("#login-form").submit(function (event) {
//Do somthing...
// Call login function
logViaAjax(event);
// Prevent the form from submitting via the browser.
return false; //Or using event.preventDefault()
});
});
// logViaAjax function
function logViaAjax(event) {
var logObj = {};
logObj["username"] = $("#username").val();
logObj["password"] = $("#password").val();
//the response
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
url: "/login",
data: logObj,
dataType: 'text',
timeout: 10000,
success: function (data) {
if (data.indexOf("login-box") !== -1) {
showLogFail();
}else{
window.location.reload();
//I dont need to reload the page because this gives me login page again... May be if there is a way to get the URL from data!?
}
},
error: function () {
showWarning();
}
});
I am using Spring Security 4 to handle authentification and we know that it gives url ex:/login?fail for failure and get the requested page if succeed and i recently knew that it redirect even before getting in the loginUrl my ex /login. I tried to test if the user logged in on server side and send json response but this could leads to lose the page before requesting login.
I think i should test in the success: function() if url loaded in the jQuery(but not showed) contains ?fail or not, to inform user to change log or password. Else, if it do not, the page user need is charged in the back and all what i need is to show it.
UPDATE
After those little changes all what I need to make is just to keep the page beyond the login page and reshow it. Take note that this function is automatically offered by Spring Security but it still running on background. Ex in my case when user click /messenger the app redirect him to /login to login, if he fail login it gives /login?fail but this page is unseen due to JQuery, else he login successfully it send him to /messenger again…
Try this
var flag;
jQuery(document).ready(function ($) {
$("#login-form").submit(function (event) {
//Do somthing...
// Call login function
logViaAjax(event);
if(flag.status == 404){
return false;
}
});
});
function logViaAjax(event) {
var logObj = {};
logObj["username"] = $("#username").val();
logObj["password"] = $("#password").val();
//the response
flag = $.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
url: "/login",
data: logObj,
dataType: 'text',
timeout: 10000,
success: function (data) {
//Here to move to the page unseen if success and show error hint if it fail...
},
error: function () {
showWarning(); //Show error alerts, this part is DONE!
}
});
Changes Made
► Assigned the AJAX to a variable and dded a condition in the jQuery(document).ready
AJAX - The onreadystatechange Event
Demo Fiddle to show 404 error

Ajax .done() don't work together for me

I have a very strange situation. I have an AJAX function which sends form data to a php codeigniter controller, on json response, it has to deal with the response. first part is working, but later part, which is a .done() function, doesn't work, no matter what I try.
here is my script:
var validator = $('#register-company-form').validate({
rules: {
title: {
required: true,
valueNotEquals: 0
},
/* rules here */
},
highlight: function (element) {
$(element).closest('.form-field').addClass('error-field');
},
unhighlight: function (element){
$(element).closest('.form-field').removeClass('error-field');
},
errorPlacement: function(error, element) {},
submitHandler: function(form) {
var formData = new FormData($(form)[0]);
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false
})
.done(function (response) {
$(".form-field").removeClass("error-field");
$(".item-exists").hide();
if(response.Response == 401) {
$("#company_email").closest('.form-field').addClass('error-field');
$("#company_email").closest(".form-field").find(".item-exists").show();
} else if(response.Response == 402) {
$("#personal_email").closest('.form-field').addClass('error-field');
$("#personal_email").closest(".form-field").find(".item-exists").show();
} else if(response.Response == 403) {
$("#user_name").closest('.form-field').addClass('error-field');
$("#user_name").closest(".form-field").find(".item-exists").show();
} else if(response.Response == 200){
/* load my view */
}
});
return false;
}
});
My PHP script returns following JSON response:
{"Response":200,"Data":null,"Message":null}
After getting this response, my .done() function is supposed to act according to it and load a page, which it is not. I have tried putting console.log() and alert() into it, but now its clear its not responding. Is there any other way to do this or any correction in code?
Please note that the same code really worked fine on another server. This has happened after migration.
Thank you so much for the help!
Thank you so much for your Kind information #DFreind and #JonathanLonowski, with your hints, I finally figured out this problem which took me almost 3 days.
Actually when I looked closely at the html produced by PHP, it said:
1 {"Response":200,"Data":null,"Message":null}
This '1' before the JSON string was generating cannot modify headers error!
After lots of efforts, I just saw a plain goddamn '1' just before opening <?php tag on first line in my controller. Removing this '1' worked like a charm, all errors gone, life saved, dosing in heaven now :-)
Indication for researchers: Please install Firebug if you are facing similar errors and always look into response headers, try experimenting. Most of the time PHP errors mess with your output. In my case, 'headers already sent' error generated because before php started its output, html came in. Watch out for any echo() or set_cookie() functions as well!
Thanks all of you StackOverflowish geeks :)

jQuery and Ajax - cannot POST

I am trying to login to a website using a known username and password and to get some data displayed from the site for a specific user account on that website. I am using jQuery and Ajax for this purpose. This is my code:
$.ajax({
async: false,
cache: false,
type: 'POST',
dataType: 'json', // json...just for example sake
data: ({
'login_username': username,
'secretkey': password
}),
url: 'https://mail.someserver.com/src/redirect.php',
success: function (data) {
alert("SUCCESS!")
if (data === '1') { // server returns a "1" for success
// success!
// do whatever you need to do
} else {
// fail!
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// something went wrong with the request
alert("Failed!");
}
});
I've already made my search around the web and I know that browsers do not permit cross server ajax calls to prevent security issues, but I've already tried to use "jsonp" as dataType to no avail :(
So, what am I doing wrong?
Be sure that your url is not breaking the same origin policy -- that is, the request coming from the client cannot request data from a server from a different domain (there are exceptions to this rule, namingly CORS, but that requires that you make changes to the server/application you're talking to).
The solution to your problem would be to make the request from some server-side script, then in turn having your client application query that script, based on the same machine that's serving the application to the web.
My fault isn't at the code above, my fault was that in my manifest file (I am building a Google Chrome extension) I didn't have set proper permissions (https://*).
Sorry for the frustration!

How to know if url is available?

I have a link redirecting to an intranet direction:
Go
Only users in intranet can access, otherwise they get a 404 error. I want to know if the the url is valid before redirecting, this way users out of intranet won't get the 404 error but a message saying 'You don't have access'. How can I do this with jquery or javascript?.
EDIT:
Well, thank you very much, but unfortunately any method does not work for me. Sorry, I didn't mention that website and intranet url are in differente domain.
Finally I had to validate user IP in codebehind and write or not the intranet url.
You could make an ajax request first, something like:
$.ajax({
url: "http://10.2.68/name/",
context: document.body,
success: function(){
window.location = "http://10.2.68/name/";
}
});
That could be run by binding to the click event on the link.
Not sure if it will work due to cross origin stuff, but might be a good place to start.
You can use this jQuery plugin to make a head request to the remote file, if it comes back with something it is good (and you can display it for instance) otherwise don't show it
Plugin:
http://binarykitten.me.uk/dev/jq-plugins/88-jquery-plugin-ajax-head-request.html
Perhaps use an htaccess file to detect the internal network instead?
The best answer would be to disable the link if it's inactive, before the user tries to click it (why make them try?).
jQuery(function($) { // make sure dom is ready
$.ajax( {
url: url,
//dataType: 'JSONP', //might need this?
complete: function(xhr) { // use complete so it fires on error OR success
if( xhr.status == 200 || xhr.status == 304 ) {
$('#link').addClass('valid');
}
else {
$('#link').addClass('invalid').click(function() { return false; });
}
}
});
});
But if you don't want the call because there are going to be thousands of users looking at the page every minute...
jQuery(function($) { // make sure dom is ready
$('#link').click(function() {
$.ajax( {
url: url,
//dataType: 'JSONP', //might need this?
success: function() {
window.location = url;
},
error: function() {
// does this work with JSONP? be sure to check!
window.alert('could not connect');
}
}
});
});
Assuming your anchor has an ID:
<a id="lnkGo" href="http://10.2.68/name/">Go</a>
And your jQuery code might look like this:
$("#lnkGo").bind("click", function() {
var $that = $(this);
$.ajax({
url: $that.attr("href"),
statusCode: {
200: function() {
window.location = $that.attr("href")
},
404: function () {
alert("Sorry, page is unavailable...");
}
}
});
return false;
});
Also, please keep mind that this won't work on cross-domain issue. The url has to be same as the current domain.

iPhone Web Application: Window.location doesn't seem to work

I have added the required meta tags to my web app so that it can be launched on an iPhone from the springboard with no safari elements (address bar etc).
However, my login page works via JS, with the response coming back as JSON.
In Safari, when not launched as a web app, the redirect works fine (using window.location).
When launched as a web app, the redirect doesn't seem to work properly. The screen will refresh but be on the same page.
Is this a limitation of a web app or (as I suspect) am I doing it wrong?
This is the code that responds to the ajax post
genericPost: function (f, ajaxLoad) {
if (ajaxLoad == undefined)
ajaxLoad = true;
var form = $(f);
var data = form.serialize();
var action = form.attr("action");
$.ajax({
type: 'POST',
url: action,
data: data,
success: function (response) {
if (response.worked) {
//navigate to the next required page
//Notify.showMessage(response.message);
if (response.redirect) {
if (ajaxLoad) {
Notify.showMessage(response.message, "ok");
var back = response.direction == "back";
$.mobile.changePage(response.redirect, "slide", back, true);
}
else {
window.location = response.redirect;
}
}
else {
Notify.showMessage(response.message, "ok");
}
}
else {
Notify.showMessage(response.message, "error");
}
},
dataType: "json",
error: function () {
Notify.showMessage("Could not submit your form at the time. Please try again. Please try again", "error");
}
});
}
Thanks
Ok, so the window.location was a red herring.
The issue was that ios seems to send a different user agent string when running full screen, one that IIS did not like.
IIS therefore decided that this browser did not support cookies or any of that stuff so the authentication token was failing.
This was fixed by adding a app_devices folder to my project and a .browser file.

Categories