I am attempting to create a user area for a website that is accessed by using a username and password. I am using HTML for the front end, JavaScript for the back end and PHP for the server side. I am using Xampp to run a local server and PHPMyAdmin to host the database.
The HTML Code:
<!-- the Login Section -->
<input type="text" name="userName" placeholder="username" id="usernameBar">
<input type="password" name="passWord" placeholder="password" id="passwordBar">
<button id="loginButton" onclick="Login();">Login</button>
<p id="IncorrectP" title="Incorrect Username or Password" style="display: none">Invalid</p>
JavaScript:
function Login(){
//Connect to the PHP:
var urlConnect = "checkLogin1.php";
//Get the username and password:
var usrUsername = document.getElementById("usernameBar").value;
var usrPassword = document.getElementById("passwordBar").value;
//Define the parameters to send to php
var strParameters = "usrUsername="+usrUsername + "usrPassword="+usrPassword + "&sid=" + Math.random();
//Define the options for the AJAX request
var objOptions = {
method: "post",
parameters: strParameters,
onSuccess: function(objXHR) {
//If objXHR. responseText = Tenant:
if(objXHR.responseText=='Tenant'){
//Go to tenant space:
alert("Success! (Tenant)");
OpenTenantPage();
}
//Else if objXHR.responseText = Staff:
else if(objXHR.responseText=='Staff'){
//Go to staff space:
alert("Success! (Staff)");
OpenStaffPage();
}
//Else if objXHR.responseText = Admin:
else if(objXHR.responseText=='Admin'){
//Go to admin space:
alert("Success! (Admin)");
OpenAdminPage();
}
else{
//Run IncorrectLogin:
alert("Error! No User Account Found!");
IncorrectLogin();
}
}
}
// define the AJAX request object
var objRequest = new Ajax.Request(urlConnect,objOptions);
}
PHP:
<?php
//Link the username and password:
$connect = mysqli_connect("localhost", "admin", "12345", "realestate") or die ('Connection to database failed: ' . mysql_error());
//Extract variables for request parameters:
extract($_REQUEST);
//Try to log in as a tentant:
$resTenantUser = mysqli_query($connect, "SELECT * FROM tenants WHERE Username='$usrUsername' AND Password='$usrPassword'") or die(mysql_error());
//$resTenantUser = mysqli_query($connect, "SELECT * FROM tenants WHERE Username='Charb1' AND Password='123456' ") or die(mysql_error());
//Set intCount to number of rows in result:
$intCount = mysqli_num_rows($resTenantUser);
if($intCount == 0){
echo "Error!";
}
else{
echo "Tenant";
}
?>
I think that the error my be that the JS is not sending the parameters to the PHP or it is sending empty parameters. I cannot seam to find my mistake though.
parameters must be in JSON format not in query string format.something like this:
parameters:{usrUsername: usrUsername , usrPassword:usrPassword , sid : Math.random()}
Problem is in the query params. You missed &. Try this way.
var strParameters = "usrUsername="+usrUsername + "&usrPassword="+usrPassword + "&sid=" + Math.random();
Or
var strParameters = {"usrUsername" : usrUsername, "usrPassword" : usrPassword, "sid" : Math.random()}
Related
I have created a chat website. I send the message with AJAX to PHP and the MySql Database. The messages are fetched using AJAX which runs per second. But this lead to fetch of all the messages (from starting to end). I came with an solution that I will pass the last message ID to the AJAX/JAVA SCRIPT and then fetch only the messages which are more than that.
Here is the Java Script / AJAX
function fetchdata(){
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
data : {cuser:cuser, ouser:ouser},
success: function(read){
$("#readarea").html(read);
}
});
}
Here is the PHP code to get messages:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
$result = mysqli_query($conn, $sql) or ("Query Failed");
while($row=mysqli_fetch_assoc($result)){
if($row["fromid"]==$_POST['cuser']){
echo "<div class='cuser'>".$row["message"]."</div>";
}else{
echo "<div class='ouser'>".$row["message"]."</div>";
}
}
Here I want to get the ID (message) in the Java Script function back from the PHP and use it as a variable for fetching the messages which will be more than it.
You should return JSON from the PHP, instead of HTML. That way you can return an object with properties such as ID, message, etc. Then you can use Javascript to store the latest ID, and also to put the message into your page with the relevant HTML.
Something like this:
PHP:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
if (!empty($_POST["lastid"]) $sql .= " AND id > {$_POST['lastid']}";
$result = mysqli_query($conn, $sql) or ("Query Failed");
$messages = array();
while($row=mysqli_fetch_assoc($result)){
$messages[] = $row;
}
echo json_encode($messages);
JS:
//make this global so it persists beyond each call to fetchdata
var lastMessageID = null;
function fetchdata()
{
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
dataType: "json",
data : { cuser: cuser, ouser: ouser, lastid: lastMessageID },
success: function(read) {
for (var i = 0; i < read.length; i++)
{
var className = "ouser";
if (read[i].fromid == cuser) classname = "cuser";
$("#readarea").append("<div class='" + className + "'>" + read[i].message + "</div>");
lastMessageID = read[i].id;
}
}
});
}
P.S. Please also take note of the comment about about SQL injection and fix your query code, urgently. I haven't done it here for the sake of brevity, but it must not be ignored.
Brief
I am now stuck at a part of AJAX, as I do now know how to extract the data out from the AJAX part and put into the PHP variables, so that I could access it and use it later. It also does not redirect me to another page ("Map.php").
I tried looking online for the answers, but to no avail. Can anyone with experience please help. Also, I am not sure if my method of doing is correct, please let me know where I have done wrong.
In details
I want to do a "Login.php", which will use a form to take the email and password from the user. There will be a "Login" button on the form which will trigger a javascript for the purpose of validation.
Upon validation, I will use AJAX to call another php file called "Auth.php", which will have make a connection with a MySQL database, to search for that particular user verify the user.
The "Auth.php" will then return a json data of the user's particulars, which I intend to use in "Login.php" page, and to start a session with the $_SESSION[] variable of php. I also want the page to redirect the user to another page ("Map.php") upon successful login.
Below are parts of my codes in the "Login.php" and "Auth.php".
Login.php
<form name="myForm" action="Map.php" method="post" onsubmit="return validateForm()">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email" type="email" autofocus value="<?php echo isset($_POST["email"])? $_POST["email"]: ""; ?>">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="<?php echo isset($_POST["password"])? $_POST["password"]: ""; ?>">
</div>
<input type="submit" value="Login" class="btn btn-lg btn-success btn-block"/>
</fieldset>
</form>
<script>
function validateForm() {
//event.preventDefault();
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email == null || email == "") {
alert("Email must be filled.");
return false;
}
if (password == null || password == "") {
alert("Password must be filled.");
return false;
}
if(re.test(email)) {
var data = {
"email": email,
"password": password
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "GET",
dataType: "json",
url: "auth.php",
data: data,
success: function(data) {
alert("You have successfully logged in!");
// TODO store user details in session
return true; // return true to form, so will proceed to "Map.php"
}
});
return false;
}
else {
alert("You have entered an invalid email address!");
return false;
}
return false;
}
</script>
Auth.php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid=true;
if (isset($_GET['email']) && isset($_GET['password'])) {
$email = addslashes($_GET['email']);
$password = addslashes($_GET['password']);
} else {
$valid = false;
$arr=array('success'=>0,'message'=>"No username or password!");
echo json_encode($arr);
}
if($valid == true){
$query = "SELECT * FROM user WHERE email='$email' and password='$password'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Login failed");
echo json_encode($arr);
}
}
// close the connection that was established with MySQL for the SQL Query
mysqli_close($connection);
Your ajax call should be like this:
data = $(this).serialize() + "&" + $.param(data)
$.post('auth.php', data, function(response){
console.log(response);
});
you must use post method because you are getting password and email so its not a good practice. And for validation there is many jQuery plugins.
Good day, I'm trying to use Ajax in my web application. But I have a little problem with it. I try to control a form if some username has already been registered or not. But my JavaScript seem does not send $_POST value to PHP. And responses that user in not defined on the line where I have $_POST['user'].
Here what I have.
PHP:
<?php
$opt = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$dsn ='mysql:dbname=someone;host=127.0.0.1;charset=utf8';
$user='someone';
$pswd='aaa';
$dbh = new PDO($dsn, $user, $pswd, $opt);
$query="SELECT 1 FROM users WHERE username = :username";
$query_p=array(':username' => $_POST['user']);
try
{
$statment = $dbh->prepare($query);
$result = $statment->execute($query_p);
}catch(PDOException $e)
{
echo "Can't run query: " . $e->getMessage();
}
$row = $statment->fetch();
if($row){
return 0;
}else {
return 1;
}
?>
So it opens a connection to database and runs a query
JavaScript:
function checkUser(e){
var state1 = document.getElementById("alert_text");
var u = document.getElementById("user").value;
if(u != ""){
state1.innerHTML = 'processing...';
var request = new XMLHttpRequest();
request.open("POST", "validation.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var result=request.responseText;
alert(result);
if(result==1){
state1.innerHTML="OK";
}else{
state1.innerHTML="Alredy exists!";
}
}
};
request.send(u);
var slova = request.responseText;
}
}
document.getElementById("user").addEventListener("blur",checkUser,false );
So technically it is ajax.
HTML:
<form id="check" name="signUp" method="post">
<p class="alert_text"></p>
<label for="user">Username:</label><br />
<input id="user" name="user" type="text" ><br />
</form>
I don't really see what's the problem...
You're not passing the username into the PHP script. Your PHP is looking for a POST variable, $_POST['user'] – in your JavaScript you make a GET request, so the PHP script has nothing to look up.
Based on the edited question: You are not sending any key-value pairs to the server, just a single value.
You need to change:
var u = document.getElementById("user").value;
to:
var u = 'user=' + encodeURIComponent(document.getElementById("user").value);
And then later on the pair will be sent correctly:
request.send(u); // sends a single key-value pair
Note that I have just added the encodeURIComponent function to make sure the value gets encoded correctly.
<form id="foo">
<input type="text" name="voucher" placeholder="voucher ID" class="bill_fillter"/>
<input type="text" name="voucher" placeholder="voucher ID" class="bill_fillter"/>
<input type="text" name="voucher" placeholder="voucher ID" class="bill_fillter"/>
</form>
This is my Jquery Code
<script>
$("#foo").submit(function(event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "ajax_receipt_sms.php",
type: "post",
data: values,
success: function(){
alert("success");
$("#result").html('Submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('There is error while submit');
}
});
});
</script>
ajax_receipt_sms.php
<?php
$viuchid = $_POST['voucher'];
$sql1="SELECT * from usertable;
$result1 = mysql_query ($sql1);
$row1 = mysql_fetch_array($result1)
$CHEQUE_NO = $row1['CHEQUE_NO'];
$cheqdate = $row1['CHEQUE_DATE'];
$mobile = $row1['mobile'];
$bank_name = $row1['name'];
$amt = $row1['Amount'];
// split "dd-mm-yyyy" into an array of three elements
$ddate = explode("-", $cheqdate);
// retrieve the values
$month = $ddate[1]; // mm
$day = $ddate[2]; // dd
$year = $ddate[0]; // yyyy
?>
<?php
$notify="Your message is successfully sent to:"."91".$mobile;
$message = "Dear Member, received with thanks Rs.".$amt. " by chq/cash dated " .$day.'-'.$month.'-'.$year. " drawn on " .$bank_name. "bank, from ".$_SESSION['socityname'].".";
$username = "xxx";
$password = "xxxxxx";
$sendername = "shoaib";
$url = "http://bulksms.mysmsmantra.com/WebSMS/SMSAPI.jsp?username=".$username."&password=".$password."&sendername=".$sendername."&mobileno=91".$mobile."&message=".urlencode($message);
// for sms send request
$ch=curl_init();
if($url)
curl_setopt($ch,CURLOPT_URL,$url);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
?>
how to send multiple checkbox data to PHP via jQuery and send sms to multiple user, when i add multiple number to input box , it should send Sms to all data to the number.
I also think need to use array like voucher[] in input element of type check box.
I have two database tables, guestlist and attendance
On one HTML page, I have a window.onload script that I want to check the guestlist via AJAX. If the firstname AND lastname in the url query appear in the guestlist table, then load the page. If not, load an error message.
When the page is properly loaded, the firstname and lastname are pre-populated in two input fields. The user completes the rest of the form and clicks submit, inserting their firstname and lastname into the attendance table.
If the firstname and lastname already appear in the attendance table, load an error message. If the firstname AND lastname to not appear in the attendance table, submit the form information to the attendance table.
When it comes to Ajax, I am not the bright bulb in the pack. This is the code I currently have:
HTML
<body>
<div id="formDiv">
<form id="partyForm" name="party" action="party_insert" method="post">
<h1>Welcome to The Party</h1>
<input name="first_name" id="firstname" class="input" type="text" maxlength="99" placeholder="First Name"><br/>
<input name="last_name" id="lastname" class="input" type="text" maxlength="99" placeholder="Last Name"><br/>
<input name="costume" id="costume" class="input" type="text" maxlength="999" placeholder="What are you supposed to be?"><br/>
<div id="buttonDiv">
<a class="button" id="submit" style="cursor:pointer;">SUBMIT</a>
</div>
</form>
</div>
<script>
window.onload = function () {
var fname_init = decodeURIComponent(getUrlVars()["fname"]);
var lname_init = decodeURIComponent(getUrlVars()["lname"]);
if(fname_init !== "undefined" && lname_init !== "undefined"){
var newString = 'fname='+encodeURIComponent(fname_init)+'&lname='+encodeURIComponent(lname_init);
$.ajax({
type: "GET",
url: "guestList.php",
data: newString,
success: function(){
alert("ON THE LIST");
$('#firstname').val(fname_init);
$('#lastname').val(lname_init);
},
error: function(){
alert("NOT ON THE LIST");
window.location = 'error1.html?fname='+encodeURIComponent(fname_init)+'lname='+encodeURIComponent(lname_init);
}
})
}
}
$("#submit").click(function() {
validate();
});
function submit(){
var fname = $("#firstname").val();
var lname = $("#lastname").val();
var cost = $("#costume").val();
var dataString = 'fname='+encodeURIComponent(fname)+'&lname='+encodeURIComponent(lname)+'&cost='+encodeURIComponent(cost);
$.ajax({
type: "POST",
url: "partyEntry.php",
data: dataString,
success: function() {
alert("ENJOY THE PARTY");
clearForms();
}
});
}
function validate(){
if ($("#firstname").val() == ""){
alert("Please Enter your First Name");
} else {
if ($("#lastname").val() == ""){
alert("Please Enter your Last Name");
}else{
if ($("#costume").val() == ""){
alert("You have to have a costume to be eligible for this raffle");
}else{
submit();
}
}
}
}
function clearForms() {
$('#partyForm')[0].reset();
}
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
</body>
guestList.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "party";
$link = mysql_connect($host, $user, $password);
mysql_select_db($database);
//SURVEY INFORMATION
$fname = mysql_real_escape_string($_REQUEST['fname']);
$lname = mysql_real_escape_string($_REQUEST['lname']);
$checkClient = "SELECT * FROM guestlist WHERE first_name = ".$fname." AND last_name = ".$lname;
mysql_query($checkClient) or die(mysql_error());
mysql_close($link);
?>
partyEntry.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "party";
$link = mysql_connect($host, $user, $password);
mysql_select_db($database);
//SURVEY INFORMATION
$fname = mysql_real_escape_string($_REQUEST['fname']);
$lname = mysql_real_escape_string($_REQUEST['lname']);
$cost = mysql_real_escape_string($_REQUEST['cost']);
$addClient = "INSERT INTO attendance (first_name, last_name, costume) VALUES ('$fname','$lname', '$cost')";
mysql_query($addClient) or die(mysql_error());
mysql_close($link);
?>
The error I am getting is that even though a name is not on the guestlist, it will still show that they are ON THE LIST. So I must be doing something wrong in the Ajax call to guestlist.php, but I have no idea what. I also am having problems scripting out an ajax call to check if the guest has already been put into the attendance table.
Like I said in my comment you will have to return a value from the guestList.php, something like this should work:
$checkClient = "SELECT * FROM guestlist
WHERE first_name = ".$fname." AND
last_name = ".$lname;
$result = mysql_query($checkClient);
$count = mysql_num_rows($result);
mysql_close($link);
// output 1 or 0 stating if the user is on the list or not
echo ($count ? 1 : 0);
exit();
Then in your ajax callback you would do a check like:
success:function(e) {
alert((e == 1 ? "User is on list" : "User isn't on list"));
According to the REST principle, responding to a POST request with HTTP 200 means that the resource is successfully created. You can respond with a HTTP 400 and also provide detailed information about the error in text/html/json/xml format.
Try doing this,
Add the folowing code,
$query = mysql_query($addClient) or die(mysql_error());
if(mysql_num_rows($query) > 0)
{
header('HTTP/1.1 500 Internal Server Error');
echo 'this is an error message';
}
The php script will never throw an error at least you try to execute an invalid query. The query is executed without any error because it is well formatted so and error won't be throw because you are not getting rows from the database.