I'm trying to use a Javascript/AJAX function that send an email (using a PHP page).
The function is:
new Request({
method: "post",
data: this,
onRequest: function() {
$('amCallMeBackForm').empty().addClass('amCallMeBackWait');
$('callback').setStyle('background', 'url(\'http://www.mysite.it/modules/mod_amcallmeback/assets/sfondo_callback.png\') no-repeat transparent');
$('callback').setStyle('height', '73px');
},
onComplete: function(response) {
$('amCallMeBackForm').removeClass('amCallMeBackWait');
$('amCallMeBackForm').addClass('amCallMeBackSent');
alert(response);
}
}).send();
});
It works fine, but i cannot manage the response from PHP page, where i've this code:
<?php
class modAmCallMeBackHelper
{
function send($params) {
// Check for request forgeries
JRequest::checkToken() or die( 'Invalid Token' );
// get data
$name = JRequest::getVar('name', '');
$rif = JRequest::getVar('rif', '');
$phone = JRequest::getVar('phone', '');
$uri = JRequest::getVar('uri', '');
// get module params
$subject = $params->get('mail_subject');
$reciptient = explode(',', $params->get('receipt_email'));
$app = JFactory::getApplication();
$sender = array($app->getCfg('mailfrom'), $app->getCfg('fromname'));
// make email
$Body = '<strong>Azienda:</strong> '.$name."<br />";
$Body .= '<strong>Riferimento:</strong> '.$rif."<br />";
$Body .= '<strong>Numero di telefono:</strong> '.$phone."<br />";
$Body .= '<strong>Pagina da cui รจ stato richiesto il contatto:</strong> <a href='.$uri.'>'.$uri."</a>";
$mailer =& JFactory::getMailer();
$mailer->setSender($sender);
$mailer->addRecipient($reciptient);
$mailer->setSubject($subject);
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setBody($Body);
if ($name == '' || $rif == '' || $phone == '' || $name == 'Azienda' || $rif == 'Riferimento' || $phone == 'Telefono') {
} else {
$send =& $mailer->Send();
}
if ($send != true) {
return 'no';
} else {
return 'ok';
}
}
}
?>
When alert(response) is displayed i can see the whole html code ( included) from the page, but I'm not able to show only the "return" from the PHP page.
What am I doing wrong?
You can check an example of my problem here: http://www.sevenit.it (check at the top right of the page after 3 seconds)
Thanks
alert(response.responseText);
would be the way to go i believe.
EDIT:
Or what you might be wanting to do is:
$('#amCallMeBackForm').html(response.responseText)
Not 100% sure what you're asking.
Related
I am adding a deactivate feature on a website i am working on, so I added a form with a textarea to tell the reason why the user is deactivating his account and a button that become enabled when the textarea is filled out so I sent the call via jquery ajax to a php script which will update the users_table in the database to 1 for deactivated then must log the user out and redirect them to the index page of the website. So everything works fine except the log out it is not happening and no redirect. I need help with that please
here is my php script :
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
// this to prevent from accessing this file by pasting a link to it
if(!is_ajax_request()) {
exit;
}
$user_id = (int)$_SESSION["user_id"];
if(isset($_POST['deactivate_reason'])) {
$deactivate_reason = mysql_prep($_POST['deactivate_reason']);
// INSERT into table
$query1 = "INSERT INTO deactivate_reason_table ( ";
$query1 .= "user_id, reason";
$query1 .= ") VALUES (";
$query1 .= " $user_id, '$deactivate_reason'";
$query1 .= ")";
$result1 = mysqli_query($connection, $query1);
$confirm_query1 = confirm_query($result1);
// if query1 is successful and replies deleted then we make the second query to delete the board comments
if ($confirm_query1 == 0) {
echo "error";
exit();
} else {
// UPDATE table
$query2 = "UPDATE users_table ";
$query2 .= "SET deactivated = 1";
$query2 .= "WHERE user_id = $user_id";
$result2 = mysqli_query($connection, $query2);
$confirm_query2 = confirm_query($result2);
if ($confirm_query2 == 0) {
echo "error";
exit();
} else {
if (isset($_COOKIE['username'])) {
// setcookie($name, $value, $expiration_time)
setcookie("username", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
if (isset($_COOKIE['user_id'])) {
setcookie("user_id", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
session_destroy();
// redirect_to() is a custom function in the functions.php that redirects
redirect_to("../index.php");
}
}
}
and here is my jquery ajax script :
$(document).on("click", "#deactivate_button", function(e){
e.preventDefault();
var text = $("#deactivate_reason_textarea").val();
var url = "widgets/deactivate.php";
$.ajax({
url: url,
method: "POST",
data: {
deactivate_reason: text
},
beforeSend: function() {
CustomSending("Processing...");
},
success: function(data){
$("#deactivate_reason_textarea").val("");
$("#dialogoverlay").fadeOut("Slow");
$("#sending_box").fadeOut("Slow");
$("body").css("overflow", "auto");
}
});
});
To redirect the user for a another page in PHP you can use something like header('Location: ...') (manual), but you are calling the script in ajax, then you need to put the redirect in this, not in the called PHP script.
To redirect in JavaScript you can use window.location (tutorial).
window.location = "my/another/script.php";
In your case, you need to put it in the success of ajax.
$.ajax({
... # your occulted script
success: function(data){
$("#deactivate_reason_textarea").val("");
$("#dialogoverlay").fadeOut("Slow");
$("#sending_box").fadeOut("Slow");
$("body").css("overflow", "auto");
window.location = "another/script.php";
// or you can put it in a timeout to show a message for the user or other thing
// setTimeout(function() {
// window.location = "another/script.php";
// }, 10000);
}
});
ok guys thanks a lot for your help, I managed to solve this with your help
after i added widow.location = "insert.php" like tadeubarbosa suggested then i went to my index.php page and added these lines :
if (logged_in()) {
$email = $user_data['email'];
$id = $user_data['user_id'];
$edited = account_edited($email);
if ($edited == 0){
redirect_to("editprofile.php?id=$id");
}
$is_deactivated = is_deactivated($_SESSION['user_id']);
if ($is_deactivated == 1) {
$query = "UPDATE users_table SET online = 0 WHERE user_id = $id";
$result = mysqli_query($connection, $query);
if (isset($_COOKIE['username'])) {
// setcookie($name, $value, $expiration_time)
setcookie("username", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
if (isset($_COOKIE['user_id'])) {
setcookie("user_id", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
session_destroy();
redirect_to("index.php");
}
}
then went to the login.php script and added a query to update deactivated = 0 if the user logs in so the account reactivates
I have an input box in html. The input searches an database through ajax and return the results in front-end. The problem is that I don't get the result from PHP. I don't know what I did wrong, so I hope you guys have a better understanding from me.
HTML
<body onload="AjaxFindPerson()">
.....
</body>
JS
var xmlHttp = createXmlHttpRequestObject();
function AjaxFindPerson() {
if ((xmlHttp.readyState == 0 || xmlHttp.readyState == 4) && document.getElementById("PersonSearchInput").value != "") {
person = encodeURIComponent(document.getElementById("PersonSearchInput").value);
xmlHttp.open("GET", "../lib/search.php?email=" + person, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else {
document.getElementById('Label-Result').innerHTML = "";
document.getElementById('UserNameSearchResult').innerHTML = "";
$('#add-person-btn').attr("disabled", "disabled");
setTimeout('AjaxFindPerson()', 1000);
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4 ) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
result = xmlDocumentElement.firstChild.data;
if (result[0] != false) {
document.getElementById('Label-Result').innerHTML = result[1];
document.getElementById('UserNameSearchResult').innerHTML = result[0];
$('#add-person-btn').removeAttr("disabled", "disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result[1];
}
setTimeout('AjaxFindPerson()', 1000);
}
else {
alert('Somenthing went wrong when tried to get data from server'+ xmlHttp.readyState);
}
}
}
PHP
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
session_start();
define("DB_HOST", 'mysql6.000webhost.com');
define("DB_USER", '');
define("DB_PASSWORD", '');
define("DB_DATABSE", '');
echo '<response>';
$email = $_GET['email'];
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_DATABSE, $conn);
$sq = mysql_query("SELECT UserEmail FROM Users");
$UserInfo = array();
while ($row = mysql_fetch_array($sq, MYSQL_ASSOC)) {
$UserInfo[] = $row['UserEmail'];
}
if (in_array($email, $UserInfo)) {
$result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
$row = mysql_fetch_row($result);
$returnRes = array($row[0], "We found results"); //row[0] holds the UserN
echo $returnRes;
}
else {
$returnRes = array(false, "We couldn't find results");
echo $returnRes;
}
echo '</response>';
?>
If we check the php-xml file alone will see the image bellow :
Do I need to pass the values to xml-php with another way?
UPDATE 1 in PHP
I manage to found a way to return the data correctly. Here are the update 'touch'
header('Content-Type: application/json');
and
if (in_array($email, $UserInfo)) {
$result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
$row = mysql_fetch_row($result);
echo json_encode(array( 'found' => $row[0], 'msg' => "We found results"));
}
else {
echo json_encode(array( 'found' => null, 'msg' => "We couldn't find results"));
}
The problem now is how to manipulate the js file to handle the return array. I made a try but it didn't worked:
result = xmlDocumentElement.firstChild.data;
if (result['found'] != null) {
document.getElementById('Label-Result').innerHTML = result['msg'];
document.getElementById('UserNameSearchResult').innerHTML = result['found'];
$('#add-person-btn').removeAttr("disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result['msg'];
}
**UPDATE 2 WORKING JS **
I figure out how to retrieve the data from PHP.
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
var result = JSON.parse(xmlDocumentElement.firstChild.data);
if (result['found'] != null) {
document.getElementById('Label-Result').innerHTML = result['msg'];
document.getElementById('UserNameSearchResult').innerHTML = result['found'];
$('#add-person-btn').removeAttr("disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result['msg'];
}
NOW ALL THE CODE IS WORKING! THANK YOU VERY MUCH GUYS!
+1 to all of you!
Four things :
Usage of send(null) doesn't seems to be right, just don't pass null in it.
Second one is timeout method. Instead the way you are using it, you can call it in the callback function or instead of string use the name at the function call.
The usage to remove the attribute is also wrong. It is currently using a set method as you have supplied a second argument. The remove attribute method only takes a attribute name.
I would rather suggest you to set a header for the application/json and use json_encode() method to return data.
For printing an array, you can either use json_encode(), or do somehow else transform your array into a string.
If we were to ignore the white elephant in the room and gloss over the use of mysql_* functions then a slightly different approach
<?php
session_start();
define('DB_HOST', 'mysql6.000webhost.com');
define('DB_USER', '');
define('DB_PASSWORD', '');
define('DB_DATABASE', '');
$dom=new DOMDocument('1.0','utf-8');
$root=$dom->createElement('response');
$dom->appendChild( $root );
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['email'] ) ){
/* Basic filtering IF mysql_* functions are used! */
$email = trim( strip_tags( filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL ) ) );
$conn = mysql_connect( DB_HOST, DB_USER, DB_PASSWORD );
mysql_select_db( DB_DATABASE, $conn ) or die('error: database connection failed');
/* By the looks of the original there should be no need for two queries and then an array lookup */
$result = mysql_query("SELECT `UserName` FROM `Users` WHERE `UserEmail` = '".$email."';");
/* If there are results, add nodes to the dom object */
if( mysql_num_rows( $result ) > 0 ){
while( $rs=mysql_fetch_object( $result ) ){
$root->appendChild( $dom->createElement( 'user', $rs->UserName ) );
}
} else {
/* Otherwise add error message */
$root->appendChild( $dom->createElement( 'error', 'We couldn\'t find any results!' ) );
}
}
/* Send the xml back to the js client */
header('Content-Type: text/xml');
$xml=$dom->saveXML();
$dom=null;
exit( $xml );
?>
function registration_ajax(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email','email','required|is_unique[register.email]');
if($this->form_validation->run() == FALSE){
$data = '{"status":"false","message":"Email already exists"}';
}
else
{
$email=$this->input->post('email');
$data= array(
'email'=>$email
);
$last_id = $this->model->registeration($data);
if ($last_id>0) {
$this->send_email($email);
$data = '{"status":"true","message":"Email Created successfully"}';
}
}
echo $data;
}
public function send_email($to='',$username="",$from='khadija#precisetech.com.pk')
///function send_mail()
{
$this->load->library('encrypt');
$toEmail = $this->encrypt->encode($to);
$toEmail = str_replace('/','forwardSlash',$toEmail);
$toEmail = str_replace('=','equalSign',$toEmail);
$toEmail = str_replace('+', 'plusSign', $toEmail);
$this->load->library('email');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'sadasds';//pust mail.com.pk
$config['smtp_port'] = '25334';
$config['smtp_user'] = 'example';
$config['smtp_pass'] = 'example1';
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
$config['validation'] = FALSE; // bool whether to validate email or not
$this->email->initialize($config);
$message = '<h1 align="center">Hellow</h1>';
$message = '<html><body style="color:#000; font-weight:normal; font-size:13/14px;"><p style="color:#000;">Hi!</p>';
$message .= '<table rules="all">';
$message .= "<p>Congratulations! You have almost completed your registration on Electronic Mall.<br><br>Click on link here to confirm your email address<br> 10.10.10.44<br><br>Thank you for joining us and becoming part of world's largest local classified sites.In our website, you can enjoy simple ad posting, easy searching and endless local listing for products.We appreciate you for choosing us in online market place.<br> Wishing you alot of success on your classified journey.Get started now!<br><br></p>";
$message .= "<p>Regards,<br>The Electronic Mall Team</p>";
$message .= "</table>";
$message .= "</body></html>";
$this->email->from($from);
$this->email->to($to);
$this->email->subject('Confirmation Email');
$this->email->message($message);
if(!$this->email->send()){
echo $this->email->print_debugger();
die();
}else{
}
}
////ajx code
//////////////////
<script>
$(document).ready(function(){
$('#registration_form').on('submit',function(e){
var email = $('#email').val();
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
/// $('#myModal').modal('hide');
$('#message_sent').html(message);
}
else{
$('#message').html(message);
}
}
});
e.preventDefault();
});
});
</script>
I want that after email is sent successfully then this message should be displayed
$data = '{"status":"true","message":"Email Created successfully"}';
When I commented the mail sending function then it display the successful message, I want that the message should be display after sending email.
have you tried returning a value from your send_email function?
if(!$this->email->send()){
return 'success';
}else{
$this->session->set_flashdata('message', 'To complete registration, click the link in email we just send you at khadija#precisetech.com.pk');
redirect('controller/login_register','refresh');
die();
}
then in your :
if ($last_id>0) {
$res = $this->send_email($email);
if($res === 'success'){
$data = '{"status":"true","message":"Email Created successfully"}';
}
}
I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.
Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.
Index.php
<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");
$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";
$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);
$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn);
?>
Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.
Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
And as final the Javascript
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
note: HTML is being returned from the "page" class called inside Index.php
How do i not let everything get called twice?
Thank you,
EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php
AutoComplete.PHP
Please explain what should be in the file and why. I am clueless.
Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:
if(!isset($_REQUEST['calledByAjax']))
{
$IndexPage = new page();
echo $IndexPage->render();
}
and in your Ajax call:
data: { query: query_value, calledByAjax: 'true' },
Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.
First thing (this is a sample, not tested yet)
autocomplete.php
<?php
$search_string = $_POST['query'];
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
}
echo($output);
?>
autocomplete.js
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "autocomplete.php", //Here change the script for a separated file
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
} else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
search(); // call the function without setTimeout
}
});
});
Have luck :)
I currently have my jQuery outputting the result in the same div as per error or success:
HTML
<div id="error-message").html(res);
JQUERY
jQuery('#register-me').on('click',function(){
$("#myform").hide();
jQuery('#loadingmessage').show();
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
$('#loadingmessage').hide();
$("#myform").show();
jQuery("#error-message").html(res);
});
});
PHP
$error = '';
$uname = trim( $_POST['username'] );
$email = trim( $_POST['mail_id'] );
$fname = trim( $_POST['firname'] );
$lname = trim( $_POST['lasname'] );
$pswrd = $_POST['passwrd'];
if( empty( $_POST['username'] ) )
$error .= '<p class="error">Enter Username</p>';
if( empty( $_POST['mail_id'] ) )
$error .= '<p class="error">Enter Email Id</p>';
elseif( !filter_var($email, FILTER_VALIDATE_EMAIL) )
$error .= '<p class="error">Enter Valid Email</p>';
if( empty( $_POST['passwrd'] ) )
$error .= '<p class="error">Password should not be blank</p>';
if( empty( $_POST['firname'] ) )
$error .= '<p class="error">Enter First Name</p>';
elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) )
$error .= '<p class="error">Enter Valid First Name</p>';
if( empty( $_POST['lasname'] ) )
$error .= '<p class="error">Enter Last Name</p>';
elseif( !preg_match("/^[a-zA-Z'-]+$/",$lname) )
$error .= '<p class="error">Enter Valid Last Name</p>';
if( empty( $error ) ){
$status = wp_create_user( $uname, $pswrd ,$email );
if( is_wp_error($status) ){
$msg = '';
foreach( $status->errors as $key=>$val ){
foreach( $val as $k=>$v ){
$msg = '<p class="error">'.$v.'</p>';
}
}
echo $msg;
} else {
$msg = '<p class="success">Registration Successful</p>';
echo $msg;
}
} else {
echo $error;
}
die(1);
}
}
I'm getting confused on how to get the results in 2 different places.
1: Error = display errors and show the form, ideally errors should be displayed below each form field, at the moment is a div on top of the form
2: Success = hide the form, display only the success msg
METHOD 1
If you would like to have an error message per validated field then:
You have a form input, for example:
<input name="myfield" id="myfield" type="text">
Next to it, you can add a div or span with your alert/error message and appropriate id, something like:
<input name="myfield" id="myfield" type="text">
<span id="myfield_Error" class="none">Please fill this field</span>
Where class="none" in your css, is used to hide the error container. Something like:
.none {display:none;}
Now for your jquery part:
var myfield= $("#myfield").val();
if (myfield=='') { $("#myfield_error").show(); }
The trick here is to named your error containers in a similar way as your target form element you validate. So for id="fieldA" you will have the error id="fieldA_error".
EDIT1:
If you need to use classes, you need to modify a little the code.
You need to form an array of element to check.
Loop through the array.
And use somethign like:
var fieldName = $(this).attr('name');
var fieldVallue = $(this).val();
if (fieldVallue=='')
{
$("#"+fieldName+"_error").show();
}
else
{
$("#"+fieldName+"_error").hide;
}
Method 2
If you just like to have 2 different containers, one for success and one for error/failed validation, then you need to output something different from your php file.
So your php file can output someting like:
$report['status'] = 'error'
$report['message'] = 'error in xxxx field - please use a proper email'
echo json_encode($report);
Then in your ajax success you can check what response you got. You parse your json response and based on your 'status', you put your 'message' in different containers
I hope this is what you look for.
Alternatively you can assign an error handler as follow
var jqxhr = jQuery.post(
ajaxurl,
ajaxdata,
function(res){
$('#loadingmessage').hide();
$("#myform").show();
jQuery("#error-message").html(res);
}
).fail(function() {
alert("error");
});
and send a non-2xx code from your php code (with http_response_code) if it doesn't validate.
It would be easier for you to return (for example) JSON to the front end instead of one string. The JSON would containt key/value pairs in the form of ID => Message.
For example:
$errors = array();
if( empty( $_POST['passwrd'] ) ) {
$errors['st-psw'] = "Password should not be blank";
}
if( empty( $_POST['firname'] ) ) {
$errors['st-fname'] = 'Enter First Name';
} elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) ) {
$errors['st-fname'] = 'Enter Valid First Name';
}
...
...
if( empty( $errors ) ){
$response['success'] = true;
} else {
$response['success'] = false;
$response['errors'] = $errors;
}
echo json_encode($response);
Then you will loop the JSON object in your javascript and insert the error messages after each target.
Encode result array in JSON format and return the response.
<?php
if ($validation==false)
{
$result = array ('response'=>'error','message'=>'Some validation error');
}
else
{
$result = array ('response'=>'success','message'=>'Success');
}
echo json_encode($result);
?>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
dataType: "json",
success: function (data) {
if (data.response == 'error') {
alert('error');
} else if (data.response == 'success') {
alert('success');
} else {
alert('sorry there was an error');
}
}
});
</script>