Adding email into MySQL database with PHP, JQuery, Ajax - javascript

My code so far
main.js file:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
success: function(html) {
alert(html);
}
});
});
index.html file:
<form method="post">
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="submit" name="submit" id="addButton">Add User</button>
</form>
<!-- jQuery first, then Bootstrap JS. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
<script src="main.js"></script>
validation.php file:
<?php
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "my_username", "my_password", "my_db");
if (mysqli_connect_error()) {
die("Error Connecting To Database");
}
if (validateEmail($_POST['email'])) {
$query = "INSERT INTO `users` (`email`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."')";
if (mysqli_query($link, $query)) {
$success = "Email: ".$_POST['email']." added";
} else {
echo "Error in query";
}
}
}
?>
Here is my validate email function:
function validateEmail($email) {
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) {
echo "Invalid Email";
return false;
} else {
$domain = array('umich.edu');
list(, $user_domain) = explode('#', $email, 2);
return in_array($user_domain, $domain);
}
}
Am I performing my Ajax request incorrectly because it never adds the email to the database?

Try something this :
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
'email': email
},
success: function(html){
}
});

There is a lot of way to do that, but I think this is the best way and the easiest way for you to make it work base on your current code.
First thing, You don't need to use type="submit" button when using AJAX.
HTML should be,
<form id='emailform'>
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="button" name="submit" id="addButton">Add User</button>
</form>
Your JS should be something like this, use jQuery's .serialize() function to your form:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
data: $('#emailform').serialize(),
dataType: "html",
success: function(html) {
alert(html);
}
});
});

Try this ;)
$('#addButton').on('click', function(event){
/* prevent default behavior of form submission. */
event.preventDefault();
var email = $('#userInput').val();
$.ajax({
type: "post",
data: {
email: email,
submit: 1
},
url: "validation.php",
success: function(html){
alert(html);
}
});
});
You need to send email and submit because you wrapped all code in if (array_key_exists("submit", $_POST)) { means you are checking if the submit field submitted or not.

You can use below function also in your main.js.
Please remember that whenever you run any post request and if you want to send some data to server you need to mention that variable or json one of the parameter.
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp", {email: "hello#hello.com"},
function(data, status){
alert("Data sent!");
});
});
});
Or you can use the below code also for better understanding
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
email: email
},
contentType:'application/json',
success: function(html){
}
});

Related

im using jquery/ajax for login. Sending works and server side returns to log in, but this fails

I have created a login system with PHP, however, i also added two factor authentication. I wanted to log in without having to refresh the page so it looks better when asking for the 2FA code
The way i have done this is by sending the username and password via ajax. my php script then checks this and then it would echo login or error
Here's my javascript code
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'text',
success: function(data)
{
alert(data);
if (data === 'login') {
window.location = '/user-page.php';
}
else {
alert('Invalid Credentials');
}
},
});
});
});
This works fine, when i alert the data i get 'login' (without quotes, obviously) however it doesn't send me to user-page.php, instead, it gives me the invalid credentials alert. Despite the php page returning login, javascript is like "nope!"
What am i doing wrong?
Here's my form
<form class="form" id="login-form" name="login-form" method="post" role="form" accept-charset="UTF-8">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Gebruikersnaam</label>
<input type="username" class="form-control" id="gebruikersnaam" name="gebruikersnaam" placeholder="gebruikersnaam" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword2">Wachtwoord</label>
<input type="password" class="form-control" id="wachtwoord" name="wachtwoord" placeholder="Password" required>
<div class="help-block text-right">Forget the password ?</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</div>
</form>
I run the javascript from this page via <script src="auth.js"></script>. I also tried putting it directly inside script tags witch failed too.
This is for testing purpose
I believe your dataType should be either html or json
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data)
{
alert(data);
if (data == 'login') {
window.location = '/user-page.php';
}
if (data == 'failed') {
alert('Invalid Credentials');
}
},
});
});
});
In absence of your server logic
Your php inc/auth.php FOR Testing purpose
//$gebruikersnaam= $_POST['gebruikersnaam'];
//$wachtwoord= $_POST['wachtwoord'];
$gebruikersnaam= 'nancy';
$wachtwoord= 'nancy123';
if($gebruikersnaam=='nancy' && $wachtwoord=='nancy123')
{
echo "login";
}
else
{
echo "failed";
}
As for CSRF attack mentioned by SO Scholar in the comment. you will need to generate something like md5 token that will be stored in a session. you will now send it with each request eg. in a hidden form input and verify that it matches the one on the server side. if match allow login otherwise trigger impersonation
Updates
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'JSON',
success: function(data)
{
alert(data);
if (data.login == 'success') {
window.location = '/user-page.php';
}
if (data.login == 'failed') {
alert('Invalid Credentials');
}
},
});
});
});
PHP
<?php
error_reporting(0);
$gebruikersnaam= 'nancy';
$wachtwoord= 'nancy123';
if($gebruikersnaam=='nancy' && $wachtwoord=='nancy123')
{
$return_arr = array('login'=>'success');
}
else
{
$return_arr = array('login'=>'failed');
}
echo json_encode($return_arr);

ajax Uncaught ReferenceError: post is not defined at HTMLButtonElement.<anonymous>

Have no idea what it could be. Please help me release this ajax commentaries. I have never done this before. HTML form for input text and some ids:
<form id="send_comment" method="POST" action="write_comment.php">
<input hidden type="text" id="c_post_id" name="c_post_id" value="<?=$_GET["id"]?>">
<input hidden type="text" id="c_user_id" name="c_user_id" value="<?=$user_id?>">
<div class="form-group shadow-textarea">
<textarea class="form-control z-depth-1" type="text" id="c_text" rows="3" placeholder="Write comment here..." name="c_text" required pattern="^[a-zA-Z0-9\s]+$"></textarea>
</div>
<div class="col-md-12 text-center">
<button id="make_comment" class="btn btn-default" name="make_comment" type="submit" value="Submit"><i class="fas fa-check" style="font-size: 35px;"></i></button>
</div>
</form>
PHP processing:
if($_POST["make_comment"]) {
$c_post_id = $_POST["c_post_id"];
$c_user_id = $_POST["c_user_id"];
$c_text = $_POST["c_text"];
$date = date("m/d/y G:i:s<br>", time());
$sql = "INSERT INTO `comments` VALUES ('$c_post_id','$c_user_id',null,'$c_text','$date')";
if ($connect->query($sql) === TRUE) {
header("Location: http://thecobnmod.com/post.php?id=$c_post_id");
}
else {
exit( "Error: " . $sql . "<br>" . $conn->error);
}
}
JS ajax:
function funcSuccess (data) {
$("#comment_ajax").text(data);
}
function funcBefore (){
$("#comment_ajax").text("Loading comment...");
}
$(document).ready(function(){
$("#make_comment").bind("click", function () {
event.preventDefault();
$.ajax({
post: $("#c_post_id").val(),
user: $("#c_user_id").val(),
text: $("#c_text").val(),
url: "write_comment.php",
type: "POST",
data: {
c_post_id:post,
c_user_id:user,
c_text:text
},
dataType: "html",
beforeSend: funcBefore,
success: funcSuccess
});
});
});
Post id comes fro GET request to input field. I thought it could be a problem but not. now I really do not know what's wrong. Please help.
I strongly recommend consulting the documentations: Ajax doc
Ajax doesn't have post property AFAIK!
I'm not sure what you wanted to do, but here is a simple ajax example:
$.ajax({
url: 'here/is/some/url',
type: 'post',
data: {
some_key: 'value1',
other_key: 'value2',
/*...*/
},
dataType: 'html',
beforeSend: function() {/*...*/}
success: function(result) {/*...*/},
error: function(error) {/*...*/}
});

Sending data to php file AJAX

So I have a target. It's to have a live area where you type in a username and every time you let a key go onkeyup() in the input area, I want it to send that data to a php file where that file will return what you just typed in and display it out where I want it. This isn't going as I like though :P. Please help, and thanks in advance.
JavaScript/jQuery/Ajax Code
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "GET",
url: "php/return.php",
data: user,
cache: false,
success: function(data){
$("#username-display").text(data);
}
});
}
HTML Code
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP Code
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $username;
?>
Please let me know if you need more info to help me solve this...
hey you can use following code
HTML CODE
<script type="text/javascript">
function changeUsername() {
// var user = $("#user").val();
$.ajax({
type: "GET",
url: "s.php",
data: {'user':$("#user").val()},
success: function(data){
$("#username-display").text(data);
}
});
}
</script>
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP CODE
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $_GET["user"];
?>
You need to correct your AJAX code also change type from GET to POST in php code so, final code will be like -
function changeUsername() {
var user = $("#user").val();
$.ajax({
url: "data.php",
data: {'user': user},
type : 'post',
success: function (data) {
$("#username-display").text(data);
}
});
}
PHP CODE :-
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo json_encode($username);
Change Get to Post.
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "POST",
url: "php/return.php",
data: {'user': user},
cache: false,
success: function(data){
alert(data);
$("#username-display").text(data);
}
});
}
Php code first try to get response.
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo $username; exit;
Try:
echo( json_encode( $username ) );
exit( 1 );

How to get ID from DB if user enters INT to text input using Ajax/PHP?

I'm running a database with itemID's and a shelfnumber for every itemID..
As the user enters an itemID I want it to run through my database to get the shelfnumber using Ajax/PHP. Then post the shelfnumber back so the user can see where to find the item. (The items are in a room and are marked with unique ID's and shared shelfnumbers.) I need to use the onChange method (or anything similar) beacuse I want it to work like a tip/search engine. In other words automatic..
I'm totally new to ajax and I can't seem to get this to work at all.. No result is given and i'm at a roadblock right now.. Any form of help will be very appreciated
HTML
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
},
success:function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
}
});
});
</script>
</head>
<body>
<a>Enter Item ID 1:</a>
<input id="target" type="text" name="itemID" required />
<div id="hyllplacering">ENTER Shelfnumber here: </div>
</body>
</html>
PHP
<?php
$con = mysql_connect("localhost", "root", "") OR die(' Could not connect');
$db = mysql_select_db('book1', $con);
$itemID = filter_input(INPUT_POST, 'itemID', FILTER_VALIDATE_INT);
$query = "SELECT Hyllplacering from booking WHERE itemID = $itemID";
$result = mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo json_encode(array('itemID' => $itemID, 'Hyllplacering' => $row['Hyllplacering']));
?>
JavaScript is executed as soon as it is encountered. You bind the Event to an Element before it is available.
You need to wrap the script in a document.ready body.
As the other answers mentioned you want to use the success callback instead of done.
<script>
$(document).ready(function(){
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
};
})
.success(function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
});
});
});
</script>
You may add a sentence in AJAX function
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
};
success:function(data){
console.info(data);
}
})
to monitor what your PHP responsed, it's more easy to check what's wrong.
I think you incorrect to use the done method of the Ajax object. I am pretty sure you wont have your response available in that scope. Try to do it like..
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
},
success:function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
},
error:function(response){
alert('error '+response);
};
})
});

PHP/JS - pass values with AJAX

I am trying to get the value of a textbox without pass through form actions (because i cannot neither redirect to another page or refresh the current one).
index.php
into head
<script type="text/javascript">
function send() {
$.ajax({
type:"POST",
url: "script.php",
data: {
fname: document.getElementById("fname").value,
lname: document.getElementById("lname").value
},
success: function callScriptAndReturnAlert() {
var sdata = new XMLHttpRequest();
sdata.onload = function() {
alert(this.responseText);
};
sdata.open("get", "script.php", true);
sdata.send();
}
});
}
</script>
into body
<button class="myclass" onclick="send();">MyButton</button>
<input type="text" id="fname" placeholder="First name here" />
<input type="text" id="lname" placeholder="Last name here" />
Button is before input just for UI stuffs
script.php
$prev = $_SESSION['prev'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
[....do something....]
echo 'You used '.$fname.' and '.$lname;
Well.. the script.php doesnt receive the value of the inputs fname and lname.
You are trying to make two ajax calls when you only need one.
<script type="text/javascript">
function send() {
$.ajax({
type:"POST",
url: "script.php",
data: {
fname: $("#fname").val(),
lname: $("#lname").val()
},
beforeSend: function(){
alert('Sending');
},
success: function(data) {
//Received data from PHP script
alert(data);
},
error: function(){
alert('Error !');
},
complete: function(){
alert('Done');
}
});
}
</script>
$.post(
'script.php', // Your PHP file
{ // The data to pass
'fname' : $('#fname').val(),
'lname' : $('#lname').val()
}
).done(function(data) { // Here your AJAX already finished correctly.
alert(data); // Show what the PHP script returned
});
The $.ajax(), $.get() and $.post() jQuery methods are for making AJAX calls and, due to that, they already manage their own XMLHttpRequest object.

Categories

Resources