Form doesn't submit on callback - javascript

I am trying to send an e-mail after an ajax call has been successfully completed. I do not have access to the file that I am making the AJAX call to.
I am preventing the first submit, making the ajax call and submitting the form again upon competition. When doing this, I can't seem to figure out why I have to press the submit button twice for the email to be sent.
Here is my code:
"use strict";
var submitted = '';
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
email = $('#email').val(),
phone = $('#primaryPhone').val(),
weight = $('#weight').val(),
origin = $('#originPostalCode').val(),
destination = $('#destinationPostalCode').val(),
notes = $('#whatsTransported').val()
if( submitted != 1 )
{
e.preventDefault();
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
crossDomain: true,
dataType: "json",
data: {"key": "my secret key","first": firstName, "last": lastName, "email": email, "phone": phone, "weight": weight, "origin_postal": origin, "dest_country": destination, "note": notes }
})
.done(function(data){
if(data[1][0][0] == 2)
{
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
})
.fail(function(data) { console.log(data); });
}
submitted = '1';
});
});
Here is the form HTML
<form action="<?php echo bloginfo($show='template_url').'/includes/form-email.php'; ?>" class="span6 offset1" id="quote" method="post">
<div class="row formRow">
<div class="firstName span3">
<label for="firstName"><?php _e('First Name:','StreamlinedService'); ?></label>
<input type="text" name="firstName" id="firstName">
</div>
<div class="lastName span3">
<label for="lastName"><?php _e('Last Name:','StreamlinedService'); ?></label>
<input type="text" name="lastName" id="lastName">
</div>
</div>
<div class="row formRow">
<div class="email span3">
<label for="email"><?php _e('Email Address:','StreamlinedService'); ?></label>
<input type="text" name="email" id="email">
</div>
<div class="primaryPhone span3">
<label for="primaryPhone"><?php _e('Phone Number:','StreamlinedService'); ?></label>
<input type="text" name="primaryPhone" id="primaryPhone">
</div>
</div>
<div class="row formRow">
<div class="weight span2">
<label for="weight"><?php _e('Weight (lbs):','StreamlinedService'); ?></label>
<input type="text" name="weight" id="weight">
</div>
</div>
<div class="row formRow">
<div class="originPostalCode span3">
<label for="originPostalCode"><?php _e('Origin:','StreamlinedService'); ?></label>
<input type="text" name="originPostalCode" id="originPostalCode">
</div>
<div class="destinationPostalCode span3">
<label for="destinationPostalCode"><?php _e('Destination:','StreamlinedService'); ?></label>
<input type="text" name="destinationPostalCode" id="destinationPostalCode">
</div>
</div>
<div class="row">
<div class="whatsTransported span6">
<label for="whatsTransported"><?php _e('What can we help you transport?','StreamlinedService'); ?></label>
<textarea name="whatsTransported" id="whatsTransported" rows="5"></textarea>
</div>
<input type="hidden" name="formType" value="quote" />
<input type="hidden" name="siteReferer" value="<?php echo $blog_id ?>">
<input type="submit" id="submit" name="submit" value="<?php _e('Get Freight Quote','StreamlinedService') ?>" class="btn btn-primary btn-large span3 offset3" style="float:right;">
</div>
</form>
My question is two-fold: Is there a more efficient way to do this? If not, why isn't this working?

Just use the .submit directly on the form node (note the [0])
$('#quote #submit').submit();
becomes
$('#quote')[0].submit();
this bypasses the jQuery bound event and forces a postback.

You use the wrong approach to Jquery
You miss the key : Write Less Do More, the heart of JQuery.
Anyway try this:
"use strict";
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var tis = $(this);
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
cache: true,
dataType: "json",
data: tis.serialize(),
success: function(data){
if(data[1][0][0] == 2){
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
},
error: function(data){console.log(data);}
});
e.stroPropagation();
e.preventDefault();
});
});
Last thin.. you CAN'T request a remote page that's not hosted on the same domain of the script.. For that ther's This answer

Related

JS - recaptcha v3 - how to verify captcha and submit form data to another file

I'm just starting with JS and like to implement a form that verifies for robots/humans by using captcha v3 on the client side and if verification succeeds the data should be submitted to another file.
This is what I got so far. I know it's wrong, but unsure what the correct logic is. Hope someone can shed a light. Thx!
<script src="https://www.google.com/recaptcha/api.js?render=6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></script>
<script type="text/javascript" src="/js/libs/jquery-1.11.3.min.js"></script>
<section class="cc-column-component regular-grid">
<form id="bank-form" class="form clear one-full cf-contact-form" action="?" method="POST" data-tracking="contact_sales">
<div>
<label class="label mandatory bank-color bank-label" for="firstName">First Name</label>
<input id="firstName" value="Pepe" type="text" class="one-full bank-color-grey bank-input" name="firstName" placeholder="First Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getFirstName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="lastName">Last Name</label>
<input id="lastName" value="Chanches" type="text" class="one-full bank-color-grey bank-input" name="lastName" placeholder="Last Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getLastName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="email">Email</label>
<input value="asdf#asdf.com" id="email" type="text" class="one-full bank-color-grey bank-input" name="email" placeholder="Email" autocomplete="off" data-validate="true" data-type="email" value="<?php isset($this) ? print $this->getEmail() : print ''; ?>">
<br/>
</div>
<div class="row inline one-full">
<br/>
<!-- <div class="g-recatpcha" data-sitekey="6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></div> -->
<button type="submit"
id="form-submit"
value="submit"
>
<a>Submit form</a>
</button>
<div class="field inline one-full">
<br/>
</div>
<!-- <input type="hidden" name="recaptcha_response" id="recaptchaResponse"> -->
</div>
</form>
</section>
<script>
$('#bank-form').submit(function(event) {
console.log('subtmitting');
event.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ', {action: 'submit'}).then(function(token) {
console.log('🚀 ~ grecaptcha.execute ~ token', token)
$('#bank-form').prepend('<input type="hidden" name="token" value="' + token + '">');
$('#bank-form').prepend('<input type="hidden" name="action" value="submit">');
// $('#bank-form').unbind('submit').submit();
});;
});
CheckCaptcha(token)
});
function CheckCaptcha(token) {
var token = $("#token").val()
console.log('🚀 ~ token', token)
var action = $("#action").val()
var RECAPTCHA_V3_SECRET_KEY = "6Lc3UZkeAAAAAIG8bVZDpkheOxM56AiMnIKYRd6z"
$.ajax({
type: "POST",
url: "http://www.google.com/recaptcha/api/siteverify",
data: JSON.stringify([{secret: RECAPTCHA_V3_SECRET_KEY }, {response : token }]),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// __doPostBack('form-submit', '');
if(response["score"] >= 0.7) {
console.log('Passed the token successfully');
}
},
failure: function (response) {
// set error message and redirect back to form?
console.log('Robot submit', response);
}
})
return false;
}
</script>

Your session has expired. on ajax form post laravel

I have the following html snippit from my view and js code to handel the form request.
$('#quick-enquiry').on('submit', function(e) {
e.preventDefault();
$(".submit").prop("disabled", true);
data = $(this).serialize();
action = $(this).attr('action');
$.ajax({
type: 'POST',
url: action,
data: data,
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
success: function(data) {
if ($.isEmptyObject(data.error)) {
$("#quick-enquiry").trigger("reset");
$('.print-error-msg').find('ul').empty();
$('.print-error-msg').css('display', 'block');
$("#response-msg").toggleClass('uk-alert-danger uk-alert-success');
$('.print-error-msg').find('ul').append("<li>" + data.success + "</li>");
setTimeout(function() {
$('.print-error-msg').fadeOut();
$(".submit").prop("disabled", false);
UIkit.modal("#modal-quick-enquiry").hide();
}, 3000);
} else {
printMessageErrors(data.error);
}
}
});
});
function printMessageErrors(msg) {
$('.print-error-msg').find('ul').empty();
$('.print-error-msg').css('display', 'block');
$.each(msg, function(key, value) {
$('.print-error-msg').find('ul').append("<li>" + value + "</li>");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.26/js/uikit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.26/css/uikit.min.css" rel="stylesheet" />
<form action="{{ route('frontend-postEnquiry') }}" method="POST" id="quick-enquiry">
<input type="hidden" id="tour-id" value="1">
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Full Name</label>
<div class="uk-form-controls">
<input class="uk-input uk-form-width-large" type="text" placeholder="Full Name" id="fullName" name="fullName">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Email</label>
<div class="uk-form-controls">
<input class="uk-input uk-form-width-large" type="email" placeholder="Email" id="email" name="email">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Message</label>
<div class="uk-form-controls">
<textarea class="uk-textarea uk-form-width-large" rows="4" placeholder="Some Message...." id="enquiryMessage" name="enquiryMessage"></textarea>
</div>
</div>
<p class="uk-text-right">
<button class="uk-modal-close-default" type="button" uk-close></button>
<button class="uk-button uk-button-primary submit uk-width-1-1" type="submit">Send</button>
</p>
</form>
With the above code I'm getting
419
Sorry, your session has expired. Please refresh and try again.
I've set CSRF-TOKEN in ajax and in head section also, but seems like my js code is not picking up csrf token.
I would be very thankful if anyone could highlight the mistake I've made above.
Try using this:
{{ csrf_field() }} instead of #csrf
419 error is mostly because of CSRF token issues.

var onSuccess works in HTML file but not in .js file

I am implementing Google's Invisible Recaptcha and I am trying to have everything run from my mail.js file (and I would really prefer to keep it there). For some reason Recaptcha is not finding "onSuccess" in mail.js but if I move it to the HTML inside <script></script> it works.
I am getting this error in JavaScript console: ReCAPTCHA couldn't find user-provided function: onSuccess when it is in mail.js
$(".input-field").each(function () {
var $this = $(this);
if ($this.val().length) {
$this.parent().addClass("input--filled")
}
$this.on("focus", function () {
$this.parent().addClass("input--filled");
});
$this.on("blur", function () {
if (!$this.val().length) {
$this.parent().removeClass("input--filled")
}
})
});
$(function () {
// Get the form.
var form = $('#ajax-contact'),
// Get the messages div.
formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function (e) {
// Stop the browser from submitting the form.
grecaptcha.execute();
e.preventDefault();
});
});
var onSuccess = function(response) {
$("#btn-submit").addClass("btn-loading");
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function (response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success').fadeIn().delay(5000).fadeOut();
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$(form).trigger("reset");
grecaptcha.reset();
$("#btn-submit").removeClass("btn-loading");
})
.fail(function (data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error').fadeIn().delay(5000).fadeOut();
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
$("#btn-submit").removeClass("btn-loading");
});
};
here is the HTML:
<form id="ajax-contact" class="" method="post" action="mailer.php">
<fieldset>
<div class="row">
<div class="input col-xs-12 col-sm-12 padding-bottom-xs-50 padding-bottom-40">
<label class="input-label" for="name">
<span class="input-label-content font-second" data-content="name">name *</span>
</label>
<input class="input-field" type="text" name="name" id="name" required />
</div>
<div class="input col-xs-12 col-sm-6 padding-bottom-xs-50 padding-bottom-50">
<label class="input-label" for="email">
<span class="input-label-content font-second" data-content="email">email *</span>
</label>
<input class="input-field" type="email" name="email" id="email" required />
</div>
<div class="input col-xs-12 col-sm-6 padding-bottom-xs-60 padding-bottom-50">
<label class="input-label" for="company">
<span class="input-label-content font-second" data-content="company">company</span>
</label>
<input class="input-field" type="text" name="company" id="company" />
</div>
<div class="message col-xs-12 col-sm-12 padding-bottom-xs-40 padding-bottom-30">
<label class="textarea-label font-second" for="message">message *</label>
<textarea class="input-field textarea" name="message" id="message" required></textarea>
</div>
</div>
<div class="g-recaptcha" data-sitekey="6Lf-6XQUAAAAAGhsZxXTlA3MtMGr_xDhOXPG-Ds0" data-badge="inline" data-size="invisible" data-callback="onSuccess"></div>
<div id="form-messages" class="form-message"></div>
<div class="col-xs-12 margin-top-30 text-center">
<button id="btn-submit" type="submit" class="btn btn-animated btn-contact ripple-alone" data-text="send it"><span class="btn-icon"><span class="loader-parent"><span class="loader3"></span></span>
</span>
</button>
</div>
</fieldset>

Get values from HTML to javascript

So I have a simple form where I ask the user some info to register and make an account, this is the part of the form I am using to achieve that:
<form class="login-form2" action="index.html">
<div class="center sliding"><img style='width:20%; margin: 42%; margin-top: 8%; margin-bottom: 0%;'src="./images/logoTemporal.png"></div>
<div class="login-wrap">
<p class="login-img"><i class="icon_lock_alt"></i></p>
<!-- Name -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_profile"></i></span>
<input type="text" id="Name" name="Name" class="form-control" placeholder="Name or Name.Corp" autofocus>
</div>
<!-- Email -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="email" id="Email" name="Email" class="form-control" placeholder="Email">
</div>
<!-- Passwrod -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="password" id="Password" name="Password" class="form-control" placeholder="Password">
</div>
<!-- Confirm password -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="password" class="form-control" placeholder="Confirm Password">
</div>
<!-- Tipo -->
<div class="item-content input-group-addon">
<div class="item-media"><i class="icon f7-icons">Tipo Usuario</i></div>
<br>
<div class="item-input">
<select id="Tipo" name="Tipo">>
<option value="0" selected>Empresa</option>
<option value="1">Usuario</option>
</select>
</div>
</div>
<br>
<!-- Button-->
<!-- <a class="btn btn-primary btn-lg btn-block" href="register.html">Register</a> -->
<p> <input type="button" class="btn btn-primary btn-lg btn-block" id="signup" value="Send"/></p>
</div>
</form>
I am trying to get the values into some variables in a jc, but for some reason I am not getting them:
$(document).ready(function() {
$("#signup").click(function() {
alert("Im in the function");//this is the only alert showing when I test the page...
//From here on it is not working
var Name = $('#Name').val();
var Email = $('#Email').val();
var Password = $('#Password').val();
var Tipo = $('#Tipo').val();
if (Name == '' || Email == '' || Password == '' || Tipo == '')
{ alert("please complete the information"); }
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: 'dummy url',
crossDomain: true,
beforeSend: function(){ $mobile.loading('show')},
complete: function(){ $mobile.loading('hide')},
data: ({Name: Name, Email: Email, Password: Password, Tipo: Tipo}),
dataType: 'json',
success: function(html){
alert("Thank you for Registering with us! you
can login now");
},
error: function(html){
alert("Not Working");
}
});
}//else end
});
});
I am still trying to learn many things here but what I need to know is why the variables are not getting the values from the form, could be something dumb but I just cant see it... Would appreciate some help...
EDIT:
Adding my php code, now I get an error when trying to send the data to my host´s php using JSON, the javascript prints the "not working" alert, what I think is that my php is not really getting the json so its not working but im not 100% sure so here is my php code:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS');
require 'data/DataCollector.php';
$varData = json_decode($data);
$Name = $varData->Name;
$Email = $varData->Email;
$Password = $varData->Password;
$Tipo = $varData->Tipo;
$database = new DataCollector([
'database_name' => 'dummy url',
'server' => 'dummy server',
'username' => 'dummy username',
'password' => 'dummy password',
'charset' => 'utf8',
]);
if($_POST){
$database->insert("Usuario", [
"nombre" => $_POST[$Name],
"email" => $_POST[$Email],
"password" => $_POST[$Password],
"tipoUsuario" => $_POST[$Tipo]
]);
}
?>
I have never used JSON and I am trying to learn about it, there is probably A LOT of issues with my code but any help will be very much appreciated! thanks!
your dictionary does not seem to be correct.
try this:
data: {"Name": Name, "Email": Email, "Password": Password, "Tipo": Tipo}

How to Check database field through AJAX

i have created a form which is submitting data through ajax to the database.this works fine.how can i prevent entering sitename is already available in database.if that sitename already in database it should give error message.
Controller
public function user_add()
{
$data_save = array(
"Mnumber" => $this->input->post("Mnumber"),
"email" => $this->input->post("email"),
"fname" => $this->input->post("fname"),
"address" =>$this->input->post("address"),
"sitename" =>$this->input->post("sitename"),
/* "reqnum" => $this->input->post("reqnum"),*/
"title" => $this->input->post("title"),
"descr" => $this->input->post("descr"),
/*"payment" => $this->input->post("payment"),*/
"uniquekey" => $this->input->post("uniquekey")
/*"subscription" => $this->input->post("subscription"),
"email_sent" => $this->input->post("email_sent"),*/
);
if ($this->user_mod->AddUser($data_save)) {
echo "Successfully Saved";
}
else {
echo "error";
}
}
view
<script>
function save_user_new() {
var Mnumber = $('#Mnumber').val();
var email = $('#email').val();
var fname = $('#fname').val();
var address = $('#address').val();
var sitename = $('#sitename').val();
/*var reqnum = $('#reqnum').val();*/
var title = $('#title').val();
var descr = $('#descr').val();
var uniquekey = $('#uniquekey').val();
/*var subscription = $('#subscription').val();
var email_sent = $('#email_sent').val();
var payment = $('#payment').val();*/
if (sitename != "" && email != "") {
$.ajax({
type: "post",
async: false,
url: "<?php echo site_url('form_con/user_add'); ?>",
data: {
"Mnumber": Mnumber,
"email": email,
"fname": fname,
"address": address,
"sitename": sitename,
/*"reqnum": reqnum,*/
"title": title,
"descr": descr,
"uniquekey": uniquekey
/*"subscription": subscription,
"email_sent": email_sent,
"payment":payment*/
},
dataType: "html",
success: function (data) {
alert(data);
if (data == 'error') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Something wrong.");
} else if (data == 'have') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : This Sitename is already exists.");
} else {
$('#error_msg1').hide();
$('#success_msg').show();
$('#success_msg').html("User details successfully saved.");
/*setTimeout(function() { location="features.php"},2000);*/
location.href = 'freecreate';
}
}
});
} else {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Please enter User Details.");
}
}
</script>
<form action="#" id="form_sample_1">
<div class="form-body">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Your First Name</label>
<input type="text" class="form-control" id="fname" name="fname" placeholder="Enter text" required="">
</div>
<div class="form-group">
<label class="control-label">Email Address</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address" required="">
</div>
</div>
<div class="form-group">
<label class="control-label">Your Mobile Number</label>
<input type="text" class="form-control" id="Mnumber" name="Mnumber" placeholder="Enter text" required="">
<!--<span class="help-block"> A block of help text. </span>-->
</div>
<div class="form-group">
<label class="control-label">Your Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Enter text" required="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Your Site Name</label>
<input type="text" class="form-control" id="sitename" name="sitename" placeholder="Enter text" required="">
<span class="help-block"> please enter the sitename only.if you wish to cretae site as john just type john.it will create the site automatically as john.site.mobi </span><br>
</div>
<div class="form-group">
<label class="control-label">Title of Your Web site</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Enter text" required="">
</div>
<div class="form-group">
<label class="control-label">Description of Your Web Site</label>
<input type="text" class="form-control" id="descr" name="descr" placeholder="Enter text" required="">
<!--<input type="hidden" class="form-control" id="req_num" name="req_num" value="1" placeholder="Enter text">-->
<?php $uniquekey = md5(uniqid(rand(), true)); ?>
<input type="hidden" class="form-control" id="uniquekey" name="uniquekey" value="<?php echo $uniquekey ?>" placeholder="Enter text">
<!--<input type="hidden" class="form-control" id="subscription" name="subscription" value="1" placeholder="Enter text">
<input type="hidden" class="form-control" id="email_sent" name="email_sent" value="1" placeholder="Enter text">-->
<!--<input type="hidden" class="form-control" id="payment" name="payment" value="1" placeholder="Enter text">-->
</div>
</div>
<div class="form-actions right">
<!--<a class="btn green" onclick="save_user_new()">Submit</a>-->
<button type="submit" id="save_btn" class="btn green" onclick="save_user_new()">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</form>
Model
public function AddUser($data_save)
{
if ($this->db->insert('users', $data_save)) {
return true;
} else {
return false;
}
}
Write a validate function which actually checks for empty value in textbox and returns true or false. Consider below example.
function ValidateForm(form){
var valid=true;
$(form).find('input[type="text"]').each(function(){
if($(this).val()=="")
valid=false;
});
return valid;
}
function save_user_new() {
//getting all the values
//change if condition to
var form=$("#form_sample_1");
if(ValidateForm(form))
{
//continue with ajax
}
else
{
alert('Please fill all the fields');
return false;
}
}
Add jQuery required in save_user_new function
$("input").prop('required',true);
There is a couple of ways to do this.
As previously mentioned, write a validate method and check if the record already exists in the database.
Set the field to 'unique', and catch the error when you run the query,
also if you want to save yourself some time and coding write a helper function which will load all your post variables for your.
eg.
function LoadPostVariables($variables = [])
{
$CI = & get_instance();
$return_array = [];
foreach($variables as $key){
$p_val = $CI->input->post($key);
//you could perform some basic validation here
$return_array[$key]=$p_val;
}
}
$values = LoadPostVariables(['MNumber', 'email', 'fname', 'address', 'sitename', 'title', 'descr', 'uniquekey']);
public function AddUser($data_save)
{
$check = false;
$query = "SELECT * FROM users WHERE email='$data_save' LIMIT 1";
$result = mysqli_query($dbc, $query);
if($result){
while($row = mysqli_fetch_assoc($result)){
$check = true;
}
}
if($check == false){
// add data
}else{
echo 'Email already found'; exit();
}
}

Categories