why does this text input not cache? - php

I have two web pages which work basically the same, code-wise, but one of them does not seem to cache information. By 'cache', I mean on the client/browser side. The text field does not retain previously entered information. In the first example below, if you register and then log in, the next time you log in, your username will be cached in the the browser to be selected; while in the second example, it does not retain that info.
http://www.dixieandtheninjas.net/hunter/ has a login prompt. once you've logged in once from a browser, when you revisit the page it has cached your username.
http://www.dixieandtheninjas.net/dynasties/ also has a login prompt, but it does not cache! And I cannot figure out why.
Perhaps because the second one is not within FORM tags? Maybe there's some other tiny coding mistake I've made which causes this.
Here's the code from the first example:
<form method = "post"
action = "">
Username: <input type="text" name="login_name" value="" />
<br><br>
Password: <input type="password" name="password" value="" />
<br><br>
<input type="submit" value="Login" />
</form>
Here is code from the second example: Note that the clicks are handled by jquery in the second example, while the first just uses pure html and php
<p>
Email address: <input type="text" id="logininfo" value="" />
<br>
Password: <input type="password" id="password" value="" />
<br>
<input type="button" id="loginbutton" value="Login" />
</p>
Here is the jquery used in the second example:
<script type ="text/javascript">
$(function(){
$('#loginbutton').click(function(){
var loginvar = $('#logininfo').val();
var passvar = $('#password').val();
//alert(loginvar + ", " + passvar);
if (loginvar != '' && passvar != '') {
var subdata = {
logindata : loginvar,
passdata : passvar
};
$.ajax({
url: "index_backend.php",
type: 'POST',
data: subdata,
success: function(result) {
//alert(result);
if (result == '1') {
// success
window.location.replace("http://www.dixieandtheninjas.net/dynasties/playermenu.php")
} else if (result == '2') {
//$('#logininfo').empty();
$('#logininfo').attr('value', '')
$('#password').attr('value', '')
alert("Login failed. Please try again, or register if you have not already created an account.");
} else {
alert("Something has gone wrong!");
alert (result);
}
} // end success
}); // end ajax
} else {
alert ("Please enter a username and password.");
}
}); /// end click function for button
}); //// end
</script>

Since you aren't truly submitting the form in the jQuery one, the browser doesn't know that the user has attempted to use this as input vs just typed something in and then went to another page. Because of that, you won't be seeing it in the stored form data.

Related

AJAX not receiving POST variables

I've read at least 20 of these similar questions and can't figure out what's wrong with my code.
I've got a login form as shown below:
<div class="login-form">
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="submit" value="Log in"/>
</div>
</form>
</div>
My login.js script is as below:
$(document).ready(function(){
$("#login-button").click(function(e){
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php", //.js file is in a diff directory
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
This is supposed to get sent back to 'index.php', which has included a separate php file that handles the login information. The reason for this is so I can update the page with the user's successful login without refreshing.
My other php file is simply checking for the post data:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
var_dump($_POST);
if (isset($_POST['login']) && $_POST['login']) {
} else if (isset($_POST['reg']) && $_POST['reg']) { //this is for registration, which will be used once this login is working
} else {
echo 'Neither login/reg were set';
}
The var dump shows:
array(0) { }
So the data is not being received. However, it clearly reaches the php page. I don't know what's wrong, any suggestions?
Edit: I figured I would add, that adding an alert at the top of login.js with the username/password does print the entered values. So the login.js is being reached, and the data is accessible there. But it doesn't go beyond that.
Edit2: Here is my updated HTML and login.js code:
index.php:
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="button" value="Log in"/>
</div>
</form>
login.js
$(document).ready(function(){
alert(1);
$("#login-button").click(function(e){
alert(0);
//e.preventDefault();
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php",
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
The solution was to change my
$("#login-button").click(function(e){
to
$(document).on("submit",".login-form-container",function(e) {
which will handle the form submit, and this includes pressing the button as well as hitting enter (ideal situation).
Now the data is being sent successfully and I can handle the actual login/registration SQL, so thank you to #Ashokkumar M. Prajapati for helping to come to the conclusion that the .js script was not actually firing upon submit (not that the rest of you didn't help!)
please replace type: "POST" with method: "POST"
you mentioned it wrong in jquery ajax function.
Default is "GET" in case you don't specify it. So, if you had checked both $_POST & $_GET then you would have found your data in $_GET.
try var_dump($_REQUEST) if it don't show up anything then your client is not sending data to server.
also, check net panel of you browser developer console. so, you will know what data are passed to server.

AJAX code not working on button click

Hi I am using AJAX for the first time and I'm watching this tutorial so I can implement the feature on my website: https://www.youtube.com/watch?v=PLOMd5Ib69Y. What I'm trying to do is make a contact us form where the user can write a message and when he click a button the message is sent to my email. With AJAX I'm trying to change the button content without reloading.
I have this AJAX code:
<script src="/js/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
var ajax =
{
send: function()
{
var userName = $("input[name=un]").val();
var userEmail = $("input[name=email]").val();
var userMsg = $("input[name=msg]").val();
if(userName == "" || userEmail == "" || userMsg == "")
{
alert("All fields are required!");
}
else
{
ajax.SetText("Sending...");
$.post("sendMSG.php", {
name : userName, email : userEmail, message : userMsg
}, function(data){
ajax.SetText(data);
});
}
},
SetText: function(text)
{
$("input[type=button]").val(text);
}
}
</script>
And the html form:
Name: <br> <input type="text" size="40" name="un">
<br>
Email: <br> <input type="text" size="40" name="email">
<br>
Write us a Message!
<br>
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br/>
<input type="button" value="Send Message!" onClick="ajax.send()" />
For some reason when I click on the button nothings happens. As I said this is my first time using AJAX and I don't have idea how to use AJAX code. So please take it easy on me if the answer is simple :p
Thanks
You seem to be using a rather old version of jQuery. You should use the latest one which can be found on the jQuery Website.
Now for this example we'll use the submit event listener.
First you need to set up a form correctly:
<form id="myform" method="post">
Name: <br> <input type="text" size="40" name="un">
<br />
Email: <br> <input type="text" size="40" name="email">
<br />
Write us a Message!
<br />
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br />
<input type="submit" value="Send Message!"/>
</form>
Now for the jQuery (as stated above; we'll be using the submit event.) But first we have to ensure the DOM element is loaded before running our jQuery. That is done by using:
$(document).ready(function(){});
Setting up our jquery is as simple as writing what we want to do in our submit event listener:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault();
$.post('sendMSG.php',{name: userName, email: userEmail, message: userMsg}, function(data) {
console.log(data);
});
});
});
Obviously doing all the proccessing you require before running the $.post ajax request.
A Few Notes:
You could use e.preventDefault() or return false; within your event to stop the default actions taking place. (see below)
e.PreventDefault()
$('#myform').submit(function(e){
e.preventDefault();
// do ajax and processing stuff
});
return false;
$('#myform').submit(function(e){
// do ajax and processing stuff
return false;
});
You should look into using jQuery.ajax instead of the jQuery.post as it gives you more options.
I think you are using jquery,So you should put each code in
$(document).ready(function(){});

Clarifications on how to make interact jquery, ajax and php in order to realize a form submission and other controls

So, as the titles says, I need some clarifications on how to make interact jquery, ajax and php in order to realize a form submission and other controls.
This is my first web experience with jquery, ajax and php used all together, and, of course, I'm facing some problems.
I describe what I'm trying to do.
Basically, I've an index page with a registration form:
<form id="formRegistration" action="registration_success.php" method="post">
<p id="ptxtFullName">
<input id="txtFullName" name="txtFullName" class="textbox" placeholder="Insert you full name" type="text" />
</p>
<p id="pTxtEmail">
<input id="txtEmail" name="txtEmail" class="textbox" placeholder="Insert an email" type="text" />
</p>
<p id="pTxtPassword">
<input id="txtPassword" name="txtPassword" class="textbox" placeholder="Choose a password" type="password" />
</p>
<p id="pTxtPasswordConfirmation">
<input id="txtPasswordConfirmation" name="txtPasswordConfirmation" class="textbox" placeholder="Confirm your password" type="password" />
</p>
<p id="pBtnRegistration">
<input id="btnRegistration" type="submit" value="Register!" />
</p>
</form>
Then, I've a jquery file, which does all the input validation things (some effects if the inputs are correct or incorrect, and things like these), and, if the validation went good, makes an ajax call.
This is only an example, I don't post the entire file, because it's quite huge:
jQuery(document).ready(function($) {
$(function() {
var $fullName = $("input[name='txtFullName']");
var $email = $("input[name='txtEmail']");
var $password = $("input[name='txtPassword']");
var $passwordConfirmation = $("input[name='txtPasswordConfirmation']");
$("#btnRegistration").click(function() {
//Validation controls and effects.
});
return true;
});
$.ajax({
type : "POST",
url : "process_registration.php",
data : "fullName", "email", "password",
dataType : "HTML",
success : function() {
alert("Ok");
},
error : function() {
alert("Error");
}
});
});
NOTE that, the jquery file, when I add the ajax call, it stops to work, whilst if I don't add the ajax call, it works perfectly.
And then, here's my php file, named process_registration.php, wich is supposed to control if the email is already in use, and, after that, to insert the validated input datas into a MySQL database:
<?php
require 'db_connection.php';
$fullName = isset($_POST["fullName"]);
$email = isset($_POST["email"]);
$password = isset($_POST['password']);
$sql = mysql_query("SELECT * FROM utente WHERE mail = '$email'") or die("Email already in use");
$num_rows = mysql_num_rows($sql);
if ($num_rows == 0)
{
$password_md5 = md5($password);
mysql_query("INSERT INTO user (Full_Name , Email, Password) VALUES
('$fullName', '$email', '$password_md5')") OR DIE(mysql_error());
}
Thats all.
Obviously it isn't working.
Maybe I'm adopting a completely wrong approach in this thing?
Thanks in advance for your kindess and your answers.
Try using this:
jQuery(document).ready(function($) {
$('#formRegistration').submit(function() {
e.preventDefault();
// Perform form validation here and return from this function
// if you do not want to submit the form.
$.ajax({
type : "POST",
url : "process_registration.php",
data : $(this).serialize(),
dataType : 'html',
success : function() {
alert("Ok");
},
error : function() {
alert("Error");
}
});
});
});
This registers an event handler that gets called when the form is going to be submitted. The call to e.preventDefault() prevents the regular form submission. Then the handler posts the form via ajax.
You'll have to change the names of the input elements though because they need to match the names your PHP code is looking for (e.g., change "txtFullName" to "fullName").
The data attribute in the ajax call is supposed to be an object.
data : {
"fullName" : fullName,
"email" : email
}

work around for javascript php login system

Im building a login/register system using javascript to show particular divs for the system e.g
1st div = menu option to either login or register
2nd div = depending on what was clicked (login or register) shows login form or register form
3rd div = shows when user has successfully registered/logged in
the script looks like this:
html:
<article id="container">
<div id="load-new" class="game_menu">
<h1>LOAD/NEW</h1>
<button id="new_but" type="button">New Game</button>
<button id="load_but" type="button">Load Game</button>
</div>
<div id="reg" class="game_menu">
<h1>REGISTER</h1>
<form name="register" method="post" action="">
<label for="usernamesignup" class="uname">Your username</label>
<input id="usernamesignup" name="usernamesignup" required="required" type="text" placeholder="Username" />
<label for="emailsignup" class="youmail"> Your email</label>
<input id="emailsignup" name="emailsignup" required="required" type="email" placeholder="domain#mydomain.com"/>
<label for="passwordsignup" class="youpasswd">Your password </label>
<input id="passwordsignup" name="passwordsignup" required="required" type="password"/>
<label for="passwordsignup_confirm" class="youpasswd">Please confirm your password </label>
<input id="passwordsignup_confirm" name="passwordsignup_confirm" required="required" type="password"/>
<button id="reg_submit" type="button">Register</button>
</form>
</div>
<div id="login" class="game_menu">
<h1>LOGIN</h1>
<form name="login" method="post" action="">
<label for="username" id="username_label">Username:</label>
<input type="text" name="username" id="username" value=""/>
<label for="password" id="password_label">Password:</label>
<input type="password" name="password" id="password" value=""/>
<button id="login_submit" type="button">Login</button>
</form>
</div>
<div id="access" class="game_menu">
<h1>ACCESS</h1>
<button id="login_but" type="button">Login</button>
<button id="reg_but" type="button">Register</button>
</div>
<canvas id="TBG" width="640" height="416">
Please use a more up to date browser
</canvas>
the javascript looks like this
main.js:
//----------Login/Register Gui --------------
$('#load-new').hide();
$('#reg').hide();
$('#login').hide();
//create new instance of gui class
var ui = new Gui();
//if login_but is clicked do ui.login function
$('#login_but').click(ui.login);
//if reg_but is clicked do ui.register function
$('#reg_but').click(ui.register);
//if login_sumbit button is clicked do ui.login_ajax function
$("#login_submit").click(ui.login_ajax);
$("#reg_submit").click(ui.register_ajax);
gui.js:
function Gui (){
var valid = 'true';
var invalid = 'false';
//hide access div, show login div
this.login = function()
{
$('#access').hide();
$('#login').show();
};
//hide access div, show register div
this.register = function()
{
$('#access').hide();
$('#reg').show();
};
//function to send login data to php script login.php
this.login_ajax = function()
{
//username user inputted
var username = $("#username").val();
//password user inputted
var password = $("#password").val();
//inputted data made into JSON string
var dataString = {"reg":invalid, "login":valid, "username":username ,
"password":password};
//AJAX Request to login.php
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data: dataString,
dataType: 'JSON',
success: function(success) {
alert("Your are logged in");
if(success == 'true'){
$('#login').hide();
$('#load-new').show();
}
},
error: function(){
alert("ERROR in AJAX");
}
});
};
this.register_ajax = function()
{
var username_signup = $("#usernamesignup").val();
var email_signup = $("#emailsignup").val();
var password_signup = $("#passwordsignup").val();
var password_signup_confirm = $('#passwordsignup_confirm').val();
var dataString = {"reg":valid, "login":invalid, "username_signup":username_signup,
"email_signup":email_signup,
"password_signup":password_signup, "password_signup_confirm":password_signup_confirm};
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data: dataString,
dataType: 'JSON',
success: function(success) {
alert("You are registered");
if(success == 'true'){
$('#reg').hide();
$()
$('#load-new').show();
}
},
error: function(){
alert("ERROR in AJAX");
}
});
}
}
i use ajax to send requests to php scripts to process login or register.
the script that the ajax requests is simple a go between so i can select specific functions in either the login php or register php.
i would like to have an are in my html to show if a user is logged in or not a bit like the are in the top right on the runescape website : here.
now i tried this php in my header.php file:
if(isset($_POST['username'])){
$is_logged_in = '<div id = "user_box">Welcome '.$_POST['username'].'</div>';
}
else
{
$is_logged_in = '<div id = "welcome_box">Welcome friend!</div>';
}
but obviously this wouldnt work because the page doesnt refresh where im using javascript to show different parts of the menu.
MY QUESTION:
What would be the most pratical way to achieving this effect with the javascript/php system i have in place?
Would i use javascript to hide/show divs like i have with the menu divs? or is there a function i can use to refresh the page without it sending me back to the first menu div?
Thanks for your time
Tom
Right now you are only sending back one value from the php scripts that you are calling using ajax, you are only using true for a successful login or registration.
What you could do, is modify these scripts to return multiple values. So apart from the true value for a successful login, you also send the username and then in your javascript you use that username to build a html block to show in the top area where you want to show the username.
You are already using json, so you only have to generate an array with return values in your php script and use echo json_encode($your_return_values); to send it to your javascript success variable.
By the way, you can use jquery / javascript to replace and build whole sections of your html, you don't need to put everything in at the start just to hide it.
If I'm understanding your question correctly your wanting to indicate to the user that they are logged in without reloading the page and by displaying a div in the top right corner.
That being the case you could create a hidden div with an absolute top right position which would be something like:
<div id="welcome" style="display:none; postion:absolute; top:0; float:right;">...</div>
In the 'success:' portion of the ajax request above, add a call to a new js function that makes a separate ajax request to retrieve a json object containing the logged in users display name and any other information that you want to show. Using that json data you could then populate 'welcome' div accordingly and change it's display to block.

Check User Validation in MySql with javascript

i want check in my mysql database if the user enter the username and password correctly and then go in the home.html, i have some javascript code that detect when the user click the login button, but i can't understand how check in the database with javascript, i know how do that in php, but i can't understand how call the php from the javascript or do it directly in the js code, this is some code:
the form in the html:
<div id="password">
<div class="input username"><input type="text" placeholder="User name" /></div>
<div class="input password"><input type="password" placeholder="Password" /></div>
<button>Log in</button>
Back
</div>
</div>
then in my Login.js file i have this:
function forgot() {
//Se ho scritto la password allora fai l'animazione wobble, altrimenti vai in home.html
if($("#password .input.password input").attr("value")!='') {
$.notification(
{
title: "Wrong password",
content: "Just leave the password field empty to log in.",
icon: "!"
}
);
$("#password").removeClass().addClass("animated wobble").delay(1000).queue(function(){
$(this).removeClass();
$(this).clearQueue();
});
$("#password .input.password input").attr("value", "").focus();
} else {
document.location.href = "home.html";
}
}
now for the login i detect only if the field are empty, but i want detect mysql database how i can check it? because i want if the user enter wrong username and password span a $notification alert, anyone can help me?
Please suppose your html form is like below:
<input id="uname" name="uname" type="text" placeholder="User name" />
<input id="pass" name="pass" type="password" placeholder="Password" />
<button id="btn_login">Log in</button>
And suppose php script named checkPassword.php is like below:
<?php
/*
1.Retrieve post data : "uname" and "pass".
2.Cehck if user name and password is valid.
*/
if( /* valid user name and password */ ){
echo "OK";
}else{
echo "NG";
}
?>
The Javascript code could goes like below:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
$(function() {
// set a event handler to the button
$("#btn_login").click(function() {
// retrieve form data
var uname = $("#uname").val();
var pass = $("#pass").val();
// send form data to the server side php script.
$.ajax({
type: "POST",
url: "checkPassword.php",
data: { uname:uname, pass:pass }
}).done(function( data ) {
// Now the output from PHP is set to 'data'.
// Check if the 'data' contains 'OK' or 'NG'
if (data.indexOf("OK") >= 0){
// you can do something here
alert("Login Successed.");
location.href = "ok.html";
}else if(data.indexOf("NG") >= 0){
// you can do something here
alert("Login Faild.");
location.href = "ng.html";
}
});
});
});
</script>
You can't communicate directly from client side JS to a server side database.
To make an HTTP request (to a server side program), use the XMLHttpRequest object.
if(document.pressed=='SUBMIT')
{
var uname = document.getElementById('uname').value;
if(uname.trim()=='' || uname.trim()==null)
{
alert("<?php echo 'uname_null'?>");
return false;
}
}
you can do the validation part on the sql server side if you use stored procedures

Categories