So. I am trying create a fields validation using ajax. I have created the class "validate-field" on the fields where is a necessary a validation.
One Field is email_addres and another is taxvat. On my controller I just created thea action "validate" and then I am trying get the Field ID and Field Value.
Follow the codes below:
-the jQuery:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".continuar").on("click", function(){
url = "<?php echo Mage::getUrl('awmajax/ajax/validar')?>";
jQuery(".required-entry").each(function(){
if(jQuery(this).val() == ""){
jQuery(this).addClass("validation-failed");
}
else {
jQuery(this).removeClass("validation-failed");
}
});
jQuery(".validate-field").each(function(){
fieldName = jQuery(this).attr('id');
fieldValue = jQuery(this).val();
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
data: ({
field : fieldName,
value : fieldValue
}),
success: function(result){
console.log(result);
}
});
});
});
});
</script>
and the php:
public function validarAction(){
$params = $this->getRequest()->getParams();
if($params['field'] == 'taxvat'){
$taxvat = $params['value'];
$validacao = Mage::helper('awm_awmajax')->validaCPF($taxvat);
if($validacao == false){
$resultTaxvat = array(
"response" => "Taxvat is not valid",
"field" => $params['field']
);
}
$this->getResponse()->setBody(json_encode($resultTaxvat));
}
if($params['field'] = 'email_address'){
$emailAddress = $params['value'];
$validacaoEmail = Mage::helper('awm_awmajax')->checkEmailExists($emailAddress);
$resultEmail = array(
"response" => $validacaoEmail, //Type a valid Email
"field" => $params['field']
);
$this->getResponse()->setBody(json_encode($resultEmail));
}
}
What is the problem:
I get always just the email response on the second "If".
Any help is welcome.
Cheers
your second IF statement is passing a value and not comparing... I think you were supposed to write if ($params['field'] === 'email_address')
regarding your issue, try this:
public function validarAction()
{
$params = $this->getRequest()->getParams();
$error = false;
$errors = [];
if ($params['field'] == 'taxvat') {
$taxvat = $params['value'];
$validacao = Mage::helper('awm_awmajax')->validaCPF($taxvat);
if (!$validacao) {
$error = true;
$errors[] = [
'field' => $params['field'],
'message' => 'Taxvat is not valid',
];
}
}
if ($params['field'] === 'email_address') {
$emailAddress = $params['value'];
$validacaoEmail = Mage::helper('awm_awmajax')->checkEmailExists($emailAddress);
if (!$$validacaoEmail) {
$error = true;
$errors[] = [
'field' => $params['field'],
'message' => 'Type a valid Email',
];
}
}
$this->getResponse()->setBody(json_encode([
'error' => $error,
'errors' => $errors
]));
}
...tyr to use a loop construct to refactor this. as this may result in a lot of IF statements if you are going to validate a lot of fields.
EDIT:
Changed $result to $errors and the JSON index status to error. It would be easier to iterate with the updated code on your JS.
Related
I need to check the field phone_mobile for duplicate into the database. If a field value is not a duplicate then continue saving.
And if such a phone already exists in the database, then show the alert message and stop the process(form submission).
My actions:
In the file ./modules/Contacts/metadata/editviewdefs.php connected custom js file:
$viewdefs['Contacts']['EditView'] = array(
'templateMeta' => array(
'includes' => array (
array (
'file' => 'custom/include/javascript/custom_contact.js'
),
),
'form'=>array(
...
Works great.
In custom_contact.js file overload check_form(formname) function:
function check_form(formname)
{
if(formname === 'correct')
{
// This part does not work right for me
var _form = document.getElementById('EditView');
_form.action.value='Save';
SUGAR.ajaxUI.submitForm(_form);
return false;
}
if(formname === 'EditView')
{
// Ajax query works perfectly
$.ajax({
url : '/',
method : 'POST',
data : {},// some data
success : function(data) {
data = JSON.parse(data);
if(!data.success)
{
var text = 'The phone already exists';
return false;
}
check_form('correct');
}
});
}
return false;
}
But the if(formname === 'correct') ... block does not work correctly.
I need to stop the work of the form_save and include when necessary.
Please help to solve the problem correctly.I'm new to SugarCRM.
This is something related to javsacrip/jquery error handling and you can find many logics on google as well.
Try following code:
// DOM Ready
$('input#PHONE_FIELD_ID').on('change', function () {
handlePhoneValidation();
return false;
});
var clickAttr = $("#SAVE_BUTTON_ID").attr("onclick");
$("#SAVE_BUTTON_ID").attr("onclick","return handlePhoneValidation(); "+clickAttr);
function handlePhoneValidation(){
clear_all_errors();
var node = $('input#PHONE_FIELD_ID');
current_val = node.val();
/*
* Your validation will go here
* if condition fail then return false otherwise true
*/
return false;
}
I resolved this another way
./custom/modules/Module_name/metadata/editviewdefs.php
$viewdefs ['Accounts'] = [
'EditView' => [
'templateMeta' => [
'form' => [
'includes' => [
[
// include custom js file
'file' => 'modules/Module_name/file_name.js'
],
'buttons' => [
// Override save button and return after click custom function
0 => array (
'customCode' => '<input type="submit" name="save" id="save" onClick="this.form.return_action.value=\'DetailView\'; this.form.action.value=\'Save\'; return check_custom_data(\'EditView\'); " value="'.$GLOBALS['app_strings']['LBL_SAVE_BUTTON_LABEL'].'">',
),
'CANCEL',
After
modules/Module_name/file_name.js:
// Function check_custom_data() :
function check_custom_data(formname)
{
if(formname === 'correct')
{
var _form = document.getElementById('EditView');
_form.action.value='Save';
SUGAR.ajaxUI.submitForm(_form);
return check_form('EditView');
}
if(formname === 'EditView')
{
$.ajax({
url : '/',
method : 'POST',
data : { }, // Some data
success: function(data) {
data = JSON.parse(data);
if(!data.success)
{
// Some code
return false;
}
}
// If everything is ok
check_custom_data('correct');
}
});
return false;
}
This is working for me.
I want to check data in database through ajax in codeigniter how can get check name already exist through ajax
controller
public function insert(){
$user = array('Name' => $this->input->post('name'),
'Cnic' => $this->input->post('cnic'),
'Phone' => $this->input->post('phone'),
'Address' => $this->input->post('address'),
);
$this->load->model('suppliermodel');
if($this->suppliermodel->checkData($user['Name'])){
if ($this->session->userdata('user_id'))
$detail = 'Already exist';
$this->load->view('admin/includes/header');
$this->load->view('admin/includes/sidemenu');
$this->load->view('admin/add_supplier',['exist'=>$detail]);
$this->load->view('admin/includes/footer');
$this->load->view('admin/includes/add_supplier_footer');
}
else{
$this->suppliermodel->add($user);
}
}
model
public function checkData()
{
$name = $this->input->post('name');
$this->db->select('*');
$this->db->where('Name', $name);
$this->db->from('suppliers');
$query = $this->db->get();
if($query->num_rows() >0){
return $query->result();
}
else{
return $query->result();
return false;
}
}
what is ajax code and controller function
How about this?
Controller
public function insert(){
// set a rule that make the Name field is unique by 'set_rules'
$this->form_validation->set_rules('Name', 'Name Field', 'required|is_unique[suppliers.name]');
//$this->form_validation->set_rules('[Other Field]', '[Field Name to Display]', '[Restriction]');
// if the field cannot pass the rule
if ($this->form_validation->run() === FALSE) {
$errors = array();
foreach ($this->input->post() as $key => $value) {
// Add the error message for this field
$errors[$key] = strip_tags(form_error($key));
}
// Clear the empty fields (correct)
$response['errors'] = array_filter($errors);
$response['status'] = false;
}
else {
// otherwise, call the model
$result = $this->suppliermodel->add($user);
if ( $result ) {
$response['status'] = true;
}
}
echo json_encode($response);
}
JavaScript
$.ajax({
url: '//localhost/insert',
data: {
Name: $('input[name=Name]').val(),
Cnic: $('input[name=Cnic]').val(),
Phone: $('input[name=Phone]').val(),
Address: $('input[name=Address]').val()
},
dataType: 'JSON',
type: 'POST',
error: function(xhr) {
alert('request failed!');
},
success: function(response) {
var response = $.parseJSON(JSON.stringify(response));
if (response.status != true) {
$.each(response.errors, function(field, i) {
alert( field+ ' errors with ' + i)
});
}
else {
alert('success!');
}
}
});
Use is_unique[table.fieldToCompare] to make the field is always unique.
Wish it helps.
set_rules restrictions, see the Codeigniter User Guide Form validation
If fails, the controller would return a set of JSON, with field and error message. Then you can handle it in $.ajax's success.
I tried to convert the codeigniter form handling using ajax then display validation error if validation is false but in my current state, it always throw an error. Check the code below for reference.
PHP:
public function add () {
$post_data = $this->input->post('formdata');
$data = array (
'identity' => $post_data ['email'],
'password' => $post_data ['password'],
'email' => $post_data ['email'],
'group' => array($post_data['group_id']),
'additional_data' => array (
'first_name' => $post_data['first_name'],
'last_name' => $post_data['last_name'],
'active' => $post_data['active'],
'date_registered' => date('Y/m/d h:i:sa')
)
);
// custom error message
$this->form_validation->set_message('alpha_dash_space', '%s appears to be invalid. Must contain only alphabets.');
$this->form_validation->set_message('matches', '%s does not match the Confirm Password field. ');
if ($this->form_validation->run() == TRUE) {
$result['data'] = $this->ion_auth->register($data['identity'], $data['password'], $data['email'], $data['additional_data'], $data['group']);
} else {
$result['message'] = validation_errors();
}
echo json_encode($result);
}
JS:
function submit_form (form_id) {
var url = $(form_id).attr("action");
var formData = {};
$(form_id).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('select[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('textarea[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$.ajax({
type: "POST",
data: {
'formdata': formData
},
url: url,
dataType: 'json',
success: function(result) {
if (result.data) {
console.log(success);
swal({
title: "Success!",
text: "You've done it great!",
type: "success"
},
function(){
location.reload();
});
} else {
$('#error-msg').html(result.message);
}
},
error: function(data) {
swal({
title: "Error!",
text: "Oops, something went wrong. Check and try again.",
type: "error"
});
}
});
}
Note: Form validation are set in config directory. So no issues in form rules. All are running good except I think the jquery that handles the condition.
Edit like below:
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->ion_auth->register($data['identity'],
$data['password'], $data['email'], $data['additional_data'],
$data['group']);
}
Also you have set_message but not set_rules. If you want to use form_validation library, you should set some rules.
Straight to the case.
This is some functions from my model (Student Model):
public function get_exam_data($exam_id){
$this->db->select('exam_id, exam_name, duration');
$this->db->from('exams');
$this->db->where('exam_id', $exam_id);
$result = $this->db->get();
$exam = array();
$examrow = $result->row();
$exam['id'] = $examrow->exam_id;
$exam['name'] = $examrow->exam_name;
$exam['duration'] = $examrow->duration;
return $result;
}
public function start_exam($exam_id, $student_id)
{
$this->db->select('*');
$this->db->from('exam_record');
$exam_newstatus = array(
'student_id' => $student_id,
'exam_id' => $exam_id);
$this->db->set('start_time', 'NOW()', FALSE);
$this->db->insert('exam_record', $exam_newstatus);
//$examrecord_id is autoincrement in mysql exam_record table
$examrecord_id = $this->db->insert_id();
return $examrecord_id;
}
This is a function from the Student Controller:
public function get_student_exam_data()
{
$exam_id = $this->input->post('examId');
$examdata = $this->student_model->get_exam_data($exam_id);
$session = get_session_details();
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode($examdata);
}
This is how I access the $examdata value via Ajax:
jQuery(function()
{
$.ajax({
type : "POST",
url : "../get_exam_data/",
async : false,
data : {"examId": EXAM_ID },
success: function(response)
{
var data = $.parseJSON(response);
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
});
}
I want to be able to pass $examrecord_id from the Student Controller to use it on my jQuery file, just like the $examdata.
I tried to use json_encode() twice on the Controller. Didn't work.
How do I pass $examrecord_id from the Controller to the jQuery file?
Can someone enlighten me, please? Thank you.
Add another index for your $examrecord_id
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode(array(
'examdata' => $examdata,
'examrecord_id' => (!empty($examrecord_id)?$examrecord_id:0)
));
Note the shorthand if condition to check if $examrecord_id is empty
Add a dataType option with 'json' as it's value. Then you can access the data
dataType : 'json',
success: function(response)
{
var data = response.examdata;
alert(response.examrecord_id); // your examrecord_id
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
I want to post data to a controller in CakePHP, but posting with JQuery always results in an error and I can't figure out why.
In my view I have the following method, that posts the data to the controller page
function RenameNode(name, id)
{
$.ajax({
type: "POST",
url: '<?php echo Router::url(array('controller' => 'categories', 'action' => 'rename')); ?>',
data: {
id: id,
name: name
},
success: function(){
}
});
}
My controller method looks like this:
public function rename($id = null, $name = null) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if(!$id)
{
$id = #$this->request->query('id');
}
if(!$name)
{
$name = #$this->request->query('name');
}
if (!$id) {
throw new NotFoundException(__('No id'));
}
$category = $this->Category->findById($id);
if (!$category) {
throw new NotFoundException(__('Invalid category'));
}
$this->autoRender = false;
$this->layout = 'ajax';
if ($this->request->is('post') || $this->request->is('put')) {
$this->Category->id = $id;
$this->request->data['Category']['name'] = $name;
if ($this->Category->save($this->request->data)) {
$this->Session->setFlash(__('The category has been updated.'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to update the category.'));
}
}
}
When I do a post with the jquery method, I keep getting the following error message in my log:
2013-05-20 11:34:25 Error: [NotFoundException] No id
Request URL: /cakephp/categories/rename
Stack Trace:
#0 [internal function]: CategoriesController->rename()
When I comment the request checks for get and post, the controller itself works perfectly when I call it with /categories/rename?id=1&name=test. For some reason the ajax way doesn't work, but I can't figure out why. Any ideas?
Update
I fixed it by changing the following code, now it works perfectly
if(!$id)
{
$id = #$this->request->query('id');
}
if(!$name)
{
$name = #$this->request->query('name');
}
to
if(!$id)
{
$id = #$this->request->data('id');
}
if(!$name)
{
$name = #$this->request->data('name');
}
You are not including the id and/or name in the URL you're posting to;
echo Router::url(array('controller' => 'categories', 'action' => 'rename'));
Will output;
/categories/rename
But you're expecting
/categories/rename/1/test
Or
/categories/rename?id=1&name=test
Change the URL in your AJAX code to something like;
echo Router::url(array(
'controller' => 'categories',
'action' => 'rename',
0 => $this->request->params['pass'][0],
1 => $this->request->params['pass'][1]
));
Which should output the right url, containing the original id and name of the current request (e.g. /categories/rename/123/oldname)
use somthing like that
data = 'name='+name+'&id='id'';
$.ajax({
type:'post',
url: '/categories/rename',
data: data
});
and in controller function
$name=$_POST[name];
$id=$_POST[id];
$('a.ajax-delete-pdf').on('click', function (event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax(
{
url: webroot + 'productos/ajax_eliminar_pdf/' + id ,
async : false,
success: function(respuesta)
{
if(respuesta == 'Borrado')
{
$(this).parent().toggle();
}
}
});
});