Log in from another php file with jquery load function - javascript

I would like to do a web site using Aptana IDE and xampp, and it has a few pages. Index page is where all users which does not log in the system and home is where all users which does log in the system must visit. I am very new to develop web site. Because of that I am changing a lot of and vital things during the development. An here my problem is began.
I have created log and sign pages separately using HTML5, CSS, Javascript, JQuery and Php. To achieve more quality service, decided to use also Ajax. These pages works correctly, log page can control validation with jquery
$('#login-form').validate({
//validation rules, messages and submitHandler(ajax code) goes here});
and with using ajax, it can communicate with php file and mysql database so can check whether the user is exist or not.
$.ajax({
type: 'POST',
url: 'log.php',
data: strAjax, //username and password
success: function(data) { //data is echoing from php file either as true or false
if(data) {
window.location.href = "home.php";
}
else {
//some error messages
}
}
});
Sign systems works like it and correctly. But I do not like the design of these pages because of emptiness. So in index file when user click log in button, the log file is showing inside a div with jquery load function.
$(".jumbotron").load("login.html").hide().fadeIn(1500).delay(5000);
Same thing for sign system as well. For good looking, I am satisfied but...
The whole system messed up. (I want to cry) I have to think before start to coding web site, very bad I know but this is my first complete web site. How can achieve a system working properly in this way? I have searched some pages on the internet and they said that the ajax can not work across the pages or something like that. I am also new to stack overflow too, so some important thing will be forgotten. I can edit if you want more information.
Thank You and Regards...
EDIT 1:
<div class="jumbotron">
<div class="container">
<h1>//sometext</h1>
<p>//some text</p>
</div>
</div>
Firstly this is showing on the screen. And when the user press login button, jquery load function running which is above. And loads login.html which works properly by itself.
<form id="login-form" class="text-left">
<div class="form-group">
<label for="lg_username" class="sr-only">Username</label>
<input type="text" class="form-control" id="lg_username" name="username" placeholder="username"
data-container="body" data-toggle="popover" data-placement="left" data-content=""
value="">
</div>
<div class="form-group">
<label for="lg_password" class="sr-only">Password</label>
<input type="password" class="form-control" id="lg_password" name="password" placeholder="password"
data-container="body" data-toggle="popover" data-placement="left" data-content="">
</div>
<div class="form-group login-group-checkbox">
<input type="checkbox" id="lg_remember" name="lg_remember">
<label for="lg_remember">remember</label>
</div>
<button type="submit" class="login-button">Submit</button>
</form>
The jquery validation works right. My rules are valid. If the inputs are ok upon my rules, it send me to home.php. I think ajax code can not work.
submitHandler: function() {
var username = $('#lg_username').val();
var password = $('#lg_password').val();
var checkbox = $('#lg_remember').is(":checked");
var strAjax = "username=" + username + "&password=" + password + "&checkbox=" + checkbox;
$.ajax({
type: 'POST',
url: 'logDeneme.php',
data: strAjax,
cache: false,
success: function(data) {
if(data) {
window.location.href = "home.php";
}
else {
//error message. but when this code run, always send to home page.
}
}
});
return false;
}
This parts all works. It does not works inside index.php. My question is why and how to handle this!

Problem 1
Your form is submitting via a GET request because the JS is not getting called (see #2 below) and the HTML is likely declared like this:
<form action='log.php'>
[...]
</form>
You must specify method='post' to submit POST data.
Problem 2
Unless you're using a jQuery plugin there is no .validate event for forms. You want to use .submit.
Finally, make sure all your javascript is in $(document).ready(function() { ... }); or it won't execute at the right time. Look in the Firefox/Chrome developer console, it's a lifesaver for debugging.

Related

Display PHP var in HTML (with jQuery)

I'm searching for the best solution to display information which I store in PHP variable (which I get from a MySQL DB).
I was thinking to use jQuery. My questions:
With the input field I receive the number of the Member.
I store a new variable called $imgMember with the img name.
Questions:
I want to display this image each time a user enters a number at <div class="boxImageMember"> (which I already validated through PHP and made a variable ($imgMember) of it.
How should I access it? Do I need to store those variable with AJAX? Internal/external jQuery? Or do I need to think otherwise? Im stuck in my head.
Im totally stuck with the way I how to process this.
HTML:
<div id="header">
<div class="header-content">
<img src="img/logo-dqmih.png" width="60px">
</div>
</div>
<div class="container">
<div class="boxImageMember">HERE I WANT TO DISPLAY A USER IMAGE</div>
<div class="boxInformationMember"></div>
<form action="" method="post">
<input type="text" id="MemberNumberEntry" name="staffNumber">
<button type="submit" name="action">
</form>
</div>
jQuery:
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
console.log(MemberNumberEntry);
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
Your jQuery script would do something like this
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
//console.log(MemberNumberEntry);
$.ajax({
url: '/your-php-script.php',
method: 'POST',
data: {
MemberNumberEntry: MemberNumberEntry
},
success: function(response){
//If call goes well, you use the image here.
}
});
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
You're basically sending an HTTP POST request to your PHP script that will accept the image ID like a normal post request, using $_REQUEST or $_POST.
There are tonnes of options to configure with jQuery, you can look at the docs here. For more information on working with images in PHP and AJAX, this answer is useful.

Need to grab input from a form, process it with php, having the option the reload the page depending on the answer

this is my problem.
I have a startpage website on this address: http://battlestation.rocks/
It mostly revolves around a search bar in the front page that executes commands. Presently, every command is processed with php, like so:
if (isset($_POST['searchBar'])) {
$originalcommand = $_POST['searchBar'];
processcommand($originalcommand);
return;
}
With this, every command reloads the page, which is a waste as most of the times it just opens some link from the startpage. In other cases, the startpage is changed by the commands, and thus in those cases I would like the page to reload.
I've seen from other questions that you can have the page not reload with AJAX, but none of the answers I've seen send the form input to php for processing, nor do they include the option to reload if necessary.
I'm very much a hobbyist coder and have zero experience with AJAX, please don't get too technical on me. I'm obsessed with this startpage, I just need to get this working as intended. Please help!
If you use PHP directly then the page needs to reload. If you use AJAX then you can send it so without reloading. !-You need a new PHP file in which you process the input-! An example with jquery but works the same:
You normal site:
<form action=''>
<input type='email' id='email' placeholder='E-Mail' required=""/>
<input type='password' id='pwd' placeholder='Passwort' required=""/>
<button id='go_login'>Go</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$('#go_login').click(function() {
var bn = $('#email').val();
var pw = $('#pwd').val();
$.post('newphpsite.php', {'bn': bn, 'pw': pw}, function(data) {
alert(data); //send back echo from PHP
});
return false; //The form is not sent and does not reload the page.
});
</script>
newphpsite.php :
<?php
$bn = $_POST['bn'];
$pw = $_POST['pw'];
echo $bn."".$pw;
?>
?>
Yes, you should send the data via AJAX. One popular option is to use jQuery. Below is a simplified example using jQuery.
First, the HTML:
<input id="searchBar" name="searchBar" type="text" />
<button id="submit">Search</button>
<div id="searchResults"></div>
Next the jQuery:
<script type="text/javascript">
$("#submit").click(function() {
$.ajax({
type: "post",
url: "search.php", // Your PHP file
data: {
searchBar: $("#searchBar").val()
},
success:function(results) {
// Do something with your results
$("#searchResults").html(results);
}
});
});
</script>

Javascript redirect not functioning after form submit. Asp Classic, Javascript

Alright, after hours and hours of research and trying things I am completely stuck at the moment. I coded quite a lot for a web page so I'll try to summarize it as good as possible.
So I've got this ASP CLASSIC page where a user can create a ticket using a form.
The coded page consists out of 3 main parts:
Javascript client side error handling.
ASP CLASSIC server side error handling after submission (checking if
database values exists like email).
The form submitting (sending an email + inserting the data into the
database).
After the form is submitted there is some ASP error handling. When a error is encountered a Javascript popup box will be shown with the error and the data submission and email is being cancelled.
The form is auto filled with the inputted values (with asp code) so that after a error the inputted values are kept in the form. This all works.
The form code:
<div align="left"><form name="myForm" method="post" style="display:inline" onsubmit="return(validate());">
<div class="FormTitel">Voor welke afdeling is de ticket bestemd?
</div>
<div class="radio">
<input type="radio" class="radio" name="automatisering" value="Automatisering" checked <% if Request.Form("automatisering") = "Automatisering" then response.write("checked")%>>Automatisering
<input type="radio" class="radio" name="automatisering" value="Software" <% if Request.Form("automatisering") = "Software" then response.write("checked")%>>Software
<div id="Error1" style="display:none" color="white"></div>
</div>
<div class="FormTitel">Soort ticket
</div>
<div class="radio">
<input type="radio" class="radio" name="probleem" value="Probleem" <% if Request.Form("probleem") = "Probleem" then response.write("checked")%>>Probleem
<input type="radio" class="radio" name="probleem" value="Wijziging"<% if Request.Form("probleem") = "Wijziging" then response.write("checked")%>>Wijziging
<div id="Error2" style="display:none" color="white"></div>
</div>
<div class="FormTitel">Uw gegevens
</div>
<div>
<input type="text" name="Name" class="name" placeholder="Vul hier uw voor- en achternaam in" style="color:#888;"
onfocus="inputFocus(this)" onblur="inputBlur(this)" value="<%=Request.Form("Name")%>">
<div id="Error3" style="display:none" color="white"></div>
</div>
<div>
<input type="text" name="EMail" class="name" placeholder="Vul hier uw emailadres in" style="color:#888;"
onfocus="inputFocus(this)" onblur="inputBlur(this)" value="<%=Request.Form("EMail")%>"/>
<div id="Error4" style="display:none" color="white"></div>
</div>
<input type="submit" class="ticketVerstuur" value="Verstuur ticket" />
</form></div>
*The error id's are client side styling boxes that are being showed when a Validation returns false (with javascript).
*Sorry for not translating the title's, names, etc. but that would be quite some work;)
The ASP IF statements in the form make sure that the inputted values are returned and not lost when a error is being showed.
Alright now for the part where it goes wrong.
After submission, which is being activated by If Request.ServerVariables("REQUEST_METHOD") = "POST" Then some stuff is happening. Namely, the input values are being parameterized for sql injection, some input values are being checked on the server side, for example; does the submitted email exists in the database? and if the server side validation is all fine then the data is being inserted in the database and a email is being send.
The error messages on the server side are being shown to the user as javascript popup boxes. This works.
The javascript popup code:
function popup(popup,container) {
var thisPopup = this;
thisPopup.load = function() {
container.animate({
"opacity": "0.3"
},250, function() {
popup.fadeIn("250");
});
container.off("click").on("click", function() {
thisPopup.unload();
});
$('#closePop').off("click").on("click", function() {
thisPopup.unload();
});
}
thisPopup.unload = function() {
popup.fadeOut("250", function(){
container.animate({
"opacity": "1"
},250);
});
}
}
The function is called in the submit code like so: new popup($("#popup_box"),$("#container")).load(); The popup div is put above the form and the container is wrapped around the form. (popup works).
The problem though is that after the server side validation is all good, so the data goes into the database and the email is send, I popup a new javascript box saying that the everything was successful. When it is successful I want to clear my form (to avoid confusion).
First I try'd to do this with a response.redirect ("mypage.asp"). Though, when I use this the javascript popup box wont show.
Then I try'd to use a window.location.replace("http://stackoverflow.com"); on my close / unload function of the popup box, this has no effect though (data is not being cleared). Also try'd it with setting a var to true when the popup is unloaded and then later checking the var if it is set to true (then redirect) but this also doesn't work, even a direct javascript redirect, so without the popup, in the submission code (after all is successful) doesn't seem to work for some reason. In matter of fact only alert seems to work. Here the example of the adjusted popup unload:
thisPopup.unload = function() {
window.location.replace("http://stackoverflow.com");
popup.fadeOut("250", function(){
container.animate({
"opacity": "1"
},250);
});
}
So what causes this problem and how can I fix it? I can imagine it requires a bit more of my code so don't hesitate to ask for it, but the post is big enough as it is.
Last but not least a short summary of how my code is setup:
<html>
<head>
stylesheet
<title></title>
</head>
<body>
<javascript>
Pop up box code + validate form code
</javascript>
<form>
</form>
</body>
</html>
<asp server side code (on submit)>
Some functions (mail - anti injection) + request form values
Validation server side (with javascript poups)
Insert data in database
Sending mail
I think you were on the right track with the redirect. To get a pop-up to show after a redirect, do something like this:
response.redirect "mypage.asp?ShowSuccess=true"
Then in mypage.asp use this:
<%
if request("ShowSuccess") = "true" then
onload = "alert('Success message here!');"
end if
%>
<body onload="<%=onload%>">

PHP included JavaScript is not working properly in Jquery Mobile

In my jquery mobile web app I include a Login-Form on every page the user is navigating to. I do that so that the user could login at every time he wants to, not just on the start page.
Since I do the Form submitting procedure with my very own Ajax logic, I disabled the Jquery Mobile Ajax logic with data-ajax="false" on the Form. The Ajax logic is implemented with JavsScript. On the start page everything works fine, but if I navigate to another page (through a link on the start page), my JavaScript is not firing anymore, but the form is submitted via the Jquery mobile own Ajax logic (and therefore it don't works).
The code (which I include at every page) looks like this:
<div data-role="fieldcontain">
<form id="loginForm" data-ajax="false" onsubmit="login();return false;">
<div data-role="fieldcontain">
<h2>Login</h2>
<label for="textinput1">
Email
</label>
<input name="emaillogin" id="textinput1" placeholder="Email" value=""
type="text">
<label for="textinput2">
Password
</label>
<input name="passwordlogin" id="textinput2" placeholder="Password" value=""
type="password">
</div>
<input type="submit" data-icon="ok" data-iconpos="left" value="OK">
<input type="hidden" name="inputCase" value="login">
</form>
</div>
The JavaScript (which is just at the end of the Code stated above) looks like that:
<script>
function login()
{
var request = $.ajax({
url: "../case.php",
type: "POST",
data: $('#loginForm').serialize(),
dataType: "json"
});
request.done(function(msg) {
if(parseInt(msg.status)==1)
{
//top_notification("Willkommen zurück!","success");
window.location="index.php";
}
else if(parseInt(msg.status)==0)
{
alert(msg.text);
}
else {
alert("Gibts nicht");
}
});
request.fail(function(jqXHR, textStatus) {
alert("Fehler");
});
}
</script>
Maybe I got the Jquery Mobile "we replace just the page-div with the other page-div from the new URL" thing wrong, but I understand it in that way that my whole JS logic will also be pulled from the new ressource.
EDIT Thanks. I have updated my JS code, which looks now like that:
<script>
$(document).on('pageinit', '[data-role="page"]', function(){
$(document).on('click','#submit-btn',function() {
login();
});
});
function login()
{
var request = $.ajax({
url: "../case.php",
type: "POST",
data: $('#loginForm').serialize(),
dataType: "json"
});
request.done(function(msg) {
if(parseInt(msg.status)==1)
{
//top_notification("Willkommen zurück!","success");
window.location="index.php";
}
else if(parseInt(msg.status)==0)
{
alert(msg.text);
}
else {
alert("Gibts nicht");
}
});
request.fail(function(jqXHR, textStatus) {
alert("Fehler");
});
}
</script>
BUT. Now when I navigate to 3 pages, and then submit the login Form, I will get 3 alerts (even when I navigate to just 1 site) of the request.fail function... after that the login goes correctly!
Ajax is still your problem. You have disabled ajax form submition but ajax is still used to load additional pages. This is just my assumption because you didn't mentioned that ajax is turned off all together.
If ajax is still used to load pages all your other pages are loaded into the DOM. Because of this you will have multiple forms with a same ID. When your first page is loaded there's only 1 form in a DOM and that form is used. But when another pages is loaded then additional form (with a same id) is added to the DOM. And whey you click a submit button jQuery will find first form with that ID from the DOM. And because there are 2 of them it will submit first for, same form loaded with an initial page.
That is why you NEVER use inline javascript with jQuery Mobile.
Instead of
onclick="..."
Your submit button should have an id and make it type="button".
<input type="button" data-icon="ok" data-iconpos="left" value="OK" id="submit-btn">
Put a click event on every button and use a $.mobile.activePage selector to find a form on an currently active page.
$(document).on('click','#submit-btn',function() {
$.mobile.activePage.find('#loginForm').submit();
});
Also everything should be wrapped inside a correct jQuery Mobile page event:
$(document).on('pageinit', '[data-role="page"]', function(){
$(document).on('click','#submit-btn',function() {
$.mobile.activePage.find('#loginForm').submit();
});
});

javascript to open certain web page and login

I am trying to create an html file that open a web page in default browser and login,
the page is in company intranet, and is .aspx strctured.
The page contain user, pwd field and a link to complete login procedure.
the related source row is
<a id="lnkAccedi" href="javascript:__doPostBack('lnkAccedi','')"
style="background-color:Transparent;font-family:Arial;">Accedi...</a>
and the simple code i've already tested is
<script language="JavaScript">
window.open("intranet_web_page","_self");
</script>
where intranet_web_page is the URL of my login page.
I tried to call the function defined in webpage source as "__doPostBack('lnkAccedi','');" in the script tag of my html file, but not work at all.
How can i do that?
Thanks in advance.
Actually I'm not an ASP user, but I believe that __doPostBack is a user defined function, you should defined it as a javascript function under the script tag.
And one point, I don't think that __doPostBack is need a parameter.
So if you want to create redirecting the user after authorized it without change the url, you can use jquery post method to post your data, then retrieve the server response under callback function to detect that user was authorized or not
I'll give you sample code, but actually I'm not tested it yet.
In HTML :
<form name="loginform" action="test.asp" method​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​="POST">
username : <input type="text" name="username" placeholder="please put your username here." /><br>
password : <input type="password" name="password" placeholder="your password here" /><br/>
<a id="lnkAccedi" href="javascript:__doPostBack" style="background-color:Transparent;font-family:Arial;">Accedi...</a>
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
On script:
function __doPostBack() {
var usernamestr = document.loginform.username.value;
var passwordstr = document.loginform.password.value;
$.post("authorize.asp", { username: usernamestr , password: passwordstr },
function(data) {
if(data = "success") {
window.open('newwindow.asp','_self');
} else {
alert("Username or password was wrong");
}
});
}​
Last, suggestion :
I think you don't have to control login process in the front end, because it's very dangerous, anyone can recreate your code and hack to your server, because it is client side. You should give the process control to the back end server.
Do NOT do any kind of authentication with JavaScript!!!
Do your login authentication on the ASP code-behind and then pass a success condition where you can use
response.write
to open a new window. I do a similar thing opening a messenger window. On login success I have the following code:
Response.Write("<script> var win =window.open('chat.aspx','mywindow','width=700,height=450,left=800,top=10,location=1'); win.close();</script>") //closes the window if it is already open
Response.Write("<script>window.open('chat.aspx','mywindow','width=700,height=450,left=800,top=10,location=1')</script>") //open the window
Again, that is how I call the script from the code-behind.
Hopefully that points you in the right direction!

Categories

Resources