Trying to get together the sign up validation with PHP and Ajax. Not sure what is wrong but the submission does not happen. If I don't add the validation part everything looks fine and i am able to insert the data to mysql.
<script type="application/javascript">
$("#submit").submit(function (event) {
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "signupregister.php",
type: "POST",
data: datatopost,
success: function (data) {
if (data) {
$("#signupmessage".html(data));
}
},
error: function () {
$("#signupmessage").html("<div class = 'alert alert-danger'></div>")
}
});
});
</script>
_
<?php
session_start();
include('mysqlconnection.php');
include('index.php');
function customError($errors, $errorslevel)
{
}
set_error_handler("customError", E_ALL);
if (isset($_POST['submit'])) {
if ($_POST($first_name) == "") {
$errors .= $first_nameError;
} else {
$first_name =
filter_var($_POST["first_name"], FILTER_SANITIZE_STRING);
}
}
if ($errors) {
$resultMessage = '<div class="alert alert-danger">' .
$errors . '</div>';
echo $resultMessage;
exit;
}
$first_nameError = '<p>first name required</p>';
First up, in your validation PHP script, you won't need to include 'index.php'
Try redirecting the form to an empty page where you only include your validation data, while setting a session variable for the first error encountered.
At the end of your validation, if your error variable contains an error, you can redirect to the form and display your said error at a convenient location. Keep in mind you will have to save form data in session variables if you want to preserve all user input (thus removing the hassle of refilling the form over and over again).
If it doesn't, you can proceed to insert the data in your db then redirect to your desired landing page.
Here's a sample code based on your input:
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['fname'] = $_POST['fname'];
//so on for your other variables
if($_SESSION['fname'] == ""){
$_SESSION['err'] = "First Name Required";
}
if(//insert your format validation for first name){
$_SESSION['err'] = "First Name Invalid";}
}
//end of validation
if isset($_SESSION['err']){
header('Location: myform.php');
}
else{
//save all your variables into normal ones, i.e $fname-$_POST['fname'];
//insert into database;
//check correct insertion;
//redirect to landing page;
}
}
?>
Related
I don't know what I'm missing. I'm trying to load data from database into the navbar. Navbar should have different links for administrators, signed users and other users. Since I didn't make page for sign in and sign up yet, I assumed that the code from page showMenu.php called with AJAX will take last function loaded from functions.php which is a query for not signed in users. But instead of getting data back from the database to write with JS, the code fall into error property of AJAX call and in addition to that displays server error 500 for showMenu.php page. I checked all the paths for both main.js and php pages and names of tables and columns in database and everything is correct. And just for the record, connection.php includes fetch mode, so columns of tables can be accessed with ->. What do I'm missing.
js code
getViaAjax("showMenu",showMenu);
function getViaAjax(fileName, specificFunction) {
$.ajax({
url: "models/" + fileName + ".php",
method: "get",
dataType: "json",
success: function(jsonData){
specificFunction(jsonData);
},
error: function(xhr){
console.error(xhr);
}
});
}
function showMenu(menuJsonData){
let writingMenu = "";
menuJsonData.forEach(partOfMenu=>{
writingMenu+=`<li id="${partOfMenu.id}" class="nav-item">
<a class="nav-link" href="${partOfMenu.href}">${partOfMenu.label}</a>
</li>`;
});
document.getElementById("menu").innerHTML=writingMenu;
}
showMenu.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'GET'){
include "../config/connection.php";
include "functions.php";
try{
if(isset($_SESSION['user'])){
$user = $_SESSION['user'];
if($user->roleId==1){
$jsonMenu = showMenuForAdmin();
}
else {
$jsonMenu = showMenuForSignedInUser();
}
}
else{
$jsonMenu = showMenuForNonSignedInUser();
}
echo json_encode($jsonMenu);
http_response_code(200);
}
catch(PDOException $exception){
http_response_code(500);
}
}
else{
http_response_code(404);
}
?>
function from functions.php I want to be triggered when user not registered or signed
function showMenuForNonSignedInUser(){
global $connection;
$query = "SELECT id, href, label WHERE id NOT LIKE 6;";
$data = $connection->query($query)->fetchAll();
return $data;
}
Im trying to fix this issue im having. The problem is that I use this code when someone want to sign in to the admin panel:
<script>
function myFunction() {
//alert('you can type now, end with enter');
$("#test").focus();
}
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
// alert($("#test").val());
var email = $("#test").val();
if(email==''){
// alert("Error.");
sweetAlert("Oops...", "Error!", "error");
} else {
$.post("sess.php",{ code1: code},
function(data) {
// alert(data);
// swal(data);
if((data)=="1") {
swal("Welcome!", "Please wait!", "success")
} else {
sweetAlert("Oops...", "Something went wrong.", "error");
}
$('#form')[0].reset(); //To reset form fields
});
}
});
});
</script>
Sess.php looks like this:
<?php
include("conn.php");
?>
<?php
include("ipcheck.php");
$code2=htmlEntities($_POST['code1'], ENT_QUOTES);
$info = explode("-", $code2);
$username = $info[0];
$password = $info[1];
$_POST = db_escape($_POST);
$sql = "SELECT id FROM adminusers
WHERE user='{$username}'
AND pass='$password'";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0){
echo "2";
exit;
}
// Session for user
$_SESSION['sess_id'] = mysql_result($result, 0, 'id');
$_SESSION['sess_user'] = $username;
// DAtabse going on here.
echo "1";
exit;
?>
So if the username and password is correct the login is successful and those session is set in sess.php:
$_SESSION['sess_id'] = mysql_result($result, 0, 'id');
$_SESSION['sess_user'] = $username;
My problem is, how do I get the sessions that is set for the user thru sess.php back to index.php using javascript so I can set the sessions in index.php not in sess.php?
why to you care to pass the session to javascript ? I mean if you set the session server side on sess.php you have already setted it even in index.php (session exists during the entire ... session :-) ) so when sess.php return that the authentication is correct, your javascript should just move the page to index.php like:
window.location.href = 'index.php';
in index.php, if you print the session print_r($_SESSION) you should see the values that you have previously set in sess.php
If your $_SESSION is empty in index.php probably you have to start the session before reading $_SESSION using session_start();
Alright so here's the situation. I have the following code block in my php file, and for some reason, whenever it comes to check data, it doesn't accept. I've printed out the value of data, and it is indeed "accepted" (without quotes obviously). Am I comparing these wrong somehow? Running basically the exact same code in another section of my website and it works fine.
$(document).ready(function () {
$("#sign").click(function () {
jQuery.ajax({
url: "loginConfirm.php",
data: { // Correct
username: $("#username").val(),
password: $("#password").val()
},
type: "POST",
success: function (data) {
if ($("#username").val() === "") {
//Do nothin
} else if (data === "accepted") {
alert("Here");
redirectSignIn();
} else {
alert("There");
$("#signInTitle").html(data);
}
},
error: function () {}
});
});
});
EDIT: php code I'm calling in the url below
<?php
// The global $_POST variable allows you to access the data sent with the POST method
// To access the data sent with the GET method, you can use $_GET
$username = htmlspecialchars($_POST['username']);
$userpassword = htmlspecialchars($_POST['password']);
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = mysql_query("SELECT count(*) FROM loginInfo WHERE userName='" . $username . "' AND password='" . $userpassword . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0)
echo "accepted";
else
echo "denied";
?>
You cant validate if ($("#username").val() === "") { in success function. For that you are suppose to validate it before making Ajax call.
I would like to give some advice here that first you have to validate the inputs of the user if validate then you can call ajax.
and then you not required to check the value of the username in AJAX process.
Like....
if($("#username").val() === "" && $("#passoword").val() === "")
{
//AJAX call
}
else
{
//alert to enter the valid inputs
}
hope you get it my concept...
I have used the following guide to ifugre out how to send emails with file uploading without refreshing the page: http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/ and it works fine, except that I'd like to be able to take a message from the php I use to upload the file and send the email, so that I can display that message to the user, on the page where they submitted the form from.
I have this code currently in my contact.php page:
if (!$sentMail) {
header('HTTP/1.1 500 Couldnot send mail! Sorry..');
exit();
} else {
echo '<h3>Hi ' . $postName . ', Thank you for your email</h3>
<p>Your email has already arrived in our Inbox, all We need to do is Check it.
<br />Good day.</p>';
}
The only problem is getting that message that I've echoed to show up where I'd like it to go. Any help would be greatly appreciated.
The PHP in the iFrame should post unique sessionID in the database with result.
In the meanwhile you can do an Ajax call to check the database if the mail is sent.
So we got 3 files
Your form (like index.html)
Your Mailer in iframe (like sendMail.php)
Your status checker (like getStatus.php)
Here we go..
Your IFRAME Mailer:
<?php
session_start();
$_SESSION['mailsender'] = mt_rand();
// this is ur iframe mailer
// here your mail send stuff .....
// if mail is sent
mysql_query("INSERT INTO mailsender (mailid, result) VALUES ('".$_SESSION['mailsender']."', 'successfull')");
// if mail fails
mysql_query("INSERT INTO mailsender (mailid, result) VALUES ('".$_SESSION['mailsender']."', 'failed')");
?>
getStatus.PHP :
<?php
session_start();
// check status and give JSON back
// getStatus.php - we be called from front-end
$query = mysql_query("SELECT * FROM mailsender WHERE mailid = '".$_SESSION['mailsender']."'");
$result = "Pending";
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_array($query)) {
$result = $rij['result'];
}
}
echo json_encode(array("result"=>$result));
?>
Your Front-end like Index.html:
<!DOCTYPE html>
<html>
<!-- include jQuery -->
<script>
$(document).ready(function(){
checkMailStatus = function() {
$.ajax({
url: 'getStatus.php',
dataType: 'JSON',
success: function(data) {
if (data['result'] == "successfull") {
// do successfull stuff here
// also clear the interval
}
if (data['result'] == "failed") {
// do failed stuff here
}
if (data['result'] == "pending") {
// still trying to send
// do stuff here while sending (like loading.gif)
}
}
})
}
$(".sendmailbutton").click(function(){
setInterval(function(){
checkMailStatus();
}, 800)
})
})
</script>
</html>
Hi I have a PHP file with data. The value is passed on to another php file which process it successfully. But the first php file does not refresh to update the new result. It have to do it manually. Can any one tell me where I'm wrong or what needs to be done. Please find my code below.
PHP code (1st page, index.php)
function display_tasks_from_table() //Displayes existing tasks from table
{
$conn = open_database_connection();
$sql = 'SELECT id, name FROM todolist';
mysql_select_db('todolist'); //Choosing the db is paramount
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<form class='showexistingtasks' name='showexistingtasks' action='remove_task.php' method='post' >";
while($row = mysql_fetch_assoc($retval))
{
echo "<input class='checkbox' type='checkbox' name='checkboxes{$row['id']}' value='{$row['name']}' onclick='respToChkbox()' >{$row['name']} <img src='images/show_options.gif' /><br>";
}
echo "</form>";
echo "<label id='removeerrormsg'></label>";
close_database_connection($conn);
}
Javascript code which finds the selected value:
var selVal; //global variable
function respToChkbox()
{
var inputElements = document.getElementsByTagName('input'),
input_len = inputElements.length;
for (var i = 0; i<input_len; i++)
{
if (inputElements[i].checked === true)
{
selVal = inputElements[i].value;
}
}
}
jQuery code which passes value to another page (remove_Task.php):
$(document).ready(function() {
$(".checkbox").click(function(){
$.ajax({
type: "POST",
url: "remove_task.php", //This is the current doc
data: {sel:selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
//console.log(data);
}
});
});
});
PHP code (2nd page, remove_task.php);
session_start();
error_reporting(E_ALL);ini_set('display_errors', 'On');
$task_to_remove = $_POST['sel'];
function remove_from_list() //Removes a selected task from DB
{
$db_connection = open_database_connection();
global $task_to_remove;
mysql_select_db('todolist');
$sql = "DELETE FROM todolist WHERE name = "."'".$task_to_remove."'";
if($task_to_remove!='' || $task_to_remove!=null)
{
mysql_query($sql, $db_connection);
}
close_database_connection($db_connection);
header("Location: index.php");
}
if($task_to_remove != "") {
remove_from_list();
}
The selected value is getting deleted but the display on index.php is not updated automatically. I have to manually refresh to see the updated result. Any help would be appreciated.
By calling header("Location: index.php"); you don't redirect main page. You sent an ajax request - you can think about it as of opening a new page at the background, so this code redirects that page to index.php.
The better way to solve your task is to return status to your success function and remove items which were deleted from the database.
success: function(data){
if(data.success){
//remove deleted items
}
}