I am creating a program and am having trouble passing user credentials into a database. I am using the AJAX .post function and for some reason, the data is not being passed into the PHP script.
The submitInfo() function seems to completely bypass the .post function nested inside, as the page does notify me with the successful sign in alert after pressing submit.
Here is the HTML/JS file, (doesn't show the implementation of jQuery along with an imported MD5 function I'm utilizing to hash the password):
<h2>First name:<h2>
<input id="firstNameInput" type="text" maxLength="20">
<h2>Last name:<h2>
<input id="lastNameInput" type="text" maxLength="20">
<h2>Create a username:<h2>
<input id="createUserInput" type="text" maxLength="20">
<h2>Create a password:<h2>
<input id="createPassInput" type="text" maxLength="20">
</br>
</br>
<input id="submitCredsButton" type="submit" onclick="submitInfo()">
<script>
function submitInfo()
{
var postData = [{
firstName : document.getElementById("firstNameInput"),
lastName : document.getElementById("lastNameInput"),
username : document.getElementById("createUserInput"),
hashPass : MD5((document.getElementById("createPassInput")).value)
}];
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: "postData",
dataType: "text",
});
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
</script>
And here is the PHP script, in a separate file:
<?php
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//posts data to db
$stmt = $data->('INSERT INTO userlist
(firstName,lastName,username,hashedPass)
VALUES (:firstName, :lastName, :username, :hashPass)');
$stmt->execute($data);
?>
-edit-
Figured it all out, one simple but overlooked mistake I had was where I had placed the single and double quotes. Thanks to all users that helped with the JS issues I was having!
HTML/JS:
<h2>First name:<h2>
<input id="firstNameInput" type="text" maxLength="20">
<h2>Last name:<h2>
<input id="lastNameInput" type="text" maxLength="20">
<h2>Create a username:<h2>
<input id="createUserInput" type="text" maxLength="20">
<h2>Create a password:<h2>
<input id="createPassInput" type="text" maxLength="20">
</br>
</br>
<input id="submitCredsButton" type="submit" onclick="submitInfo()">
<script>
function submitInfo()
{
var fName = document.getElementById("firstNameInput").value;
var lName = document.getElementById("lastNameInput").value;
var uName = document.getElementById("createUserInput").value;
var pPass = document.getElementById("createPassInput").value;
var hPass = MD5((document.getElementById("createPassInput")).value);
if(fName.length <= 0 || lName.length <= 0 || uName.length <= 0 || pPass.length <= 0)
{
alert("Please verify all fields have been filled out.");
}
else
{
$.ajax
({
type: "POST",
url: "phpScripts/signup.php",
data: {firstName: fName, lastName: lName, userName: uName, hashPass: hPass},
dataType: "text",
success: function(response)
{
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
});
}
}
</script>
PHP Script:
<?php
$servername = "******";
$username = "******";
$password = "******";
$dbname = "******";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
?>
<?php
//posts data to db
$fName = $_POST["firstName"];
$lName = $_POST["lastName"];
$uName = $_POST["userName"];
$hPass = $_POST["hashPass"];
$sql = "INSERT INTO userlist ( firstName,lastName,username,hashedPass )
VALUES ( '$fName', '$lName','$uName','$hPass' )" ;
$result = $conn->query($sql);
if($result){
echo "true";
}
else{
echo "false";
}
?>
You have written "postData" in double quote, so it will consider as string, but actually it is variable.
Try :
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
});
The problem is that you are using "postData" which is just a string but you need to use postData because it already has definition.
Just replace "postData"
with postData
Ajax
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
});
First problem. You are not passing a string to the $.ajax. You have to pass the variable which is an object: data: postData,.
Second problem. Your postData is an array but it has to be an object:
var postData = {
firstName : document.getElementById("firstNameInput"),
lastName : document.getElementById("lastNameInput"),
username : document.getElementById("createUserInput"),
hashPass : MD5((document.getElementById("createPassInput")).value)
};
Third problem. Your are passing DOM objects as postData instead of their values. Just use .value property:
var postData = {
firstName : document.getElementById("firstNameInput").value,
lastName : document.getElementById("lastNameInput").value,
username : document.getElementById("createUserInput").value,
hashPass : MD5((document.getElementById("createPassInput")).value)
};
Fourth problem. The $.ajax is asynchronous so you have to provide a success callback, so the callback will be run just after the finish of the request:
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
success: function () {
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
});
Complete solution:
function submitInfo()
{
var postData = {
firstName : document.getElementById("firstNameInput").value,
lastName : document.getElementById("lastNameInput").value,
username : document.getElementById("createUserInput").value,
hashPass : MD5((document.getElementById("createPassInput")).value)
};
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
success: function () {
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
});
}
$.ajax() in an asynchronous function. You need to use its success(result,status,xhr) callback to show actual success message.
What you are doing is show the success alert outside Ajax call.
The code should be:
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
success: function(html){
$("#results").append(html);
}
});
Your postData is an object does not need to so round in quotes "" and include a success call back and in success call back try to redirect on login page. Try this:
<script>
function submitInfo()
{
var postData = [{
firstName : document.getElementById("firstNameInput"),
lastName : document.getElementById("lastNameInput"),
username : document.getElementById("createUserInput"),
hashPass : MD5((document.getElementById("createPassInput")).value)
}];
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
success: function(response){
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
});
}
</script>
Basically you needs to get value of textboxs. And also in Ajax function you need to pass as a Object (Currently you are passing as String)
<script>
function submitInfo()
{
var postData = [{
firstName : document.getElementById("firstNameInput").value,
lastName : document.getElementById("lastNameInput").value,
username : document.getElementById("createUserInput").value,
hashPass : MD5(document.getElementById("createPassInput").value)
}];
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
});
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
</script>
You need to change
data: "postData",
With
data: postData,
And add success variable after dataType: "text",
success: function(res){
if(res=="true"){
alert("Sign up Successful! Please log in to enter.");
}
else{
alert("something went wrong.");
}
}
and add this line in your php script after $stmt->execute($data);
$result=$stmt->execute($data);
if($result){
echo "true";
}
else{
echo "false";
}
Related
I have an AJAX call in my codeigniter project. Here is my code:
in view :
$('#forgotPassword').click(function() {
var base_url = '<?php echo base_url()?>';
$('#forgotPasswordEmailError').text('');
var email = $('#forgotPasswordEmail').val();
console.log(email);
if(email == ''){
$('#forgotPasswordEmailError').text('Email is required');
}else{
$.ajax({
url : base_url + 'Home/forgotPassword',
type : 'POST',
data : {email : email},
success: function(data) {
console.log(data);
//location.reload();
}
});
}
});
and controller :
public function forgotPassword() {
$email = $this->input->post('email');
echo $email;
}
but the response contains only the html content from my view. I couldn't identify what is happening.
change your jquery code to
$('#forgotPassword').click(function() {
var base_url = '<?php echo base_url()?>';
$('#forgotPasswordEmailError').text('');
var email = $('#forgotPasswordEmail').val();
console.log(email);
if(email == ''){
$('#forgotPasswordEmailError').text('Email is required');
}else{
$.ajax({
url : base_url + 'Home/forgotPassword',
type : 'POST',
data : {email : email},
dataType:'json',
success: function(data) {
console.log(data);
//location.reload();
}
});
}
});
change your controller code like
public function forgotPassword() {
$email = $this->input->post('email');
$response = ["email" => $email];
echo json_encode($response);
}
Instead of
echo $email;
use:
$response = ["email" => $email];
return json_encode($response);
And parse JSON, on client side, using JSON.parse.
hi maybe i can help someone, i had the same problem, in my case the error was here "url : base_url + 'Home/forgotPassword'"
in this example i have to pass all way like this url : /anotherdirectory/Home/forgotPassword.php',
take a look in your "url"
$.ajax({
url : "change here fo works"',
type : 'POST',
data : {email : email},
dataType:'json',
success: function(data) {
console.log(data);
//location.reload();
}
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 );
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){
}
});
Ajax jquery always running error function, althought success function run and i can get session value,i can't run window.location="profile.php";
$(document).ready(function(){
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
type: "POST",
url: "model/user.php",
data: {
user_log : username,
password : password
},
dataType: 'json',
error: function (xhr,textStatus,errorThrown) {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
},
success: function(json){
window.location="profile.php";
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
user.php
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
require_once(dirname(__FILE__).'/../model/connect.php');
?>
<?php
global $pdo;
if(isset($_POST['user_log'])) {
// username and password sent from Form
$username=$_POST['user_log'];
$password=$_POST['password'];
$qr= "SELECT * FROM user where username='$username' AND password='$password'" ;
$stmt= $pdo->query($qr);
$row= $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$_SESSION['id']=$row['id'];
$_SESSION['name_mem']=$row['username'];
$_SESSION['level_mem']=$row['level'];
}
header("location:../../../../index.php");
}
?>
Remove this line :
header("location:../../../../index.php");
If above doesn't work, omit this from ajax properties :
dataType: 'json',
you can use ajax like this,
<script>
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//progress
xhr.upload.addEventListener("progress", function(e) {
//progress value : you can load progress bar in here
}, false);
return xhr;
},
type: "POST",
url: "model/user.php",
data: {'username' : username, 'password' : password},
dataType:json,
success: function(msg) {
//when success //200 ok
if(msg.status=="done"){
window.location="profile.php";
}else{
$("#error").html("<span style='color:#cc0000'>Error:</span> "+msg.massage);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//when error: this statement will execute when fail ajax
}
});
});
</script>
server side code like this(inside user.php),
$username=$_POST['username'];
$password=$_POST['password'];
...........
//$status="fail" or "done"
//success must be always success
//$massage= "password or username not match"
$respond=array("success"=>"success","status"=>$status,"massage"=>$massage);
echo json_encode($respond);
exit;
I hope you useful this.
I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}