I have a form forgot password that confirms if the user exists and send a email with a link for password reset, it works fine but i do like that message "email was been sent..." should appear in a popup instead on the same page.
I tried this but does not works:
response.php
var useremail = document.getElementById("email").value();
$.get( "validation.php?email=" function( response ) {
// console.log( response ); // server response
response = response.trim();
if(response == 1){
alert("Email sent....");
} else{
alert(response);
return false;
}
});
}`
Form:
<form class="register" id="email" action="forgot.php" method="post" onSubmit="checkAll();">
mysql
if ($result=="") { $result = "Email has been sent"; }
echo "<div>$result</div>";
}
?>```
I have sorted all and now it works i let here the solution in a hope that can helps someone else:
function alert(){
echo "<script type='text/javascript'>";
echo "alert('Email has been sent - Please click on the link in the email to confirm.');";
echo "</script>";
}
if ($result=="") { $result = alert(); }
}
?>
Related
I tried questions showing up before asking a question didnt have chance to make it work.
it works fine when I add it to mail send success alert, But I dont want to add script in php part.
I am trying to redirect contact page to an another page after form
success and delay a few seconds.
Here is my Jquery ajax :
$(document).ready(function(){
$('#ContactForm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"modules/contact.inc.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html(data.error);
setTimeout(function() {
window.location = 'index.php';
}, 1000);
} else {
$('#result').html(data.error);
$('#ContactForm')[0].reset();
}
}
});
});
});
I tried the folowing setTimeout(); in success function but didnt work:
setTimeout(function() {
window.location.replace("index.php");
},1000);
Then I tried : window.location.replace("index.php"); without setTimeout function didnt work too.
window.location.href
window.location.hostname
window.location
This one works for modal in another page
setTimeout(function() {
window.location.reload();
}, 3000);
These are my tries didnt have a chance, Thanks for any advice and help.
EDIT: Here is php part for data.error contain:
$error = "";
// Validate user name
if(empty($_POST["fname"])){
$error .= "<p class='error'>İsim girmediniz.</p>";
} else {
$name = test_input($_POST["fname"]);
}
// Validate email address
if(empty($_POST["email"])){
$error .= "<p class='error'>E-Posta girmediniz.</p>";
} else{
$email = $_POST["email"];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error .= "<p class='error'>E-Posta doğru formatta değil.</p>";
}
}
// Validate user subject
if(empty($_POST["subject"])){
$error .= "<p class='error'>Konu girmediniz.</p>";
} else {
$subject = test_input($_POST["subject"]);
}
// Validate user message
if(empty($_POST["message"])){
$error .= "<p class='error'>Mesaj girmediniz.</p>";
} else {
$message = test_input($_POST["message"]);
}
// Validate user departman
if(empty($_POST["departmant"])){
$error .= "<p class='error'>departman Seçin.</p>";
} else {
$departman = test_input($_POST["departmant"]);
}
if($error === ''){
require "../PHPMailer/mailer.php";
$mail = new mailSend();
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$name = test_input($_POST["fname"]);
$subject = test_input($_POST["subject"]);
$departman = test_input($_POST["departmant"]);
$message = test_input($_POST["message"]);
$error = $mail->sendMail($email,$name,$subject,$departman,$message);
}else{
$error .= "<p class='error'>Formda bir hata oluştu.</p>";
}
$data = array(
'error' => $error
);
echo json_encode($data);
EDIT : Got it work thanks for answers,
Displaying error causing the problem, $('#result').html(data.error); I changed it to text message instead of success message from php:
$('#result').html('Form successfuly');
$('#ContactForm')[0].reset();
setTimeout(function() {
window.location = 'index.php';
}, 1000);
it works fine.
String.replace() requires two parameters. As written, it will look for the string "index.php" and replace it with nothing. Try adding a regex to match everything and replace with your new URL.
setTimeout(function() {
window.location.replace( /.*/, "index.php");
},1000);
Use the full URL (i.e. https://yourdomain.com/index.php) or write a better regex. For instance, if your domain ends with .com, you could do something like:
setTimeout(function() {
window.location.replace( /\.com\/.*/, ".com/index.php");
},1000);
The code is for simple login validation.
The PHP script doesnt seem to run when returning values to JavaScript but runs fine when there are not variables to return.
So is there anything wrong or do I need to add anything else to return the values from PHP.
<?php
header('Content-type: application/json; charset=utf-8');
include("config.php");
$formd=array();
//Fetching Values from URL
$username2=$_POST['username1'];
$password2=$_POST['password1'];
$query = mysqli_query($db,"SELECT username FROM login WHERE username = '$username2'");
$result=mysqli_fetch_assoc($query);
$sql=mysqli_query($db,"SELECT password FROM login WHERE username = '$username2'");
$resul=mysqli_fetch_assoc($sql);
$row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$count = mysqli_num_rows($query);
$pass=$resul['password'];
if((password_verify($password2,$pass))and($count==1)) {
echo "ds";
} else {
echo "no";
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit();
?>
JavaScript
<script>
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ username + '&password1='+ password;
if(username==''||password=='') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
dataType: "json",
data: dataString,
success: function(data){
alert(data.no);
}
});
}
return false;
});
});
</script>
your Php code has 2 echo statements
if((password_verify($password2,$pass))and($count==1))
{
echo "ds"; // first
}
else
{
echo "no"; // first
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd); // second
This way, your php script returns malformed JSON data and hence $.ajax() cannot handle it.
Also, as others pointed out, please use the developer console to verify your script returns the expected data.
The if else part of your php script has an echo statement and then outside the if else you echo the array $formd. This malforms the JSON response. Also, you should use exit(1) as there is no exception being raised in your code.
Here the snippet you should use to get the script working.
if((password_verify($password2,$pass))and($count==1))
{
echo "ds";
}
else
{
// echo "no"; this is not required
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit(1);
I am new in HTML and PHP, I have created a contact form for the users where they can add their messages. When they click on the send button I want the page to stay on this contact form and show a text message below that says it is succesfully sent. Here is my code some of it .
if (isset($_POST['submit']))
{
if (!isset($_POST['name'])) {
echo "please enter the name";
}else {
if (!isset($_POST["emailaddress"])) {
echo "please enter the email adresse ";
}else {
if (!isset($_POST["subject"])) {
echo " Please enter the message ";
} else {
$nom = $_POST['name'];
$email = $_POST['emailaddress'];
$msg = $_POST['subject'];
$sql = "INSERT INTO contacts (name, email, message) VALUES ('$nom', '$email', '$msg') ";
if (!mysql_query($sql)){
die ('error : ' . mysql_error());
} else {
mysql_close($link);
?>
</br></br>
<p25><center>sent succesfully! thanks</center></p25>s
<?php
echo "<script>setTimeout(\"location.href = 'no-sidebar.php'\",8000);</script>";
You need to understand each line of code.
if (!isset($_POST['name'])) {
echo "please enter the name";
}
The page will get reloaded on the first instance.
You need to do the form validation part in javascript. In this way, if some validation error happens, it can be displayed somewhere in the page without reloading it.
Then send the data to php through ajax, where you set your model and pass it to database and send a response back to javascript which can then print the message that the form has been submitted successfully.
Here's what I'm saying:
<input type="text" id="email" />
<button id="submit">Submit</button>
<div id="status"></div>
Javascript Part:
$(document).ready(function(){
$('#submit').on('click', function(){
var email = $('#email').val();
if(email.trim().length === 0){
$('#status').html('Email not provided');
}else{
$.ajax({
type : 'POST',
data : {action: 'sendData' , email : email}, // object
url : 'example.php',
cache: false,
success: function(response){
$('#status').html(response);
}
});
}
});
});
And in the php side, then you can just get the value which is already validated and return true or false based on your data insertion result to database.
example.php
<?php
if(isset($_POST['action']) && $_POST['action'] == 'sendData'){
$email = $_POST['email'];
if(dbinsertion successful){
echo "Success";
}else{
echo "Something went wrong";
}
}
?>
You have to use jquery here. Hope you understood.
I do have two kind of echo in my ajax processing script. One for error messages and other one for form processing success.
This is how its look.
if (strlen($password) != 128) {
$errorMsg = "<div class='alert alert-danger alert-dismissible' role='alert'>\n";
$errorMsg .= "<strong>Oops!</strong> System error, Invalid password configuration.\n";
$errorMsg .= "</div>\n";
echo $errorMsg;
}
And other one is
// Print a message based upon the result:
if ($stmt->affected_rows == 1) {
// Print a message and wrap up:
$successMsg = "<div class='alert alert-success alert-dismissible' role='alert'>\n";
$successMsg .= "Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the 'Password Modification' link.\n";
$successMsg .= "</div>\n";
echo $successMsg;
}
So, I am using one DIV to populate these message upon the ajax success.
My question is, is there a way to identify which message is displaying with ajax success?
Hope somebody may help me out.
Thank you.
You can use filter() to see if the response has the class of .alert-danger:
// $.ajax({ ...
success: function(html) {
var $html = $(html);
if ($html.filter('.alert-danger').length) {
// something went wrong
}
else {
// it worked
}
}
Note however, that a better pattern to use would be to return JSON containing the message to display, along with the class of the alert and a flag to indicate its state. Something like this:
var $arr;
if (strlen($password) != 128) {
$arr = array('success'=>false,'cssClass'=>'alert-danger','message'=>'Oops! System error, Invalid password configuration.');
}
if ($stmt->affected_rows == 1) {
$arr = array('success'=>true,'cssClass'=>'alert-success','message'=>'Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the Password Modification link.');
}
echo json_encode($arr);
// $.ajax({ ...
success: function(json) {
if (json.success) {
// it worked
}
else {
// something went wrong
}
// append the alert
$('#myElement').append('<div class="alert alert-dismissible + ' + json.cssClass + '" role="alert">' + json.message + '</div>');
}
I'm having an issue with an contact form everything works except it will not show the success message after the form is added to the db.
The process script
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'db.php';
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$phone = stripslashes($_POST['phone']);
$device = stripslashes($_POST['device']);
$model = stripslashes($_POST['model']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.<br />';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.<br />';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.<br />';
}
// Check phone number
if(!$phone)
{
$error .= 'Please enter your phone number.<br />';
}
// Check device
if(!$device)
{
$error .= 'Please enter your device manufacturer.<br />';
}
// Check device model
if(!$model)
{
$error .= 'Please enter your device model.<br />';
}
// Check message (length)
if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15 characters.<br />";
}
// Get current time stampe
$date = time();
if(!$error)
{
$addDB = "INSERT INTO contactus (`name`,`email`,`phone`,`device`,`model`,`subject`,`message`, `date`, `read`) VALUES ('$name','$email','$phone','$device','$model','$subject','$message','$date', '')";
$result = mysqli_query($con,$addDB) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error(), E_USER_ERROR);
echo 'OK';
} else {
echo '<div class="notification_error">'.$error.'</div>';
}
}
And here is the jQuery part
<script type="text/javascript">
$(document).ready(function ()
{ // after loading the DOM
$("#ajax-contacts").submit(function ()
{
// this points to our form
var str = $(this).serialize(); // Serialize the data for the POST-request
$.ajax(
{
type: "POST",
url: 'includes/contact-process.php',
data: str,
success: function (msg)
{
$("#note").ajaxComplete(function (event, request, settings)
{
if (msg == 'OK')
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
return false;
});
});
</script>
Thanks any help is gladly appreciated.
Drop this line:
$("#note").ajaxComplete(function (event, request, settings)
You don't need it as you are already in the success: function.
For debugging purpose you can try to put in an alert("Test"); just above that troublesome line to check if it is displayed.
Note that the success callbacks have been deprecated and you should instead use .done. See the jQuery API for more info:
You could also try and do some debugging yourself. E.g. Chrome has some really good developer tools where you can see a lot of stuff and you can even setup breakpoints and walk through your code step-by-step. Very useful.
Hit F12 to show Developer Tools.
Go in to Settings:
Enable logging of XHR/Ajax requests:
When doing Ajax requests hereafter it will be logged in the console:
Just rightclick on that Ajax request to trigger a new identical request. In this way you can see exactly what the browser sends and what your PHP script receives. Of course the request needs to be GET for you to debug the variables being passed.