I’m new to jQuery and AJAX and I’m working on a login-page as a project and I need to retrieve data from a database using AJAX. I’m not 100% fluent in English so I’ll do my best to explain the problem (with help from Google Translate).
Here’s the code I’m using:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<form validate="">
<input type="text" placeholder="Username" id="username" required/><br />
<input type="password" placeholder="Password" id="password" required/><br />
<input type="submit" id="submit" value="Login" />
</form>
<script type="text/javascript">
// when document is loaded
$(document).ready (
// when submit is clicked
$("#submit").click (
// sets test to null
var test = null;
// sets username to value of username input
var username = document.getElementById("username").value;
// AJAX request
$.ajax({
type: "POST",
async: true,
url: test.php,
data: {username: username},
success: function (data) {
test = data;
console.log(test);
return test;
}
});
);
);
</script>
</body>
</html>
test.php
<?php
// connects to database
$conn = mysqli_connect('server', 'username', 'password', 'database');
// sets var username to POST username value
$username = $_POST['username'];
// SQL Query
$sql = "SELECT * FROM users WHERE username='" . $username . "'";
$result = mysqli_query($conn, $sql);
// sets result to mysqli_fetch_assoc()
$result = mysqli_fetch_assoc( $result );
// echos $result
echo $result['password'];
// closes database connection
mysqli_close( $conn );
?>
Console Log
Console Output:
“`
[DOM] Input elements should have autocomplete attributes (suggested: “current-password”): (More info: https://www.googlesite.com)
Uncaught SyntaxError: Unexpected token var ajax.html:19
I've looked at the code and I can't seem to find an error.
Thanks in advance! ;)
>P.S.
>It's probably going to end up being some stupid typo.
>Other than that, have a great day!
2
Answers
You need to pass in a function to your document.ready() call and your click() call.
Instead of using
click
event you can usesubmit
.In your case, just give
id
to yourform
like –Now,
In your
js
script –So check your whole code –
Hope this will help you.