Message error its not showing using ajax via jQuery - javascript

Im trying to update data in a form via ajax with jQuery.
Im doing the update with sucess, but when I have empty fields Im not getting my error message saying: myModal('config_datas_errempty','alert','Fill al fields please');
And also if I write a wrong format for email I dont have any message too.
Do you see where might be the error? Because for me everyting seems fine and I already review the code many times!
My php:
switch ($action)
{
case 'data_update':
$d['adress'] = $_POST['adress'];
$d['phone'] = $_POST['phone'];
$d['fax'] = $_POST['fax'];
$d['email']= $_POST['email'];
if(in_array('',$d))
{
echo 'errempty';
}
else if(!valMail($d['email']))
{
echo 'erremail';
}
else
{
$updateData= $pdo->prepare("UPDATE config_data set adress=?, phone =?, fax=?, email=? WHERE id = ?");
$updateData->bindValue(1, $d['adress']);
$updateData->bindValue(2, $d['phone']);
$updateData->bindValue(3, $d['fax']);
$updateData->bindValue(4, $d['email']);
$updateData->bindValue(5, '1');
$updateData->execute();
}
break;
default: echo 'Error';
}
My jQuery:
$('form[name="config_data"]').submit(function(){
var forma = $(this);
var data = $(this).serialize() + '&action=data_update';
$.ajax({
url: url,
data: data,
type: 'POST',
beforeSend: function(){
forma.find('.load').fadeIn("fast");
},
success: function( datas ){
if(datas == 'errempty'){
myModal('config_datas_errempty','alert','Fill al fields please');
}else if((datas == 'erremail')){
myModal('config_datas_accept','accept','Sucess update');
}
},
complete: function(){
forma.find('.load').fadeOut("fast");
}
});
return false;
});

Related

How do I get a message in a div box instead of the alert box with ajax success?

I'm trying to create error validation handling for my custom form. What I want to do is get the error messages in a div instead of the browser alert box but I'm new to all of this and have no idea how to do it. I tried to do some research but found nothing useful for my case.
Basically my form works and shows error or success messages correctly, but I don't want to display them in the alert box, but in a dedicated div. Thanks for any answers, I appreciate any help.
So here's what I have:
My section which contains all the various messages error
<div class="error-message-wrapper">
<!-- Here are all my error messages that are printed with the wc_print_notices(); function -->
</div>
My Script
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
alert( response );
}
});
});
});
My function
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
$msg = wc_print_notices();
$response = $msg;
} else {
$response = "Settings Saved!";
}
// Don't forget to exit at the end of processing
echo json_encode($response);
exit();
}
If u wanna show in exist class then choose element by document.querySelector(".className").innerHtml = response.textFromResponse or u can do like below
Query(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
alert( response );
const uiDivElement = document.createElement("DIV");
uiDivElement.innerHTML = response.textFromResponse
document.appendChild(uiDivElement)
}
});
});
});

Codeigniter & Ajax - Condition statement in javascript

Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.

Accessing PHP Value through Ajax

Ok so what I'm basically trying to do is sending a form which contains a password (predefined, no DB) through AJAX. In my php file I check the input and I try to return true or false to my JS, but this part fails as I can't manage to access the value. Here is my code:
ajaxRequest.js
// Variable to hold request
var request;
// Bind to the submit event of our form
$(".lockForm").submit(function(event){
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "assets/php/lockscreen.php",
type: "POST",
data: serializedData,
dataType: 'text',
success: function (data) {
console.log(data.status);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
lockscreen.php
<?php
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$pass = isset($_POST['pass']) ? $_POST['pass'] : null;
$response = false;
function CheckInput($pass){
if($pass == "SPV" || $pass == "TEACHERS"){
$response = true;
$responseLock['status'] = 'true';
echo json_encode($responseLock);
} else {
$response = false;
$responseLock['status'] = 'true';
echo json_encode($responseLock);
}
}
?>
So far I tried changing the dataType to JSON, but then I got an unexpected end of input error. If I leave it 'text', whenever I try to access the value, I get "undefined". If I only display the console.log, without trying to access any value, I get a success message. I have no idea why though.
call your CheckInput function:
<?php
$pass = isset($_POST['pass']) ? $_POST['pass'] : null;
$response = false;
function CheckInput($pass) {
if($pass == "SPV" || $pass == "TEACHERS"){
$result = true;
} else {
$result = false;
}
return array('status' => $result);
}
echo json_encode(CheckInput($pass));
?>

how to check that ajax returns true or false value using jquery

i'm building a signup form for my website i validate my signup page with jquery i want to do that when all the fields are filled with valid way then the signup page redirect or load and store the data in database...
1. first jquery code checks input fields
2. then in the jquery code there is a ajax call which check if the email already exist or not if the ajax call return true then data will be inserted in database if it return false the the page will not load and display the message that email is already exist
the problem in my code is that when the ajax call is true or false my page keep loading and insert the data in database but i want that if value is false page will not load.
here is my code
$.ajax({
type:'POST',
url:'email_validator.php',
data:{email:mail},
success:function (response){
var result = $.parseJSON(response);
if (result.status===false) {
$('#error').html("Email alreaday exist");
return false;
} if(result.status===true) {
return true;
}
}
});
and here is my email_validator.php
<?php
if(isset($_POST["email"])){
$result = array();
$email=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$email]);
if($STH->rowCount() == 1){
//echo "Email alreday exist";
$result["status"] = false;
}
else{
$result["status"] = true;
}
echo json_encode($result);
exit(0);
}
Try this:
$.ajax({
type:'POST',
url:'email_validator.php',
data:{email:mail},
success:function (response){
if (response.status === true) {
return true;
} else {
$('#error').html("Email alreaday exist");
return false;
}
}
});
In my opinion you should invoke the PHP API method to insert the new email directly inside the success function callback:
$.ajax({
type: 'POST',
url: 'email_validator.php',
data: {email: mail},
success: function (response) {
var result = $.parseJSON(response);
if (result.status === false) {
$('#error').html("Email already exists");
}
else (result.status === true) {
// -> Call here the PHP api method to insert the new email in the database
}
}
});
You can add async option to false and return outside the ajax call:
function testAjax() {
var resultStatus = "";
$.ajax({
type:'POST',
url:'email_validator.php',
async: false,
data:{email:mail},
success:function (response){
var result = $.parseJSON(response);
resultStatus = result.status;
if (result.status===false) {
$('#error').html("Email alreaday exist");
}
}
});
return resultStatus;
}
[UPDATE]
But you do not need to check this on client side. Yo can check if email exists in your email_validator.php and immediately write it to the database if it does not exist:
email_validator.php
<?php
if(isset($_POST["email"])){
$result = array();
$email=$_POST["email"];
$db=new PDO("mysql:host=localhost;dbname=the_scops","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH=$db->prepare("SELECT email FROM signup WHERE email=?");
$STH->execute([$email]);
if($STH->rowCount() == 1){
//echo "Email alreday exist";
$result["status"] = false;
}
else{
$result["status"] = true;
// --> INSERT the new email into the database
}
echo json_encode($result);
exit(0);
}

Security measures for AJAX-PHP scripts

For a link like this
DELETE
i am using this ajax call
$(function() {
$(".delete_msgs").click(function() {
var msgid = $(this).attr("id");
var dataString4 = 'msgid=' + msgid;
$('a#'+msgid).html('<img src="img/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "del_msg.php",
data: dataString4,
cache: false,
success: function(data){
if (data == 0) {
//alert('Sent!');
} else {
$('a#'+msgid).html(data);
$('.viewmessage'+msgid).hide();
}
}
});
return false;
});
});
The del_msg.php file contains that code:
if(isset($_POST)) {
$msgid = $_POST['msgid'];
$delmsg = mysql_query("DELETE FROM messages
WHERE id = $msgid") or die(mysql_error());
echo 'Message sent!';
} else {
echo 0;
}
My big question is, how can i protect my send throught AJAX function? Anyone can change the id of the #a element and, consequently, can delete any row from my database.
Is there a more secure way to call php with ajax, or at least, to hide my important variables sent via ajax?

Categories