AJAX request posts on second submit - javascript

I was making a form to post data, combined with Ajax. Below is all code associated with it. The problem is that when filling the form in and submitting, on the first click it does the XHR request, and get's a success call back so changes the button to Done!.
But the results don't appear in the database. When clicking the submit button again, it does another XHR request that DOES get through. Any ideas what could cause this? Thanks!
// Method for updating the post in User.php
public function updatePost($id, $title, $content){
$query1 = $this->conn->prepare("UPDATE posts SET post_title=:post_title, post_content=:post_content WHERE post_id=:post_id");
$query1->bindparam(":post_title", $title);
$query1->bindparam(":post_content", $content);
$query1->bindparam(":post_id", $id);
try {
$query1->execute();
} catch (Exception $e) {
echo $e->getMessage();
}
} ?>
// Backend for the authenication and validation (where the form posts to)
<?php
session_start();
require_once("../User.php");
$login = new User();
$errors = [];
$post_title = $_POST['post-title'];
$post_content = $_POST['post-content'];
$post_id = $_POST['post-id'];
if( isset($post_title) && isset($post_content) && isset($post_id) ){
if( empty($post_title) ){
$errors[] = "The entered title is invalid in some way.";
}
elseif (empty($post_content)) {
$errors[] = "The entered content is invalid in some way.";
}
elseif(empty($post_id)){
$errors[] = "An internal error has occured, please contact the system administrator.";
}
else{
try {
if( !$login->updatePost($post_id, $post_title, $post_content) ){
echo "allrighty";
}
else{
echo "charliewegotaproblem";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
?>
// JS for the Ajax request itself
$("form").submit(function(evt){
evt .preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax(url, {
data: formData,
type: "POST",
success: function(response){
if(response == "allrighty"){
$(".update-submit").prop("value", "Done!")
}
else if (response == "charliewegotaproblem") {
$(".update-submit").prop("value", "Something went wrong...")
}
}
}); // Ajax OBJECT END;
});// Submit END

<?php
==> First return success message, if post update query has executed successfully in updatePost function
// Method for updating the post in User.php
public function updatePost($id, $title, $content){
$success = false; // Here I changed the code
$query1 = $this->conn->prepare("UPDATE posts SET post_title=:post_title, post_content=:post_content WHERE post_id=:post_id");
$query1->bindparam(":post_title", $title);
$query1->bindparam(":post_content", $content);
$query1->bindparam(":post_id", $id);
try {
$query1->execute();
if($query1){ $success = true; } // Here I changed the code
} catch (Exception $e) {
echo $e->getMessage();
}
return $success;
}
==> Now here if $login has return true than an only than "allrighty" will return
// Backend for the authenication and validation (where the form posts to)
session_start();
require_once("../User.php");
$login = new User();
$errors = [];
$post_title = $_POST['post-title'];
$post_content = $_POST['post-content'];
$post_id = $_POST['post-id'];
if( isset($post_title) && isset($post_content) && isset($post_id) ){
if( empty($post_title) ){
$errors[] = "The entered title is invalid in some way.";
}
elseif (empty($post_content)) {
$errors[] = "The entered content is invalid in some way.";
}
elseif(empty($post_id)){
$errors[] = "An internal error has occured, please contact the system administrator.";
}
else{
try {
if($login->updatePost($post_id, $post_title, $post_content)){ // Here I changed the code
echo "allrighty";
}
else{
echo "charliewegotaproblem";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
?>

Related

[Ajax][PHP] - login form, response is always empty

I have a problem with my login form. Every time when i write (correct or incorrect) login and password in my login form, my JS script return error and when i try to print "response" it is empty.
Can anyone help?
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var name = $("#name").val().trim();
var paw = $("#paw").val().trim();
$.ajax({
url: 'check.php',
type: 'POST',
data: {name:name, paw:paw},
success: function(response){
if(response == 1){
window.location= "home.php";
}
else{
alert("error");
}
}
});
});
});
<?php
session_start();
require_once 'dbconfig.php';
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST['submit']))
{
$name = trim($_POST['name']);
$paw1 = trim($_POST['paw']);
$paw = md5($paw1);
try {
$stmt = $pdo->prepare("SELECT * FROM user WHERE login=:nazwa and haslo=:has");
$stmt->execute(array(':nazwa'=>$name, ':has'=>$paw));
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['haslo']==$paw){
echo 1;
$_SESSION['user_session'] = $row['login'];
}
else {
echo 0;
}
} catch (\Exception $e) {
echo $e->getMessage();
}
}
?>
Remove the if(isset($_POST['submit'])) line. The reason is that the button key value is not sent via the AJAX call. To verify, do a print_r($_POST);
instead verify that name and password variables are not empty()
if (!empty($_POST['name']) && !empty($_POST['paw'])) {
}
Also do not use md5() for your passwords. use php's password_hash() to hash and password_verify() to verify that the posted password via the form matches the hash stored in the database for that user.

Inserting to database after validation has passed using ajax, php and javascript

This my signUp.php I dont know what is wrong here that prevents my form values from being inserted into the database
<?php
$errors = array();
$data = array();
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if(empty($_POST["full_Name"])){
$errors['full_Name'] = "Please fill in yor full name";
}
else{
$full_Name = test_Inputs($_POST['full_Name']);
//using regular expression to check if the name includes only letters and whitespaces
if(#!preg_match("/^[A-z\s]*$/", $full_Name)){
$errors['full_Name'] = "Only alphabets and whitespace";
}
}
if(empty($_POST['user_phoneNumber'])){
$errors['user_phoneNumber'] = "Mobile number is required";
}
else{
$mobileNumber = test_Inputs($_POST['user_phoneNumber']);
// using regex to make sure only numbers are inputted in the field
if(#!preg_match("/^[0-9]+$/", $mobileNumber)){
$errors['user_phoneNumber'] = "Only numbers allowed";
}
}
if(empty($_POST['user_Email'])){
$errors['user_Email'] = "Please fill in your email address";
}
else{
$Email = test_Inputs($_POST['user_Email']);
//using regex to validate email input
if(#!preg_match("/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/", $Email)){
$errors['user_Email'] = "Invalid Email address";
}
}
if(empty($_POST['userName'])){
$errors['userName'] = "User name field is blank";
}
else{
$userName = test_Inputs($_POST['userName']);
if(#!preg_match("/^[A-z0-9]+$/", $userName)){
$errors['userName'] = "Only letters and numbers allowed";
}
}
if(empty($_POST['password'])){
$errors['password'] = "Password field is blank";
}
else{
$password = test_Inputs($_POST['password']);
if(#!preg_match("/^[A-z0-9]+$/", $password)){
$errors['password'] = "Only letters and numbers allowed";
}
if(strlen($password) < 8){
$errors['password'] = "Password must be at least 8 characters long";
$valid = false;
}
}
if(empty($_POST['RPassword'])){
$errors['RPassword'] = "Confirm your password";
$valid = false;
}
else{
$RPassword = test_Inputs($_POST['RPassword']);
if($RPassword != $password){
$errors['RPassword'] = "Passwords do not match";
}
}
if(!isset($_POST['terms'])){
$errors['terms'] = "Agree to the terms";
}
else {
$Terms = test_Inputs($_POST['terms']);
}
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// Inserting into the database
require_once ('insert_user.php');
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
//return all our data on AJAX call
echo json_encode($data);
//creating the test_puts functions
function test_Inputs($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
This is my dbConn.php
<?php
$host = "localhost";
$db_name = "Interns";
$username = "root";
$password = "";
try {
$dbh = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $ex){
echo "Failed to connect" .$ex->getMessage();
}
this is my insertUser.php code
<?php
require_once ('dbConn.php');
$salt = "cH!swe!retR:";
If(isset($_POST['submit'])) {
try {
$stmt = $dbh->prepare("INSERT INTO Users(FullName, MobileNumber, Email, Username, Password)
VALUES(:user_name, :user_mobile, :user_email, :user_username, :user_pass)");
$stmt->bindParam(":user_name", $full_Name);
$stmt->bindParam(":user_mobile", $mobileNumber);
$stmt->bindParam(":user_email", $Email);
$stmt->bindParam(":user_username", $userName);
$stmt->bindParam(":user_pass", $password);
$full_Name = $_POST['full_Name'];
$mobileNumber = $_POST['user_phoneNumber'];
$Email = $_POST['user_Email'];
$userName = $_POST['userName'];
$password = SHA1(($_POST['password']), $salt);
$stmt->execute();
echo "Query successful";
} catch (PDOException $ex) {
echo "Query Failed" . $ex->getMessage();
}
}
$dbh = null;
This is my signUp.js
// signUpValidation.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'full_Name' : $('input[name=full_Name]').val(),
'user_phoneNumber' : $('input[name=user_phoneNumber]').val(),
'user_Email' : $('input[name=user_Email]').val(),
'userName' : $('input[name=userName]').val(),
'password' : $('input[name=password]').val(),
'RPassword' : $('input[name=RPassword]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'signUpValidation.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for name ---------------
if (data.errors.full_Name) {
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#name-group').append('<div class="help-block">' + data.errors.full_Name + '</div>'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.user_phoneNumber) {
$('#mobile-group').addClass('has-error'); // add the error class to show red input
$('#mobile-group').append('<div class="help-block">' + data.errors.user_phoneNumber + '</div>'); // add the actual error message under our input
}
// handle errors for superhero alias ---------------
if (data.errors.user_Email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.user_Email + '</div>'); // add the actual error message under our input
}
if (data.errors.userName) {
$('#username-group').addClass('has-error'); // add the error class to show red input
$('#username-group').append('<div class="help-block">' + data.errors.userName + '</div>'); // add the actual error message under our input
}
if (data.errors.password) {
$('#password-group').addClass('has-error'); // add the error class to show red input
$('#password-group').append('<div class="help-block">' + data.errors.password + '</div>'); // add the actual error message under our input
}
if (data.errors.RPassword) {
$('#retypePassword-group').addClass('has-error'); // add the error class to show red input
$('#retypePassword-group').append('<div class="help-block">' + data.errors.RPassword + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
I would be glad if someone puts me through. Please note I sent the form through an AJAX call to the signUp.php.
Do you know about this in your AJAX code: url: 'signUpValidation.php',
sinse your file is signUp.php?
That is a lot of code but you are calling signUp.php then require_once ('insert_user.php'); in it and then in insert_user you are using $_POST["full_Name"] again even when you validated it already in signUp.php. Shouldn't insert_user.php just make the query in the DB?
And you are checking If(isset($_POST['submit'])) in insert_user.php. You should check it in signUp.php.
I would organize the code in functions at least if not classes: functionConnectToDB, fnInsertUser...
signUp.php:
require_once('functions.php');
if(isset($_POST['submit'])) {
validations you have
}
if (empty($errors)) {
fill $data array with $full_Name etc. cause you didn't do it!
insertUser($data);
}
functions.php:
function connectDB() {
...
}
function insertUser($data) {
connectDB();
insert DB query
...
}

Ajax url: parameter and checking for success

im not so sure how this works, but where does my success(data) value come from?
must I return a value in url: php/login.php?
$.ajax({
url: 'php/login.php', //must i return a value in login.php?
data: {username:username,password:password},
type: "POST",
dataType: 'json',
success: function(data)
{
if(data == true){
console.log("sdfsdfs " + data);
login.submit();
}
else{
console.log("NO DATA PRESENT");
}
}
//else do an alert("please lgo in again");
});
in php/login.php i query the DB to see if such a user exists and if password match
part of my login.php
<?php
echo $username = $_POST['username']; //not echo-ing
echo $password = $_POST['password'];
if ($_POST['login']) //check if the submit button is pressed
{
$remember = $_POST['remember'];
if ($username&&$password) //check if the field username and password have values
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$connect=mysqli_connect($dbhost,$dbuser,$dbpass) or die("Unable to Connect");
mysqli_select_db($connect,"clients") or die("Could not open the db");
$sql = "SELECT * FROM clients.users WHERE username='$username'";
$login = mysqli_query($connect, $sql);
if (mysqli_num_rows($login))
{
while ($row = mysqli_fetch_assoc($login))
{
$db_password = $row['password'];
if ($password==$db_password)
{
$loginok = TRUE;
echo json_encode( true );
} else {
echo json_encode( false );
echo "Please re-enter username and password, they did not match";
header("Location: ../login.php");
}
?>
When you want to return some data using ajax, you need to echo data in your script that will be called by ajax. If the request is successful, it will return everything you echoed in your script into your parameter you specified in success function.
success: function(data)
{
// code...
}
so "data" will contain result from your script, then you can do whatever you want.
EDIT:
Well, i would solve it like this
$db_password = $row['password'];
if ($password==$db_password)
{
echo json_encode(array("status" => "ok", "message" => "Login successful!"));
} else {
echo json_encode(array("status" => "error", "message" => "Please re-enter username and password, they did not match!"));
//header("Location: ../login.php"); you don't need this
}
you can't echo json, then some text after it. You can, but it is not recommended at all.

EOF / Failed to load error when calling PHP file with AJAX

Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.

JavaScript Prompt Box Cancel Button?

I have a JavaScript function as follows:
function popup(username) {
var req = createAjaxObject();
var message = prompt("Message:","");
if(message != ""){
req.onreadystatechange = function() {
if (req.readyState == 4) {
alert(req.responseText);
}
}
req.open('POST','getmessage.php',true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("username=" + username +"&message="+message);
} else {
alert("Please enter a message");
}
}
When the Cancel button is hit, the form is still processed through getmessage.php. Any way to have the Cancel button do nothing?
EDIT:
Here is the way this function is called:
<?php
mysqlLogin();
$username = $_COOKIE['sqlusername'];
$sql = mysql_query("SELECT username FROM `users` WHERE username!='$username'");
if(mysql_num_rows($sql) != 0) {
echo "<table class='usertable' align='center'>";
while($row = mysql_fetch_array($sql)){
$username = $row['username'];
echo "<tr><td><center>" . $row['username'] . "</center></td><td> Send Message</td></tr>";
}
echo "</table>";
} else {
echo "<center>No users found!</center>";
}
?>
The PHP script its linked to:
<?php
$id = rand(1,1500);
$poster = $_POST['username'];
$message = $_POST['message'];
$to = $_COOKIE['sqlusername'];
require('functions.php');
mysqlLogin();
$sql = mysql_query("INSERT INTO `messages` VALUES ('$id','$message','$to','$poster','')");
if($sql){
echo "Message sent!";
} else {
echo "Woops! Something went wrong.";
}
?>
In the case of Cancel, the prompt result is null, and null != '' (as per ECMA-262 Section 11.9.3).
So, add an extra explicit check for null inequality:
if(message != "" && message !== null) {
However, since the message is either some string or null and you only want to pass when it's a string with length > 0, you can also do:
if(message) {
This means: if message is truthy (i.e. not null or an empty string, amongst other falsy values), then enter the if clause.
Are you using Safari by any chance? I have found that Safari seems to be returning empty string instead of null when the user clicks Cancel.
See here: Safari 5.1 prompt() function and cancel.
Yeah, my suggested comment does work
var message = prompt("Message:","");
if(message){
alert("Not working!");
} else {
alert("Working!");
}
JSFiddle
var message = prompt("Message:","");
if(message){
alert("Message accepted, now i can process my php or script and blablabla!");
} else {
alert("Cancel Press or Empty Message, do nothing!");
}
var message = prompt('type any...', '');
if(message+'.' == 'null.')
{
alert("you've canceled");
}
else
{
alert("type ok");
}
$.messager.prompt('Save To File', 'FileName:', function(e){
if (e.response!='undefined'){
if (r!="")
{
alert('Your FileName is:' + r);
}
else
{
$.messager.alert('Err...','FileName cannot empty!!!');
}
}
});

Categories