rendering views inside view while processing ajax form in codeigniter? - php

while processing a form with an Ajax call to one of my controller function then it will show a notification inside a div i need to display this notification message which already included with the design with special css format ..
i though it can be done through rendering the notifications view which i split it from the main design
i tried to do like this ..
public function add ()
{
$data = array();
if (!empty($_POST)) {
$this->model->insert();
$this->load->view('dashboard/notification', $data);
exit;
}
$this->load->view('dashboard/categories', $data, FALSE);
}
but sadly it didn't work and nothing appear ..
when i printed a simple message to show if everything working normally it shows up the message and print it normally ..
public function add ()
{
$data = array();
if (!empty($_POST)) {
$this->model->insert();
echo 'message';
exit;
}
$this->load->view('dashboard/categories', $data, FALSE);
}
and this is the jquery script
$(document).ready(function() {
$("#addCatgory").validate({
rules: {
categoryname: {
required: true,
minlength: 5
},
categoryslug: {
required: true,
minlength: 5
},
categorytype: {
required: true,
min : 1
}
},
messages:{
categoryname : 'Please enter your name',
categoryslug : 'Please enter a valid email',
categorytype : 'Please enter a valid type'
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type: "POST",
async: false,
data: $("#addCatgory").serialize(),
success: function(data){
$('#result').html(data);
},
error: function(){alert('error');}
});
}
});
});

You need to modify this part by setting TRUE as third parameter so HTML is printed back to your Ajax response
public function add ()
{
$data = array();
if (!empty($_POST)) {
$this->model->insert();
echo $this->load->view('dashboard/notification', $data, TRUE);
exit;
}
$this->load->view('dashboard/categories', $data, FALSE);
}

Related

Server-side validation is repeating on all the field using ajax in Codeigniter

I am using Codeigniter. I am getting the issue on server-side validation error message using ajax. Server-side validation is not displaying properly.
Gender field is required but I am getting the server-side error message on all the field. Also, check I am getting the id name.
I have to display the error message on the specific field which is required.
I tried below code
js
my success code
success: function(data) {
if (data.error == "true") {
swal({
title: "Success",
text: data.msg,
icon: data.icon,
type: "success"
}).then(function() {
window.location.href = baseUrl + "/Menu_control/confirmList";
});
} else {
$.each(data.error, function(key, value) {
var element = $('#' + key);
element.after(value);
});
}
},
Controller
$response = array('success' => false, 'error' => array());
if ($this ->form_validation-> run() == FALSE) {
foreach($_POST as $key => $value) {
$response['error'][$key] = validation_errors($key);
}
} else {
//submit code here
}
echo json_encode($response);
I remove foreach from the controller and added below code. In the console, I am getting the correct output now how do I display below of error message below of the field?
$errors_val = validation_errors();
$response['error']=$errors_val;
Would you help me out with this issue?

Jquery remote method showing the email and mobile already exist on the edit page without change anything

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; ?>

using jQuery Validation 'remote' with PHP

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?

jQuery Validation - prevent submit on remote

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/

How to make jQuery Validator remotely trigger errorPlacement?

Can anyone please tell me how I can get the jQuery Validator to call the errorPlacement handler when a remote function fails? I have provided a short example:
Cliff Notes: According to their documents, I have to output JSON, but I must have missed something because do I just echo out json_encode, or do I provide a key like echo json_encode(array('result' => 0)) as it says in this block of text.
JS:
var validator = $("form#signup").validate({
onfocousout: true,
rules: {
email: {
required: true,
email: true,
remote: {
type: "POST",
url: 'test.php',
data: {
email: function() {return $("#email").val();}
}
}
},
errorPlacement: function(error, el) {
console.log('ERR' + $(el).attr('id'));
}
}
});
PHP:
<?php
echo false; // This should allow the errorPlacement to call shouldn't it?
I think you need to echo false as a string from your PHP script:
<?php
echo 'false';
I've created a jsfiddle based on your question. The pastebin link just returns the word "false".

Categories