For the life of me I can't figure out why the following code is not working. I'm quite inexperienced so any assistance appreciated.
I want to get a simple connection working where an ajax call will return a username from a mySQL DB (this is a precursor to a much larger project). My HTML file is the following:
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="jquery/test-theme.min.css"/>
<link href="jquery/jquery.mobile.icons.min.css" rel="stylesheet" />
<link href="jquery/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet" />
<link href="jquery/app.css" rel="stylesheet" />
<script src="jquery/jquery-2.1.4.min.js"></script>
<script src="jquery/jquery.mobile-1.4.5.min.js"></script>
<script> function login(){
$(document).ready(function(){
var user = $("#username")[0].value;
var email = $("#email")[0].value;
$.ajax({
type: "GET",
url: "http://localhost:8888/test/connection.php",
data: "username="+user+"&email="+email,
success: function(result){
if(result){
$("#message")[0].value = "Success" +result;
}
else{
$("#message")[0].value = "Fail :(";
}
},
error: function(result){
$("#message")[0].value = "Ajax error!"+result;
}
});
});
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header" data-theme="c">
<h1>Sign Up!</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h3>Sign Up</h3>
<label for="txt-first-name">Username</label>
<input type="text" name="txt-first-name" id="username" value="" onkeyup="login()">
<label for="txt-email">Email Address</label>
<input type="text" name="txt-email" id="email" value="" onkeyup="login()">
<input type="text" id="message"></input>
<button id="submit" onclick="login()"> Submit</button>
<div data-role="popup" id="dlg-sign-up-sent" data-dismissible="false" style="max-width:400px;">
</div>
</div><!-- /content -->
</div>
</body>
</html>
And my PHP:
<?php
$user = $_REQUEST['username'];
$email = $_REQUEST['email'];
mysql_connect("localhost:8889","root","root") or die(mysql_error());
mysql_select_db("TEST") or die(mysql_error());
$result = mysql_query("SELECT username, email FROM login WHERE username ='$user'");
while($row = mysql_fetch_array($result)){
if($user = $row["username"]){
echo $row["id"];
}
else{
echo "failed getting user"
}
}
?>
I have a DB called TEST running via MAMP with some entries in the login table for username and email. I just want to get the connection running properly but I'm stumped.
Related
Just started working with php and little bit struggling with jQuery. Went through documentation and in my opinion everything should be working fine, however no. The hidden value does not appear visible after entering the wrong data into form. In css I assigned to #warning display:none
index.php
<?php require "../src/models/Database.php"; ?>
<?php include_once "../src/controllers/DatabaseController.php"; ?>
<?php session_start(); ?>
<?php include "../src/includes/header.php"; ?>
<?php
if (isset($_POST["submit"])) {
$username = $_POST["username"];
$password = $_POST["password"];
$dbController = new DatabaseController();
$dbController->loginUser($username, $password);
}
?>
<div class="container main">
<h1 class="text-center">Web</h1>
<p class="text-center" id="warning">Incorrect username or password</p>
<div class="row login-page">
<form class="form" method="POST">
<input class="form-control" type="text" name="username" placeholder="Username" required>
<input class="form-control" type="password" name="password" placeholder="Password" required>
<input class="btn btn-success" type="submit" name="submit" value="Login">
</form>
</div>
</div>
<?php include "../src/includes/footer.php"; ?>
header.php
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Bootstrap starts -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- Bootstrap ends -->
<!-- Css starts -->
<link rel="stylesheet" href="../src/styles/css/main.css">
<!-- Css ends -->
<!-- Jquery starts -->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<!-- Jquery ends -->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title id="title"></title>
</head>
<body>
databasecontroller.php
<?php
class DatabaseController extends Database
{
public function loginUser($username, $password)
{
$connection = $this->connection;
$escapedUsername = mysqli_real_escape_string($connection, $username);
$escapedPassword = mysqli_real_escape_string($connection, $password);
$query = "SELECT * FROM users WHERE username = '$escapedUsername'";
$result = $this->findUser($query, $escapedPassword);
if ($result) {
// $_SESSION["authenticated"] = true;
echo "Logged in";
} else { ?>
<script>
$("#warning").show();
</script>
<?php
}
}
}
composer.json
{
"require": {
"components/jquery": "^3.5"
}
}
You are including the jQuery script before the html is finished.
Therefore, there is no #warning on the page, yet. Nothing is shown.
You should either include your script after the <p class="text-center" id="warning"> or you can tell jQuery to wait until the document is ready before applying the show():
$( document ).ready(function() {
$("#warning").show();
});
I've put together a codebase that successfully calls Ajax to a PHP server which issues requests to a database. I'm very new to this, but I've been able to successfully update rows in the SQL.
The good news is it doesn't update that row if there are already values in email, name, and redeem time columns. How do I cause the program to make errors if the coupon code has already been redeemed, though?
Is using a test query a possible approach? Or should I try to set up a separate Ajax request..possibly a Get to do a comparative evaluation on submission with the values in the form? But even if that is the case I have no idea how to actually implement that sort of conditional in PHP. Thanks if you have any advice.
//user_process.php
<?php
$con = mysqli_connect(); //<--redacted ;D
//first, test with what should be in the db
//with defaults.
$testcode=$_GET["code"];
$testname="Unredeemed";
$testemail="N/a";
$testredeemed="0000/00/00 00:00:00";
$testquery=mysqli_query($con,"SELECT code,name,email,redeemed FROM codestore WHERE code='$testcode', name='$testname', email='$email', redeemed='$testredeemed'");
if($testcode){
if(!$testquery){
die("Er");
}
}
$code=$_POST["code"];
$name=$_POST["name"];
$email=$_POST["email"];
$redeemed=$_POST["redeemed"];
$query=mysqli_query($con,"UPDATE codestore SET name='$name', email='$email', redeemed='$redeemed' WHERE code='$code',name='Unredeemed',email='N/a',redeemed='0000/00/00 00:00:00'");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>
//user_index.js
function formatDate(date) {
//deleted for readability
}
$("#submit").click(function (event) {
$(".main-content").append("<?php require 'user_process.php';?> ");
// if() each has a value else alert error
var currentDateTime = new Date();
var redeemedOn = formatDate(currentDateTime);
var code = $("#code").val();
var name = $("#name").val();
var email = $("#email").val();
$.ajax({
type: "post"
, url: "user_process.php"
, data: "code=" + code + "&name="+name+"&email="+email+"&redeemed="+redeemedOn
, success: function (data) {
$("#info").html(data);
}
, error: function(){
alert("That code is invalid or has already been redeemed!")
}
});
});
//index.php
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="/demo_mini.css">
<title>Search Contacts</title>
</head>
<body>
<div class="main-content">
<form class="form-basic">
<div class="form-row"> <span>Enter your code </span>
<input type="text" name="code" id="code"> </div>
<div class="form-row"> <span>Full Name </span>
<input type="text" name="name" id="name"> </div>
<div class="form-row"> <span>Email</span>
<input type="text" name="email" id="email"> </div>
<div class="form-row">
<button id="submit">Redeem!</button>
</div>
<div id="info" /> </form>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="/user_index.js"></script>
</body>
</html>
I'm trying to send some Data to a MySQL Database that I have stored on a server. When I press the submit button, my PHP scripts let me know that the connection to the DB has been successful, but the insertion of data has not. I can't find any issue in the Error logs, or an obvious problem when I examine the code via Google Chrome's developer tools.
Below is the HTML File;
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="http://example.com/JS/functions.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
//CSS
<style>
.ui-page {
background: #4990E2;
}
p {
color: #ffffff;
}
</style>
</head>
div data-role="page" id="page1">
<div data-role="header" data-theme="a">
<h1>Welcome</h1>
</div>
<!-- Main page content goes under this line -->
<div data-role="main" class="ui-content">
<br>
<br>
<br>
<form id="myForm" method="post" action="include.php">
<label for="rating">How are you feeling?</label>
<input type="range" name="rating" id="rating" value="50" min="0" max="100" data-popup-enabled="true">
<input id="submit" type="submit" data-inline="true" value="Submit">
</form>
<br>
<br>
<span id="result"></span>
<br>
<p>Some text</p>
</div>
<div data-role="footer" data-position="fixed" data-theme="b">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>Example</li>
<li>Example</li>
<li>Example</li>
</ul>
</div>
</div>
</div>
<!-- Page ends here -->
<!-- -->
Below is the PHP file (db.php);
<?php
//put your connection code here
$servername = 'localhost';
$username = 'user_admin';
$password = '12345-678';
$dbname = 'my_DB';
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully, <br>";
?>
Below is the PHP file(include.php);
<?php
include 'db.php';
$rating = $_POST['rating'];
$sql="INSERT INTO user Values('$rating')";
if(mysqli_query($conn,$sql)){
echo "Successfully Inserted";
} else {
echo "Did NOT insert";
}
?>
Below is the Javascript file (functions.js);
// AJAX-ify the slider
$(document).on("pagecreate","#page1",function()
{
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){ $("#result").html(info);
});
});
$("#myForm").submit( function() {
return false;
});
});
The MySQL table is called 'user' and the column is called 'rating'. The column is set as int(3) [this should match with the slider max value of 100?].
Can anyone pinpoint why the Data isn't being inserted into the DB?
change this
$sql="INSERT INTO user Values('$rating')";
to this
$sql="INSERT INTO user (`rating`) VALUES ('$rating')";
rating would be the column name for that field in the db, if the table has more than one column then the statement need to say in which column it need to be placed.
also to show errors of the statement use this
if(mysqli_query($conn,$sql) or die(msqli_error($conn))){
... your code here > it worked
}else{
... your code here > it failed
}
Hello I'm trying to do simple authentification application on android, I use dreamweaver as editor. Well here is the code, please can you tell why I'm not redirected to login.php after a success authentification.
index.html
<html><head>
<meta charset="utf-8">
<title>Guide touristique</title>
<link href="jquery.mobile.theme-1.0.min.css" rel="stylesheet" type="text/css"/>
<link href="jquery.mobile.structure-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery.mobile-1.0.min.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
$("#loginform").submit(function() {
$.post('auth.php', $(this).serialize(), function(data) {
$("#errorm").html(data); // semicolon missing in your code
}); // round bracket and semicolon missing in your code
}); // round bracket missing in your code
return false;
});
</script>
</head>
<body>
<div data-role="page" id="page2">
<div data-theme="a" data-role="header">
</div>
<div data-role="content" style="padding: 15px">
<div style="text-align:center">
</div>
<form id="loginform" method='post'>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="textinput2" style="text-align:right">
Email:
</label>
<input id="textinput2" name="login" value="" type="text"/>
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="textinput3" style="text-align:right">
Password: </label>
<input id="textinput3" name="password" value="" type="password"/>
</fieldset>
</div>
<h3 id="errorm"> <?php if (isset($_GET['msg'])){
echo "Invalid username or password";
}
?></h3>
<input type="submit" name="submit" id="submit" data-inline="true" data- icon="arrow-l" data-iconpos="left" value="login"/>
</form>
</body>
</html>
auth.php
<?php
//Sanitize the POST values
$login = $_POST['login'];
$password = $_POST['password'];
$aqry="SELECT * FROM user WHERE utilisateur='".$login."' AND pswd='".$_POST['password']."'";
$conn=mysql_query($eqry);
if( $conn ){
//Check whether the query was successful or not
if(mysql_num_rows($conn) == 1) {
//Login Successful
/* $member = mysql_fetch_assoc($conn);
$_SESSION['MEMBER_ID'] = $member['id'];
$_SESSION['NAME'] = $member['utilisateur'];
*/
header("location: login.php");
exit();
}
else {
//Login failed
header("Location: mobile/mlogin.php?msg=invalid%20name%20or%20password");
exit();
}
?>
login.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>login</title>
</head>
<body>
You're logging on
</body>
</html>
You are doing the login via an ajax request with $.post(), which means that the redirect you are sending is being captured by the ajax request. If you look in FireBug or something similar, you should see that the result of the ajax call is actually login.php.
I'd recommend having auth.php always return a json response (see http://php.net/manual/en/function.json-encode.php) something like {"result":"success", "redirect":"login.php"} or {"result":"error", "message":"abcd"}
In your ajax response handler:
if (data.result == "success") {
window.location = data.redirect;
} else {
$("#errorm").html(data.message);
}
I am new to jquery and phonegap and i am un able to find an answer to my question anywhere.
This is my index.html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo 2</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script src="jquery.mobile/jquery-1.7.2.min.js"></script>
<script src="jquery.mobile/jquery.mobile-1.1.0.min.js"></script>
<script src="main.js"></script>
</head>
<body onload="init()">
<div id="launcherPage" data-role="page">
<!-- I'm just here waiting for deviceReady -->
</div>
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Auth Demo</h1>
</div>
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
<div data-role="footer">
<h4>© Camden Enterprises</h4>
</div>
</div>
</body>
</html>
And my Js.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
handleLogin();
}
}
function handleLogin(){
var form = $("#loginForm");
var u = $("#username", form).val();
var p = $("#password", form).val();
//remove all the class add the messagebox classes and start fading
if(u != '' && p!= '') {
$.post("http://www.myaddress.com/loginlogin.php",{ user_name:$('#username', form).val(),password:$('#password', form).val(),rand:Math.random() } ,function(data)
{
if(data=='yes') //if correct login detail
{
//store
window.localStorage["username"] = u;
window.localStorage["password"] = p;
// $.mobile.changePage("some.html");
$.mobile.changePage( "some.html", { transition: "slideup"} );
}
else
{
navigator.notification.alert("Your login failed", function() {});
}
});
} else {
//Thanks Igor!
navigator.notification.alert("You must enter a username and password", function() {});
$("#submitButton").removeAttr("disabled");
}
return false;//not to post the form physically
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginPage");
}
Non of this is my own work but from here
http://www.raymondcamden.com/index.cfm/2011/11/10/Example-of-serverbased-login-with-PhoneGap
I changed the the example to work with php. This is very simple and only for testing purposes
php here
<?//get the posted values
require_once("backend/functions.php");
dbconn(true);
$username = $_POST['user_name'];
if ($username=='Steven'){
echo "yes";
}else{
echo "no";
}
?>
Now this all works and when the conditions are met the page some.html opens.
Now my question is .
How would i send the username of the logged in person to the page some.html?
once confirmed from the php file.
You should be able to access
window.localStorage["username"]
on your some.html page