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>');
}
Related
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(); }
}
?>
I have the following code writing in ajax which sent a request to the back-end
$.ajax({
type: "POST",
url: action,
data: str,
success: function(msg) {
//alert(msg);
if (msg == 'sent') {
alert("success");
$('#errormessage').html('<div class="alert alert-success">Email sent successfully.</div>');
$('.contactForm').find("input, textarea").val("");
}else if (msg == 'saved') {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html('<div class="alert alert-warning">Email couldn\'t be sent but not too worry we got it in our database. We will get back to you.</div>');
$('.contactForm').find("input, textarea").val("");
}
else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
php code
$to_email = $set['Email'];
$headers = "From: ". $email;
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($email);
if ($secure_check == false) {
echo "Invalid input";
} else { //send email
$query = mysqli_query($mysqli,"INSERT INTO emails(name,email,subject,message)VALUES('$name','$email','$sub','$msg')");
$mail = mail($to_email,$sub,$msg,$headers);
if($query and $mail){
echo 'sent';
}else if($query and !$mail){
echo 'saved';
}else{
echo $mysqli->error;
}
}
If I send an email it successfully executed with the insertion. The issue I am facing is that ajax is not printing out the right message. It only execute the else part which displayed sent
This part of the code is not exected:
if (msg == 'sent') {
alert("success");
$('#errormessage').html('<div class="alert alert-success">Email sent successfully.
</div>');
$('.contactForm').find("input, textarea").val("");
}
instead, this is displayed with just sent message
else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
The issue is most likely because you're returning a text-based response and there is whitespace around the value so msg == 'sent' is never true.
To fix this you could simply call trim() to remove the whitespace:
if (msg.trim() == 'sent') {
// your code...
}
Alternatively you can change your PHP to return a serialised data structure, such as JSON or XML, to avoid this problem. I would suggest doing this.
I want to use my webpage to recognize if a $_POST is set and the, if it is, print it in the page, so this is what I really have now:
if (isset($_POST['error'])) {
echo '<div id="error">'.$_POST['error'].'</div>';
}
But what I want is that, when an if statement that I have in the same document returns true, to send a POST request to that same file and so, show the error message with the $_POST. Is this possible or it is another easy way for doing it?
Sorry for not explaining so well, this is my code:
if (password_verify($_POST['oldpassword'], $result['password'])) {
// Upload password to database
} else {
// Set the $_POST['error'] to an error message so I can show it in the error DIV.
}
Thanks!
You can define a $message athe beginning of your page then handle the errors you want to show
$message = '';
if (password_verify($_POST['oldpassword'], $result['password'])) {
// Upload password to database
} else {
//set a proper message ID which will be handled in your DIV
$message_id = 1;
header('location: /current_path.php?message='.$message_id);
}
Now in the div you can show it as
if (!empty($_GET['message'])) {
echo '<div id="error">';
if ($_GET['message'] == 1) { echo 'First message to show.'; }
elseif ($_GET['message'] == 2) { echo 'Second message to show.'; }
echo '</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.
I have successfully implemented the Jquery Validation Plugin http://posabsolute.github.com/jQuery-Validation-Engine/ but i am now trying to get an ajax database email check to work (email exists / email available) and i have written some php script to get this done. Its kinda working but i am getting the most unexpected heretically odd behavior from my IF ELSE statement (seems really crazy to me). observe ### marked comments
PHP code: LOOK AT THE IF ELSE STATEMENT
/* RECEIVE VALUE */
$validateValue = $_REQUEST['fieldValue'];
$validateId = $_REQUEST['fieldId'];
$validateError = "This username is already taken";
$validateSuccess = "This username is available";
/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results = array($row['Email']);
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR ### popup shows "validating, please wait" then "This username is already taken" when email typed is in database - i.e. Working
file_put_contents('output.txt', print_r("1 in array - Email is Taken " . $validateValue, true)); ### this runs!!
}else{
$arrayToJs[1] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success ### popup shows "validating, please wait" when email typed is NOT in the database - i.e. not Working
file_put_contents('output.txt', print_r("2 else - Email is available " . $validateValue, true));
//### THIS RUNS TOO !!!!!!!!!!!!! i.e. echo json_encode($arrayToJs) wont work for both.. If I change (in_array()) to (!in_array()) i get the reverse when email is in database.
//i.e. only the else statements echo json_encode($arrayToJs) runs and the popup msg shows up green "This username is available" crazy right???
//so basically IF ELSE statements run as expected (confirmed by output.txt) but only one echo json_encode($arrayToJs) will work.!!!!
//If i remove the json_encode($arrayToJs) statements and place it once after the IF ELSE statement i get the same problem.
//both $arrayToJs[1] = false; and $arrayToJs[1] = true; can work separately depending on which is first run IF or ELSE but they will not work in the one after another;
}
HERE IS THE REST OF THE CODE-->
1-HTML FORM INPUT CODE:
<tr>
<td> <Label>Business Email</Label>
<br>
<input type="text" name="Email" id="Email" class="validate[required,custom[email],ajax[ajaxUserCallPhp]] text-input">
</td>
</tr>
2-Relevant JQUERY code in jquery.validationEngine.js:
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
3-Relevent code for ajaxUserCallPhp in jquery.validationEngine-en.js:
"ajaxUserCallPhp": {
"url": "validation/php/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "*Validating, please wait"
},
Im sure the problem lies with this echo.
echo json_encode($arrayToJs)
Please help i've spent to long on this and its almost working fully.
To clarify - I basically am trying to code it so that if i type an email in the db it shows red "This username is taken" then if i edit the input box to an email not in the database it changes to green "username is available" at the moment only one json_encode will run in any scenario no matter how i change the if else statement –
Thank you very much in advance.
Ok got it finally after a fiddle. I found that json_encode() returns false when any error or warning is posted. using the php error log file in xampp/php/logs/error_logs file i realised that i was getting an error only when the query result was null making $results = null. this caused an output error preventing json_encode() from echoing true, which is why i only got one response.
To fix it i made sure that the $result array was not empty by using the following code after the query to array part.
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
The whole code is now
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = $row['Email'];
}
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = 0;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
} else {
$arrayToJs[1] = 1; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
}
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})