I m validating a data by clicking the submit button and then again loading the views. I want just to show the errors on the page before loading the controller. Its is not a form validation. it is just a data validiation.
I think you can do the validation using AJAX.
in view page
<script type="text/javascript">
$(document).ready(function() {
/// make loader hidden in start
$('#loading').hide();
$('#email').blur(function(){
var email_val = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(filter.test(email_val)){
// show loader
$('#loading').show();
$.post("<?php echo site_url()?>/user/email_check", {
email: email_val
}, function(response){
$('#loading').hide();
$('#message').html('').html(response.message).show().delay(4000).fadeOut();
});
return false;
}
});
});
</script>
in controller function
public function email_check()
{
// allow only Ajax request
if($this->input->is_ajax_request()) {
// grab the email value from the post variable.
$email = $this->input->post('email');
// check in database - table name : tbl_users , Field name in the table : email
if(!$this->form_validation->is_unique($email, 'tbl_users.email')) {
// set the json object as output
$this->output->set_content_type('application/json')->set_output(json_encode(array('message' => 'The email is already taken, choose another one')));
}
}
}
Related
This question already has answers here:
jQuery Validate remote method usage to check if username already exists
(2 answers)
Closed 5 years ago.
I have a form that that is already validated by jquery.validate.min.js, what I want is another validation method, ajax call to mysql to check if the email address is already in my DB. How do I merge the validations? I already played a little with the codes but can't figure it out.
My form: http://demos.creative-tim.com/wizard-demo-register?_ga=2.138099576.979789193.1518540669-1813170823.1518540669
My validation code:
$('document').ready(function() {
var email_state = false;
$('#email').on('blur', function() {
var email = $('#email').val();
if (email == '') {
email_state = false;
return;
}
$.ajax({
url: 'index.php',
type: 'post',
data: {
'email_check': 1,
'email': email,
},
success: function(response) {
if (response == 'taken') {
email_state = false;
alert('email is taken');
} else if (response == 'not_taken') {
email_state = true;
alert('email available');
}
}
});
});
});
The PHP who process the email check:
<?php
$db = mysqli_connect('localhost', 'user', 'pass', 'subscribers');
if (isset($_POST['email_check'])) {
$email = $_POST['email'];
$sql = "SELECT * FROM subscribers WHERE email='$email'";
$results = mysqli_query($db, $sql);
if (mysqli_num_rows($results) > 0) {
echo "taken";
}else{
echo 'not_taken';
}
exit();
}
?>
Take a look at json_encode what you need to do is return a response (ex: true or false) to javascript from php (check this answer) .
Then check in the success js function the response, if it is true, then the email is already in the database, and alert the user, otherwise, submit the form with the email value.
There are two ways to accomplish this, 1) Make an ajax request for every keystroke on the email field $('#email-input').on('keyup')and once the response is false, enable the submit button via jquery $('#submit-button').prop('disabled', false) note that in your button html tag you should have the disabled property by default <input type="submit" id="submit-button" value="Submit" disabled /> and after the validation occurs you disable it, then it's going to be clickable and the user will be able to submit the form.
The problem is, that you're going to make a lot of ajax calls when the user types in the email address, and you don't want that, instead what you can do is to just make the request when the user submit the form (click on the submit button) and then prevent the default behaviour (sending a post request via form) for you to check via ajax if the email is already in use or not, if it is, do not submit the form and display a message, otherwise, submit the form.
<form id="form" action="http://foo.com" method="post">...</form>
$('#form').on('submit', function (ev) {
ev.preventDefault() // prevent default behaviour (making a post request)
// do your ajax call here to check the email availability
// if it's taken, do nothing and just display a message to the user
// otherwise, submit the form: $(this).submit()
})
Cheers.
I have a form that submits data to parse.com using the code below:
<script>
function validateForm() {
Parse.initialize("xxxx", "xxxxxx");
var TestObject = Parse.Object.extend("Event");
var testObject = new TestObject();
testObject.save({
Name: document.forms["myForm"]["fname"].value,
Date: document.forms["myForm"]["date"].value,
success: function(object) {
$(".success").show();
},
error: function(model, error) {
$(".error").show();
}
});
}
</script>
however I was wondering if there was a way that I could simultaneously send an email with the contents of the form. Is this possible?
You would need some type of server side script to send email.
If you use PHP, you could use the mail function.
In the JavaScript, you would just send an AJAX request to the server-side file containing the code that sends the email.
Yes you can, use AJAX to send it. Here's an example code:
JavaScript
var name = "Test";
var last_name = "Last Test";
$.ajax({
type:"POST",
url:"your_php_file.php",
data:{
name : name,
lastname : last_name
},
success:function(data){
// TODO when success
}
});
And your PHP file would look like:
$name = $_POST['name'];
$lastName = $_POST['lastname'];
Note i've used different last name's on purpose.
EDIT: Forgot to mention, once in PHP you can send email either by using mail, PHPMailer or whatever you wish
I've got an issue with a small javascript form that submits perfectly, brings up the success message but fails to reset the form. The data remains visible, until you manually refresh the page.
The code is:
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(750,function() {
$('#message').hide();
$('#submit')
.after('<img src="images/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
subject: $('#subject').val(),
comments: $('#comments').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null);
}
);
});
return false;
});
});
I wondered if I can add in a reset command but as my java is limited I'm not sure where? Would appreciate any pointers or advice. Thanks in advance.
You could add this inside the if (data.match...), as follows:
if (data.match("success") != null){
$('#contactform')[0].reset();
}
You need to manually clear/reset the form.
As you using JQuery to send the request, it is not like form action that changes your browser location.
Just call RESET once the data has been successfully sent.
For more on that see: http://www.w3schools.com/jsref/met_form_reset.asp
If on the other hand you want to reset your form values to defaults you specify you can create a function such as:
function resetFormValues()
{
$('#name').val('name');
$('#email').val('email');
etc..
}
and call resetFormValues(); from within your code such as:
if (data.match("success") != null){
resetFormValues();
}
I was trying to figure out how to check if the value entered in text box is existing in
database or no as soon as it is entered or on tab event using cakePHP and javascripts. I am new so please can someone help?
Thanks,
Create a validation for Unique on the field. It will check the value of the field before it saves it. If it exists, it will tell the user that the value already exists.
assumptions:
table: posts
model:Post
controller:Posts
and the field about which you need notification of pre-existence is post_title
Now do something like this
In view:
let id of text field for post_title is PostPostTitle
$('#PostPostTitle').bind({
blur:function(){
var newTitle = $(this).val();
if(newTitle){
$.ajax({
url:'Posts/checkTitle/',
type:'POST',
data:{title:newValue},
dataType:'JSON',
success:function(data){
if(data.ok==1){
//dont show any error and let the user submit
}else {
//show error notification in desired format
}
}
})
}
}
});
Now in your controller make an action with name checkTitle
controller code will be like this
public function checkTitle(){
//fetch the vlaue of title from appropriate key of the controller class
//variable $this->params (in cake v<2) or from $this->reuest (cake v2.x+)
$this->layout = 'ajax';//or json or null what ever you prefer
$this->autoRender = false;
//assumig that you have fetched value of newTitle in $newTitle from requestVar
//make a database query to post table
$response = array('ok'=>0);
$data = $this->Post->find('count',array('conditions'=>array('post_title'=>$newTitle)));
if($data==0) {
$response['ok']=1;
}
echo json_encode($response);
exit;
}
...Some form gets submitted...
$.("form").submit(function() {
saveFormValues($(this), "./../..";
}
function saveFormValues(form, path) {
var inputs = getFormData(form);
var params = createAction("saveFormData", inputs);
var url = path + "/scripts/sessions.php";
$.post(url, params);
}
The weird thing is that if i add a function to the
$.post(url, params, function(data) {
alert(data);
}
I get a blank alert statement.
Within scripts/sessions.php i have a function to save whatever the $_POST information is to a file, and the sessions.php never saves this saveFormValues call. It never shows up to the file. But if i keep trying to get it to save, about once every 15 will actually allow it to be saved. This leads me to believe that the forms POST is somehow blocking this value saving post. Any help?
add a return false; to the submit function to prevent the form from submitting:
$.("form").submit(function() {
saveFormValues($(this), "./../.."); return false });
UPDATE:
if you want to later submit the form, keep a variable to indicate if it can be submitted:
var canSubmit = false;
$.("form").submit(function() {
if(!canSubmit)
{
saveFormValues($(this), "./../..");
return false;
}
});
and later:
$.post(url, params, function(data) {
alert(data);
canSubmit = true;
$.("form").submit();
}
So instead of doing a $.post i tried doing a $.ajax with asynch set to false. It saves the form values every ... like 3/5 times... any new suggestions?
You need to cancel the original submit by returning false from the handler. Update: If you want the original form submission to continue, then you can remove the handler and re-submit the form from the post callback.
$.("form").submit(function() {
saveFormValues($(this), "./../..");
return false; // cancels original submit and allows AJAX post to complete
});
function saveFormValues(form, path) {
var inputs = getFormData(form);
var params = createAction("saveFormData", inputs);
var url = path + "/scripts/sessions.php";
$.post(url, params, function() {
$('form').unbind('submit').trigger('submit');
});
}
So i decided to create an associative list of items that will not be saved from a form.
$nosave = array("password" => true, "confirmPassword" => true,
"descriptionCount" => true, "detailedDescriptionCount" => true,
"submit" => true, "action" => true, "p" => true);
//Then i decided to go through the $_POST information and save it to the SESSION info.
foreach ($_POST as $key => $value) {
if ($key != $id && !array_key_exists($key, $nosave)) {
//saves the value to the form.
$_SESSION[$id][$key] = $value;
}
}
//The $id is a hidden input.. name="formId" value="someUniqueId" That way whenever
//the form info is saved, its saved under a unique area and can be easily unset.
Instead of doing it through jQuery, i just called a function that roughly does all of that in my sessions.php file.