I need to prevent form from submitting when remote call returns true as result. How can I do this?
The JS code:
var userForm = $('#user-form');
userForm.validate({
rules : {
email : {
email: true,
remote: {
url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
type: 'POST',
data: function(){
return $('#email').val()
},
complete: function(data){
if(data.responseText.trim() == 'true'){
return false;
}
}
}
}
}
});
Server side:
public function isUniqueEmail()
{
$result = $this->users->isUniqueEmail($this->input->post('email'));
if($result):
echo false;
else:
echo true;
endif;
}
Quote OP:
"I need to prevent form from submitting when remote call returns true as result."
That's backwards. You would return false to block the submit and trigger the validation message.
You don't need the data option since the plugin sends the field value by default. You also don't need the complete option as the plugin captures the server response automatically.
JavaScript:
var userForm = $('#user-form');
userForm.validate({
rules: {
email: {
email: true,
remote: {
url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
type: 'POST' // default is GET
}
}
}
});
Server-side:
public function isUniqueEmail()
{
$result = $this->users->isUniqueEmail($this->input->post('email'));
if($result):
// setting message in PHP allows you to dynamically have any message
echo json_encode('name is already taken');
else:
echo true;
endif;
}
ALTERNATE
(Custom error message set in JavaScript)
JavaScript:
var userForm = $('#user-form');
userForm.validate({
rules: {
email: {
email: true,
remote: {
url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
type: 'POST' // default is GET
}
}
},
messages: {
email: {
remote: "name is already taken"
}
}
});
Server-side:
public function isUniqueEmail()
{
$result = $this->users->isUniqueEmail($this->input->post('email'));
if($result):
echo false;
else:
echo true;
endif;
}
DOCUMENTATION: http://jqueryvalidation.org/remote-method/
Related
I am using CodeIgniter with jQuery validation. I am using remote to check mobile number and email id is already available or not in the database. So there is no issue when the user registers. I am getting the issue on the edit page.
On the edit page, I just change the name and address but mobile number and email id both are showing already exist. I haven't change mobile and email. I know it will call the controller to check mobile and email are available or not but is there any other way to handle this issue?
I mean, not to check the previous data and check current data if the user enters anything in the field.
I want to check user against the database when creating the account, but NOT check user against the database when editing the account.
$("#edit_member").validate({
errorElement: 'div',
rules: {
name: {
required: true,
alphabets: true,
minlength: 3
},
email: {
required: true,
Email: true,
remote: {
url: baseUrl + "/AddMember/isEmail",
}
},
phone: {
required: true,
number: true,
minlength: 10,
maxlength: 10,
remote: {
url: baseUrl + "/AddMember/isMobile",
// async: false
}
},
address: {
required: true,
minlength: 10
}
},
messages: {
email: {
remote: "Email already Exists"
},
phone: {
remote: "Mobile no already Exists"
},
},
submitHandler: function(form) {//form.submit();}
});
Controller
function isEmail()
{
$email = trim($this->input->get('email'));
$result = $this->addmember_model->isEmail($email);
if($result)
{
echo $msg = "false";
}
else
{
echo $msg = "true";
}
}
function isMobile()
{
$mobile = trim($this->input->get('phone'));
$result = $this->addmember_model->isMobile($mobile);
if($result)
{
echo $msg = "false";
}
else
{
echo $msg = "true";
}
}
Model
function isEmail($email)
{
$result = $this->db->where(['email'=>$email,'is_status'=>1])
->get('members')
->row();
return $result;
}
function isMobile($mobile)
{
$result = $this->db->where(['phone'=>$mobile,'is_status'=>1])
->get('members')
->row();
return $result;
}
Use PHP to determine if the page is Editing or Creating and set a variable as such. You could look at a URL segment with the URI Class.
<?php
$create = ($this->uri->segment(3) == "create") ? TRUE : FALSE;
?>
Then use PHP to write the relevant rule(s) for that particular version of the View.
$("#edit_member").validate({
....
rules: {
....
email: {
required: true,
Email: true,
<?php if ($create) : ?>
remote: {
url: baseUrl + "/AddMember/isEmail",
}
<?php endif; ?>
},
....
The above only works when this part of the JavaScript is in the View file and not included from an external JavaScript file.
Otherwise, if .validate() is part of an externally included JavaScript file, then you can use the .rules() method instead.
After the JavaScript includes (after .validate() invoked), programmatically remove the remote rule.
<?php if ($edit) : ?>
<script>
$(document).ready(function() {
$('[name="email"]').rules('remove', 'remote');
});
</script>
<?php endif; ?>
I'm attempting to use jQuery's remote validation method for a basic (well, should be) ajax call to some server-side logic. Now, where my situation gets peculiar is that i'm using SlimFramework and so I'm posting to a route, not a direct script page.
Here is the JS:
rules: {
email: {
required: true,
email: true,
remote: {
url: 'http://localhost:3000/email/check',
async: false,
type: 'post',
dataType: 'json',
data: {
email: function() {
return $('#email').val();
}
}
}
}
}
messages: {
email: {
required: 'Please enter an email address.',
remote: 'This email is already taken.'
}
}
Here is my server-side logic which I am almost certain is correct:
$app->post('/email/check', function() use ($app) {
$request = $app->request;
$email = $request->post('email');
$response = '';
$user = $app->user
->where('email', $email)
->first();
if($user) {
$response = false;
} else {
$response = true;
}
header("HTTP/1.1 200 OK");
header('Content-Type: application/json');
echo json_encode($response);
});
UPDATE
To be more specific, when I check the network response in the inspector, its seems the request is being made successfully:
However, The remote validation message that i specified in the messages property of the validation object is not being thrown...
Any suggestions as to why it is not functioning?
I am building an inline code validation for a web form. With my current script, When a bad code is entered and it is being corrected (same length), POST data is not using the latest value. For example, I first enter "QFFE" and then correct it to "QFFF", but the latter is not stored in $_POST. See Firebug extract ("QFFF" passed but "QFFE" processed):
Here is the code (AJAX part):
var data = {};
$(document).ready(function() {
$('input[type="submit"]').on('click', function() {
resetErrors();
var url = 'process.php';
$.each($('form input, form select'), function(i, v) {
if (v.type !== 'submit') {
data[v.name] = v.value;
}
}); //end each
console.log(data);
$.ajax({
dataType: 'json',
type: 'POST',
url: url,
data: data,
cache: false,
success: function(resp) {
if (resp === true) {
//successful validation
alert("OK, processing with workflow...");
// $('form').submit();
return false;
} else {
$.each(resp, function(i, v) {
console.log(i + " => " + v); // view in console for error messages
var msg = '<label class="error" for="'+i+'">'+v+'</label>';
$('input[name="' + i + '"], select[name="' + i + '"]').addClass('inputTxtError').after(msg);
});
var keys = Object.keys(resp);
$('input[name="'+keys[0]+'"]').focus();
console.log('QD: error val');
}
return false;
},
error: function() {
console.log('there was a problem checking the fields');
}
});
return false;
});
});
function resetErrors() {
$('form input, form select').removeClass('inputTxtError');
$('label.error').remove();
}
And here my PHP script (process.php):
<?php
//List of accepted codes
$code_list = array("QWOLVE", "QFFF");
session_start();
if(isset($_POST)){
if (empty($_POST['promo_code'])) {
$_SESSION['errors']['promo_code'] = 'Please enter a promo code to access the beta site';
}elseif(! in_array($_POST['promo_code'], $code_list)){
$_SESSION['errors']['promo_code'] = $_POST['promo_code']." is not a valid code";
unset($_POST);
}
if(count($_SESSION['errors']) > 0){
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
// header('Location: redirect.php');
exit;
}
//This is when Javascript is turned off:
echo "<ul>";
foreach($_SESSION['errors'] as $key => $value){
echo "<li>" . $value . "</li>";
}
echo "</ul>";exit;
}else{
//Form validation successful - process data here:
echo json_encode(true);
}
}
?>
How can I make sure that the process.php is always using the latest form data?
I'm not sure why you store errors in the the session, but since you don't seem to clear that session, the next time you call the POST method $_SESSION['errors'] will still have the previous error in it (QFFE), hence the output.
This is my reference link
I am trying to implement Email exist check using jQuery Validation plugin & CodeIgniter.
Backend: MySQL
My Database table users contains id (auto increment, primary key, integer field) and email (varchar). This table stores email ids.
I am getting the jQuery response. So it kinda works. But the function always returns TRUE. I don't know why. Even when I enter an email id that's not in the database table, I get that 'Email Id already in use' message which means the model function returns TRUE always. I tried JSON encoding the returned value, but it was useless. Everything looks perfect, don't know where I made mistake.
My Form:
<?php $attributes = array('name' => 'formed', 'id' => 'formed' ,'method'=>'POST' ,'action' => 'echo base_url()' );
echo form_open('home/myController', $attributes); ?>
<div class="input-group">
<input type="text" id="email" name="email" placeholder="Email *">
</div>
<?php echo form_close(); ?>
jQuery Validation
$('#formed').validate(
{
rules: {
email:{
email: true,
required: true,
remote:
{
url: base_url+"home/register_email_exists",
type: "post",
data:
{
email: function(){ return $("#email").val(); }
,csrf_test_name : csrf_token
}
}
}
},
messages: {
email:
{
remote: 'Email Id already in use.'
}
},
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element
.text('').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
My Controller Function:
function register_email_exists()
{
if (array_key_exists('email',$_POST))
{
if ( $this->Home_model->email_exists2($this->input->post('email')) == TRUE )
{
//echo json_encode(FALSE);
echo 'false';
}
else
{
//echo json_encode(TRUE);
echo 'true';
}
}
}
My Model Function:
function email_exists2($email)
{
$this->db->where('email', $email);
$query = $this->db->get('users');
echo $this->db->last_query();
if( $query->num_rows() > 0 )
{
return TRUE;
}
else
{
return FALSE;
}
}
FYI, I have included .js files for jQuery validation plugin. Also don't bother about the CSRF token for now. It works.
Remove the single quotes from controller return statement:
function register_email_exists()
{
if (array_key_exists('email',$_POST))
{
if ( $this->Home_model->email_exists2($this->input->post('email')) == TRUE )
{
//echo json_encode(FALSE);
echo false;
}
else
{
//echo json_encode(TRUE);
echo true;
}
}
}
I have some validation code something like this -
if ($('#address').val()) {
if ($('#address').val().length > 60 || $('#address').val().length < 5) {
errorMessage += "Length of Your Address must be between 5 and 60.\n";
valid = false;
} else {
var rege = /^[a-zA-Z]([0-9a-z_\s])+$/i;
if(!rege.test($('#address').val())){
errorMessage += "Please enter Valid Address.\n";
valid = false;
} else {
var address = $('#address').val();
//alert ('My address is : ' + address);
}
}
} else {
errorMessage += "please enter your address\n";
valid = false;
}
My problem is how I get this value to php. My value have here - var address = $('#address').val();
I need to check this value again in PHP and need to echo the value on the same page.
I use it something like this -
if( !valid && errorMessage.length > 0){
alert(errorMessage);
} else {
$.ajax({
type: "POST", // HTTP method POST or GET
url: "demo2.php", //Where to make Ajax calls
data: {
myname: name,
myaddress: address,
myemail: email
}
});
}
demo2.php page is the same page which my form have.
Above of my page I tried to print $_POST array but nothing display there.
echo '<pre>', print_r( $_POST).'</pre>';
Hope someone will help me.
Thank you.
First put a check in demo2.php for if POST is set
if( isset($_POST['myaddress']) ) {
// your echo statement here
}
Then you just need to add some code to the jquery handle the response.
if( !valid && errorMessage.length > 0){
alert(errorMessage);
} else {
$.ajax({
type: "POST", // HTTP method POST or GET
url: "demo2.php", //Where to make Ajax calls
data: {
myname: name,
myaddress: address,
myemail: email
}
}).done(function(response) {
$('#address-display-div').html(response);
});
}
replacing #address-display-div with whatever selector you're going to display the address in.
Request page:
var request =$.ajax({
type: "POST",
url: "demo2.php",
data: {myname: name,myaddress: address,myemail: email}
dataType: "json",
success: function (a) {
alert(a[0]);
}
});
request.fail(function(jqXHR, textStatus){alert('Ajax Error: '+ textStatus);});
And in your php file:
<?php
if(isset($_POST['myname']) && isset($_POST['myaddress']) && isset($_POST['myemail'])){
[do your stuff]
echo json_encode(array(0=>'<pre>'.print_r( $_POST,true).'</pre>'));
}
else
echo json_encode(array(0=>'Missed Variable'));
exit();
?>
Otherwise can you also post your php page?