My page doesn't refresh when there are no errors.
I used:
window.location.reload(true);
That is supposed to be executed when data.success returns True.
I'm new to PHP and AJAX, so I'm using this as a guide. I know how to process info to server, but I want to display messages without leaving the page.
PHP:
<?php
// connects to "ajax" database
mysql_connect("localhost", "root", "password");
mysql_select_db("ajax");
// assigns variables to fields
$name = $_POST['name'];
$email = $_POST['email'];
$superheroAlias = $_POST['superheroAlias'];
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['superheroAlias']))
$errors['superheroAlias'] = 'Superhero alias is required.';
// return a response ===========================================================
// 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 {
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$query = #mysql_query($sql);
header("location: /");
}
// return all our data to an AJAX call
echo json_encode($data);
?>
JS
// magic.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 = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'superheroAlias' : $('input[name=superheroAlias]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.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.name) {
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
}
// handle errors for superhero alias ---------------
if (data.errors.superheroAlias) {
$('#superhero-group').addClass('has-error'); // add the error class to show red input
$('#superhero-group').append('<div class="help-block">' + data.errors.superheroAlias + '</div>'); // add the actual error message under our input
}
} else {
window.location.reload(true);
}
})
// 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();
});
});
There are many errors in your code. To begin with, the reason your AJAX call is only executed when there are errors is because you're relocating your page when there aren't any errors.
header("location: /");
Is your culprit. You're relocating the page before you can ever output any JSON. Second of all, your $data variable doesn't contain the [success] key when there is a successful $_POST transit. So even if you weren't to relocate, you still wouldn't be outputting any useful data. Third of all, you never saved a link to your MySQL database, you only instantiated it. Also, you're going to want to use mysqli_ because mysql_ is deprecated.
Change those first two lines of code to this:
$link = new mysqli( "localhost", "root", "password", "ajax" );
Change that if-statement to this:
if ( ! empty( $errors ) ) {
$data["errors"] = $errors;
$data["success"] = false;
} else {
$data["success"] = true;
$data["errors"] = $errors; // There are none, so this isn't neccessary
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$link->query( $sql );
}
By the way, I hope this is for demonstration purposes only, because that is some terrible validation/sanitation. If it isn't, here are some useful links:
http://www.phpro.org/tutorials/Validating-User-Input.html -- In-depth tutorial on sanitation/validation
http://php.net/manual/en/book.mysqli.php -- Your guide to the MySQLi library.
remove header("location: /"); from your php file in else part.
I think this will redirect page so, your response is not like you want.
Here If condition fails then check for $data in else and remove header from else.
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$query = #mysql_query($sql);
$data['success'] = false;
//header("location: /");
}
// return all our data to an AJAX call
echo json_encode($data);
Related
So my database does not add this data into the database when the button is pressed.
I have created a form, and all the id's are perfect and the email is a foreign key so it is taken from sessionStorage of the logged in user. I need help with why it is not working, I have no idea. The page alerts me "the order was successful" when I press submit but the data does not get stored in the database.
My SQL statement also works definitely, I tried it in my database.
Here are my php and js:
<?php
header("Content-Type: application/json; charset=UTF-8");
$servername = "localhost";
$username = "root";
$password = "leaf123";
$dbname = "laxmi";
// Create Connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed:" . mysqli_connect_error());
}
else
{
// Obtain the contents
$request = file_get_contents('php://input');
// decode json so PHP can use it
$jsonRequest = json_decode($request);
// Query
$sql = "INSERT INTO checkout(email, ccName, ccNumber, month, year, cvc) VALUES ('$jsonRequest->email', '$jsonRequest->ccName', '$jsonRequest->ccNumber', '$jsonRequest->month', '$jsonRequest->year', '$jsonRequest->cvc')"
}
// Execute Query
$results = mysqli_query($conn, $sql);
echo json_encode("success");
mysqli_close($conn);
my javascript
$(document).ready(function () {
//When the submit button on the checkout form is pressed.
$("#SubmitOrder").on("click", function () {
//store each individual entry into a separate variable.
var email = sessionStorage.getItem("loggedInUser");
var ccname = document.getElementById("ccName").value;
var ccnum = document.getElementById("ccNumber").value;
var month = document.getElementById("month").value;
var year = document.getElementById("year").value;
var cvc = document.getElementById("cvc").value;
//create an array with the details in.
var checkout = {
email: email,
ccname: ccname,
ccnum: ccnum,
month: month,
cvc: cvc,
}
//direct the user to the login page and alert them that their registration was successful.
alert("Your order was successful.")
window.location.href = "../index.html"
//posts the JSON object to the php file so it can fill the database, and converts the checkout array into JSON so it can be read.
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout))
})
})
First off, you're displaying the success message before even trying to send the post request to your PHP file. So your first job is to re-order things
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout));
alert("Your order was successful.");
window.location.href = "../index.html";
Secondly, you're currently not checking for a response from the server as to whether the request was successful or not. I've modified the example from the jQuery docs https://api.jquery.com/jquery.post/
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout))
.done(function() {
alert("Your order was successful.");
window.location.href = "../index.html";
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
Once you're done with that, you'll want to look into returning a response from PHP to say whether the query worked etc, but the above is at least enough to get you something that works for now :)
Currently I' am setting up a email verification system for my personal site. I (try) to handle this with jQuery and AJAX (code follows). But the problem is that it does not return to the echo 2; in my signup.inc.php so that I can continue working in the AJAX call.
As I understand it the compiler should return to/continue from the point where it was redirected, in this case the send_ver_email($user_email) below and echo 2. What did I get wrong? This is pretty new to me and I don't have so much experience , but I don't not what else to try. Tried moving and merging documents, but nothing works.
The AJAX call in JS:
$.ajax({
type: 'POST',
url: 'include/signup.inc.php',
data: 'user_name=' + user_name +
'&user_email=' + user_email +
'&user_pw=' + user_pw,
dataType: 'html',
success: function (data) {
if (data == 0) { // invalid email
... do something
} else if (data == 1) { // account already exists
... do something
} else if (data == 2) {
**This is where it should land after the successful sign up**
return false;
}
}
});
signup.inc.php works great and stores the data in database, so this is not the problem:
include_once "dbc.inc.php";
include_once "verification.inc.php";
if (isset($_POST)) {
//get posted data;
//select $statement
// error handlers
if (filter_var($user_email, FILTER_VALIDATE_EMAIL) === false) {
echo 0;
exit();
} else if ($statement->rowCount() > 0) {
echo 1;
exit();
} else {
// db entry (works great no problems there)
send_ver_email($user_email);
echo 2;
exit();
}
}
the AJAX receives the 2 and reacts as intended if send_ver_email($user_email) is disabled, so I'am very sure that it has something to do with the structure or the way send() handles things. This function is included in verification.inc.php which includes the whole PHPMailer package. And the Email works too! I get every single mail
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
include_once "../PHPMailer/src/Exception.php";
include_once "../PHPMailer/src/PHPMailer.php";
include_once "../PHPMailer/src/SMTP.php";
function generate_ver_code() {
// ...
}
function send_ver_email ($user_mail) {
$verCode = generate_ver_code();
$mail = new PHPMailer;
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = '.......';
$mail->Password = '........';
$mail->setFrom('........', '.......');
$mail->addAddress('.........', '..........');
$mail->Subject = '...........';
$mail->Body = "......................";
$mail->isHTML(true);
$mail->AltBody = '.........';
$mail->send()
}
I am also very grateful for tips about code style and layout :)
EDIT 1: A different approach:
if($mail->send()) {
echo 2;
exit();
} else {
// some error handling
}
This does not crash, I logged everywhere around it, but the ajax still does not register the echo 2
And another try showed:
if($mail->send()) {
} else {
// some error handling
}
and in signup.inc.php:
send_ver_email($user_email);
--------LOGGED HERE---------
echo 2;
exit();
}
This works fine too... this weirds me out the most. Either I got a really dumb typo somewhere or another newbie mistake (hopefully) or ajax handles this echo calls in a very confusing way.
dataType - delete this one.
Add console.log and open console in Your browser
success: function (data) {
console.log( data );
show Your console, and then You will see why. Maybe an unwanted char or php error
Second thing - there should be if stament like this (I supposed)
if (data == "1") // it is returning string, not integer.
You can also try to use switch case in success.
I have this (soon-to-be, hopefully) ABM application running on XAMPP.
I've already dealt with its validations and the query for the insert.
I have a file for registering subjects, in an html form, with a button type="submit".
So, when the options are selected and the input filled, when pressing the button a function is called (in a javascript file) --> it validates the data and sends a request to put the info in a database. Here's the js file:
function registerSubjects(){
var carreraMateria = "";
var nombreMateria = "";
var descripcionMateria = "";
var cargaHorariaMateria = "";
if(validacionFormularioAlta()){ //this is the main validating function
$.ajax({
url: 'http://localhost/path/registerSubjects.php',
type: "POST",
data: {"carreraMateria": carreraMateria,
"nombreMateria": nombreMateria,
"descripcionMateria": descripcionMateria,
"cargaHorariaMateria": cargaHorariaMateria,
},
dataType: "html",
beforeSend: function() {
console.log("I'm in before send part");
},
success: function(data) {
if( data == "OK"){
console.log("it saved the data");
location.href = "http://localhost/path/main.php";
return;
}
//Note: There are better ways, this is just because I'm learning, will try to improve on it later :)
if( data == "ERROR"){
console.log("not saved");
alert("error, please try again");
return;
}
alert("Server message: " + data);
}
});
}else{
alert("Incorrect inputs");
}
}
Data from the form is "caught" using these variables (javascript file):
carreraMateria = document.getElementById("carreraMateria").selectedIndex;
nombreMateria = document.getElementById("nombreMateria").value;
descripcionMateria = document.getElementById("descripcionMateria").value;
cargaHorariaMateriaElemento = document.getElementById("cargaHorariaMateria");
cargaHorariaMateriaSeleccion = document.getElementById("cargaHorariaMateria").selectedIndex;
cargaHorariaMateria = parseInt(document.getElementById("cargaHorariaMateria").value);
And..... this is the registerSubjects.php which deals with some server-side validations and the INSERT:
<?php
//Connection data
include("../extras/conexion.php");
//Inicialization of variables
$carreraMateria = "";
$nombreMateria = "";
$descripcionMateria = "";
$cargaHorariaMateria = "";
//Getting data
$carreraMateria = $_POST['carreraMateria'];
$nombreMateria = $_POST['nombreMateria'];
$descripcionMateria = $_POST['descripcionMateria'];
$cargaHorariaMateria = $_POST['cargaHorariaMateria'];
//CONNECTION
$CONN = new mysqli($serverName, $username, $password, $dataBase);
// Verifico la conexion
if ($CONN->connect_error) {
die("Problema al conectar con la base de datos" . $CONN->connect_error);
return;
}
//INSERT!
//Query para introducir los datos en la base
$SQL = "INSERT INTO subjects(career_id, name, description, hours) VALUES (?, ?, ?, ? )";
if($stmt = $CONN->prepare($SQL))
$stmt->bind_param('ssss', $carreraMateria, $nombreMateria, $descripcionMateria, $cargaHorariaMateria);
$stmt->execute();
$id = $stmt->affected_rows;
$stmt->close();
}
//Check for row modification
if($id>0 ){
echo "OK";
}else{
echo "ERROR";
}
return;
?>
And so it is... I had the connection part and its checking in a different file, but was causing some problems. I've written that in the files themeselves and now the ajax is working "fine"... well, at least is working :/
The thing is... I can't insert anything... I'm stuck in my own alert, in the part that says (in the AJAX part):
if( data == "ERROR"){
console.log("not saved");
alert("error, please try again");
return;
}
Can't seem to be realizing what's wrong. At first I wasn't "catching" the values in the JS file correctly, I've fixed that, but now I can't have the INSERT working right.
Apparently I'm getting the values right (from the form, from what was selected), and I'm referencing them well, so I'm pretty confused.
EDIT1:
I've tried getting the values received in the php file; I've done this:
$carreraMateria = $_POST['carreraMateria'];
var_dump($_POST["carreraMateria"]);
$nombreMateria = $_POST['nombreMateria'];
var_dump($_POST["nombreMateria"]);
$descripcionMateria = $_POST['descripcionMateria'];
var_dump($_POST["descripcionMateria"]);
$cargaHorariaMateria = $_POST['cargaHorariaMateria'];
var_dump($_POST["cargaHorariaMateria"]);
And the result was:
string(0) ""
string(0) ""
string(0) ""
string(0) ""
Then I GUESS I'm not getting the data correctly...? :/
EDIT2:
I've disabled the PHP and AJAX parts, and was just testing the JavaScript. I've "caught" the values and printed them into console log, and they show fine, so now the problem is with transferring them into the PHP file to insert them into the database.
if($stmt = $CONN->prepare($SQL)) {
$stmt->bind_param('ssss', $carreraMateria, $nombreMateria, $descripcionMateria, $cargaHorariaMateria);
$stmt->execute();
$stmt->execute();
$id = $stmt->affected_rows;
$stmt->close();
}
there was a missing open bracked
This is functioning now :)
In the javascript file, I had declared the variables meant for initialization inside the function registerSubjects(), and so they were empty when trying to pass them. They had to be declared as global variables, outside the function.
I have a problem with redirection, my whole code is working my only problem is losing a POST/SESSION data in the process. spent countless hours working with it and try alot of work arounds, but still it does not work and that is my only problem. here's my code
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This variable will be used to re-display the user's username to them in the
// login form if they fail to enter the correct password. It is initialized here
// to an empty value, which will be shown if the user has not submitted the form.
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST)) {
// This query retreives the user's information from the database using
// their username.
if(isset($_POST['validEmail'])) {
$query = "SELECT *
FROM registered_email
WHERE email = :validEmail";
}
// The parameter values
$query_params = array( ':validEmail' => $_POST['validEmail'] );
try {
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query");
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the username
// they entered is not registered.
$row = $stmt->fetch();
if($row) {
if($_POST['validEmail'] === $row['email']) {
// If they do, then we flip this to true
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok) {
$_SESSION['sesEmail'] = $row;
// Redirect the user to the private members-only page.
if (isset($_POST['validEmail'])) {
echo "<script>location='http://www.url.com.ph/some.php'</script>";
}
} else {
// Tell the user they failed
print "Sorry to say that your Email is not Registered!.";
}
}
Ideally your code should look something like this, it should work fine as far as I see. I refactored your code and edited the redirect statement.
// I am assuming you have session_start(); included in common.php
require("common.php");
if(!empty($_POST)) {
if(isset($_POST['validEmail'])) {
$query = "SELECT *
FROM registered_email
WHERE email = :validEmail";
$query_params = array( ':validEmail' => $_POST['validEmail'] );
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
die("Failed to run query");
}
$login_ok = false;
$row = $stmt->fetch();
if($row) {
if($_POST['validEmail'] === $row['email']) {
$login_ok = true;
}
}
if($login_ok) {
$_SESSION['sesEmail'] = $row;
if (isset($_POST['validEmail'])) {
// the page where you are redirecting should be linked with session as well
echo "<script>window.location.href='http://www.url.com.ph/some.php'</script>";
}
} else {
// Tell the user they failed
print "Sorry to say that your Email is not Registered!.";
}
}
else {
// Tell the user they failed
print "Sorry no POST parameters!.";
}
}
Hope it helps. If not feel free to discuss.
I am trying to use ajax to add a div to display an error message. But instead of the correct error message I get null every time. The null is a result of
<?php echo json_encode($_SESSION['msg']['login-err']); ?>;
How can I fix this? Why is it showing as null?
JavaScript:
$(document).ready(function(){
$("#open").click(function(){
$("#register").fadeIn(500);
});
$("#close").click(function(){
$("#register").fadeOut(500);
});
$("#log").click(function(){
username=$("#username").val();
password=$("#password").val();
submit=$("#log").val();
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(html) {
if(html==true) {
}
else {
$("#error-log").remove();
var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
<?php unset($_SESSION['msg']['login-err']); ?>
}
}
});
return false;
});
members.php:
<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('Login');
// Starting the session
session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week
session_start();
if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: ../../index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('FRCteam3482Remember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}
Normally a AJAX request makes a request to a PHP page which returns a value. It is often JSON but does not have to be. Here is an example.
$.ajax({
type: "POST",
url: "a request URL",
data:{
'POST1':var1,
'POST2':var2
}
success: function(result)
{
//Do something based on result. If result is empty. You have a problem.
}
});
Your PHP page doesn't always return a value so its hard to know whats going on. Your work-around for this is to use javascript variables wich hold echoed PHP data when your page returns empty. But this won't work in your case. Echoing PHP variables into javascript might work fine on occasion to but it is not good practise.
It won't work in your case because your javascript variables are set when the page is first loaded. At this point the variable $_SESSION['msg']['login-err'] has not been set (or might hold some irrelevant data) and this is what your javascript variables will also hold.
When you do it the way I mentioned you can also use functions like console.log(result) or alert(result) to manually look at the result of the PHP page and fix any problems.
I would suggest doing something like the following.
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
echo $_SESSION['msg']['login-err'];
}
else
echo 'success';
}
Javascript
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(response) {
if(response=='success') {
alert("Woo! everything went well. What happens now?");
//do some stuff
}
else {
alert("oh no, looks like we ran into some problems. Response is"+ response);
$("#error-log").remove();
var error_msg = response;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
}
}
});
This may not necessarily work exactly as you intended but its a good start for you to build on.
By going through the code , it seems that you are doing redirect first then sending the response.
There is something wrong in below code snippet
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}