Form validation not working when using Ajax - php

I'm currently using ajax to auto-save a form. Codeigniter's form validation function doesn't seems to be working when using ajax. Anyone knows whats the problem here?
PHP:
function autoSavePublicationDetails()
{
$this->form_validation->set_rules('first_author', 'First author', 'required');
if ($this->form_validation->run() == FALSE)
{
$data['message'] = validation_errors();
}
else
{
$newRow = json_decode($_POST['json']);
$claim_id = $_POST['claim_id'];
//$this->publicationClaim_model->updateClaim($newRow,$claim_id);
//$data['claim_id'] = $claim_id;
$data['message'] = "Success";
}
print json_encode($data);
}
Jquery:
setInterval(function(){
var date = new Date();
var dateFormat = date.getFullYear() + "-" + ("0" + date.getMonth()).slice(-2) + "-" + ("0" + date.getDate()).slice(-2) + " " + ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2) + ":" + ("0" + date.getSeconds()).slice(-2);
var claimObj = {
first_author : $('#first_author').val(),
authors : $('#authors').val(),
publication_title : $('#publication_title').val(),
source : $('#source').val(),
publication_submitted : $('#publication_submitted :selected').val(),
research_bank_number : $('#research_bank_number').val(),
research_code_1 : $('#research_code_1 :selected').val(),
research_code_2 : $('#research_code_2 :selected').val(),
research_code_3 : $('#research_code_3 :selected').val(),
issn : $('#issn').val(),
type_of_publication : $('#type_of_publication :selected').val(),
claim_type : $('input[name="claim_type"]').val(),
claim_author : $('input[name="claim_author"]').val(),
claim_date : dateFormat,
user_id : $('input[name="user_id"]').val()
};
var json_data = JSON.stringify(claimObj);
var className;
$.post("autoSavePublicationDetails",
{
'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',
'json' : json_data,
'claim_id' : $('#claim_id').val()
},
function(data,status){
console.log("Status: " + status);
var jsonReturn = $.parseJSON(data);
alert(jsonReturn.message);
if (jsonReturn.message == "Success")
{
className = 'label label-success';
$('#message').addClass(className);
$('#message').text('Data saved.');
}
else
{
className = 'label label-danger';
$('#message').addClass(className);
$('#message').text('Form not saved.');
}
$('#message').fadeIn();
setTimeout(function() {
$('#message').fadeOut();
$('message').removeClass()
}, 1000);
});
}, 10000);
I tried alerting the validation errors. It says that my first_author field is empty even when I already entered the some text inside.
Json that is passed to controller:

instead of $.post() try to use $.ajax()

Related

Jquery Scroll Loading All The Rows At Once And Should Only Load 5 At A Time

I am using the following script to load more, 5 rows at a time from the database, on scroll. All the rows are loading at once on scroll after the initial loads correctly. In realtime, the first 5 load. Then on scroll the last 14 load at once. Like it rushes to the end instead of incrementally loading 5 at a time. I use the same code for a load more button and it works fine. Same PHP file for both. No issue with that. Can anyone see why all the rows are being loaded on scroll instead of 5 at a time.
<script>
//SET NUMBER OF ROWS TO DISPLAY AT A TIME
rowsPerPage = 5;
$(document).ready(function() {
// GETTING DATA FROM FUNCTION BELOW
getData();
window.onscroll = function() {
if ($(window).scrollTop() >= $('#load-container').offset().top + $('#load-container').outerHeight() - window.innerHeight) {
$('#load-more').html('Loading...');
var rowID = Number($("#row-id").val());
var allCount = Number($("#count").val());
rowID += rowsPerPage;
if (rowID <= allCount) {
$("#row-id").val(rowID);
getData();
} else {
$('#load-more').html('End Of Data');
//$('#load-more').html('');
}
}
}
/* REQUEST DATA */
function getData() {
var rowID = $("#row-id").val();
var allCount = $("#count").val();
$('#load-more').html('Loading...');
$.ajax({
url: 'promotions/newest-load-scroll-data-invalid.php',
type: 'post',
data: {
rowID: rowID,
rowsPerPage: rowsPerPage
},
dataType: 'json',
success: function(response) {
setTimeout(function() {
loadData(response)
}, 1000);
},
});
}
/* LOAD DATA TO PAGE */
function loadData(data) {
var dataCount = data.length;
for (var i = 0; i < dataCount; i++) {
if (i == 0) {
var allCount = data[i]['allcount'];
$("#count").val(allCount);
} else {
var promoID = data[i]['promoid'];
var promoNameNewest = data[i]['promoname'];
var promoNameNewestVideo = data[i]['promoname'];
var promoRefNum = data[i]['promorefnum'];
var promoType = data[i]['promotype'];
var theBanner = data[i]['thebanner'];
var email = data[i]['email'];
var customerType = data[i]['customerType'];
if (email == "") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="visitor-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="visitor-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
if (customerType == "p") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="advertiser-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="advertiser-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
}
$('#load-more').html('Loading...');
}
}
});
</script>
I was able to utilize flags to make it work right with a couple other small changes. Appreciate the input, Taplar.

CodeIgniter AJAX JSON validator with form validation

I am trying to make AJAX form validation work in CodeIgniter.
If you have the same title don't add The data from the form always reports as successful, even if the result is negative.
Is there a mistake in my logic?
Save controller:
public function save(){
$options = array();
$data['title'] = $this->input->post('title');
$data['description'] = $this->input->post('description');
$data['sale_price'] = $this->input->post('sale_price');
$data['purchase_price'] = $this->input->post('purchase_price');
$data['add_timestamp'] = time();
$data['options'] = json_encode($options);
$this->form_validation->set_rules("title", "Title", "required|trim|is_unique[product.title]");
$this->form_validation->set_rules("description", "Description", "required|trim");
$this->form_validation->set_rules("sale_price", "Price", "required|trim");
$this->form_validation->set_message(
array(
"required" => "<b>{field}</b> is not null.",
'is_unique' => 'A %s content has already been added in thistitle.!'
)
);
$validate = $this->form_validation->run();
if($validate){
$insert = $this->db->insert('product', $data);
// alert
if($insert){
$alert = array(
"title" => "Success Sir",
"text" => "Content successfully added",
"type" => "success"
);
}else {
$alert = array(
"title" => "Error Sir",
"text" => "Content failed to load content,
"type" => "danger"
);
}
}
JSON, AJAX, jQuery:
function ajax_set_full(type, title, noty, form_id, id) {
// ajax func
ajax_load(base_url + '' + user_type + '/' + module + '/' + type + '/' + id, 'list', 'form');
}
function form_submit(form_id, noty, e) {
var alerta = $('#form'); // alert div for show alert message
var form = $('#' + form_id);
var can = '';
if (!extra) {
var extra = '';
}
form.find('.summernotes').each(function () {
var now = $(this);
now.closest('div').find('.val').val(now.summernote('code'));
});
//var form = $(this);
var formdata = false;
if (window.FormData) {
formdata = new FormData(form[0]);
}
var a = 0;
var take = '';
form.find(".required").each(function () {
var txt = '*' + req;
a++;
if (a == 1) {
take = 'scroll';
}
var here = $(this);
if (here.val() == '') {
if (!here.is('select')) {
here.css({borderColor: 'red'});
if (here.attr('type') == 'number') {
txt = '*' + mbn;
}
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="label label-danger require_alert" >'
+ ' ' + txt
+ ' </span>'
);
}
} else if (here.is('select')) {
here.closest('div').find('.chosen-single').css({borderColor: 'red'});
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="label label-danger require_alert" >'
+ ' *Required'
+ ' </span>'
);
}
}
var topp = 100;
if (form_id == 'product_add' || form_id == 'product_edit') {
} else {
$('html, body').animate({
scrollTop: $("#scroll").offset().top - topp
}, 500);
}
can = 'no';
}
if (here.attr('type') == 'email') {
if (!isValidEmailAddress(here.val())) {
here.css({borderColor: 'red'});
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="require_alert" >'
+ ' *' + mbe
+ ' </span>'
);
}
can = 'no';
}
}
take = '';
});
if (can !== 'no') {
if (form_id !== 'vendor_pay') {
$.ajax({
url: form.attr('action'), // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formdata ? formdata : form.serialize(), // serialize form data
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
console.log(formdata);
var buttonp = $('.enterer');
buttonp.addClass('disabled');
buttonp.html(working);
},
success: function () {
ajax_load(base_url + '' + user_type + '/' + module + '/' + list_cont_func + '/' + extra, 'list', 'first');
if (form_id == 'vendor_approval') {
noty = enb_ven;
}
iziToast.show({
color: 'dark',
icon: 'fa fa-info',
title: 'Bilgi',
message: 'İşlem Başarılı!',
position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
progressBarColor: 'rgb(0, 255, 184)',
/*onOpening: function(){
setTimeout(function(){
window.location.reload(1);
}, 5000);
console.log('Page Refresh!');
},
onClosing: function(){
// console.log('goodbye');
}*/
});
$('.bootbox-close-button').click();
('form_submit_success');
other_forms();
},
error: function (e) {
console.log(e)
}
});
} else {
//form.html('fff');
form.submit();
//alert('ff');
return false;
}
} else {
if (form_id == 'product_add' || form_id == 'product_edit') {
var ih = $('.require_alert').last().closest('.tab-pane').attr('aria-labelledby');
$("[id=" + ih +"]").click();
}
$('body').scrollTo('#scroll');
return false;
}
}
The error message always returns positive.
after run the validation, you need specify the array to be validated
public function save(){
$data = array();
$data['title'] = $this->input->post('title');
$data['description'] = $this->input->post('description');
$data['sale_price'] = $this->input->post('sale_price');
$data['purchase_price'] = $this->input->post('purchase_price');
$data['add_timestamp'] = time();
$this->form_validation->set_rules("title", "Title", "required|trim|is_unique[product.title]");
$this->form_validation->set_rules("description", "Description", "required|trim");
$this->form_validation->set_rules("sale_price", "Price", "required|trim");
$this->form_validation->set_message(
array(
"required" => "<b>{field}</b> is not null.",
'is_unique' => 'A %s content has already been added in thistitle.!'
)
);
$this->form_validation->set_data($data);
$validate = $this->form_validation->run();
You have to call the set_data() method before defining any validation rules.
Ref: https://codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post

How to get ajax value and store in PHP variable?

custom.js file:
$(document).ready(function() {
$("#company_name").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/capms_v2/ca_autocomplete/getcompanyName",
data: {
keyword: $("#company_name").val()
},
dataType: "json",
success: function(data) {
//alert(data);
if (data.length > 0) {
$('#DropdownCompany').empty();
$('#company_name').attr("data-toggle", "dropdown");
$('#DropdownCompany').dropdown('toggle');
} else if (data.length == 0) {
$('#company_name').attr("data-toggle", "");
}
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCompany').append('<li role="displayCountries" ><a role="menuitem DropdownCompany" id=' + value['company_id'] + ' Address1=' + value['company_address1'] + ' Address2=' + value['company_address2'] + ' city=' + value['company_city'] + ' state=' + value['company_state'] + ' pincode=' + value['company_zip'] + ' class="dropdownlivalue">' +
value['company_name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#company_name').val($(this).text());
$('#company_id').val($(this).attr("id"));
// $('#company_address1').val($(this).text());
$('#tableCityID').html($(this).attr("id"));
$('#tableCityName').html($(this).text());
$('#Address1').html($(this).attr("Address1"));
$('#Address2').html($(this).attr("Address2"));
$('#city').html($(this).attr("city"));
$('#state').html($(this).attr("state"));
$('#pincode').html($(this).attr("pincode"));
});
});
I was getting id in span id="tableCityID" but if I store the value and pass the value to mysql it was not fetching the value
$com = '<span id="tableCityID">';
and if I echo the select query
echo $sql="select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '".$com."'";
I get the result with not completed single codes
select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '15
If anybody faces this problem, please help me. Thanks in advance.
just use the </span>
like this
$com = '<span id="tableCityID"></span>';

ajax function doesn't work when referred to from instagram

My function seems to return nothing for the destination element when the link is referred to from Instagram. It works fine if I directly visit the page.
function getTeamsByLeague(league) {
//console.log("League Set: " + league);
$.ajax({
url: "<?php echo SITE_BASE_URL; ?>json.php",
data: {method: "getteamsbyregion", league: league},
success: function (data) {
if (data && data.length > 0) {
$("#destination").empty();
var selected = "";
$.each(data, function (index, item) {
if (item.team == teamSelected) {
selected = " selected";
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
} else {
selected = "";
}
$("#destination").append('<option ' + selected + ' value="' + item.lat + ',' + item.lng + '">' + item.team + '</option>');
if (index == 0) {
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
}
});
}
},
type: "GET",
dataType: "json"
});
}

Returned JSON not displaying a value

I have a jQuery script that returns JSON data and for some reason a specific value is not displayed and I don't know why since all the other properties are displayed fine. The value that is not working correctly is data.code.
$(document).ready(function() {
$(".cos").click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var produs_href = $(this).closest('.productinfo').find('a:first').attr('href');
var id_prod = $(this).data('id');
var color = $(this).closest(".col-sm-4").find(".selected").data("color");
if (typeof color === 'undefined') {
alert ("selecteaza o culoare!");
} else {
$.getJSON(href + '&color=' + color).done(function(data) {
$.each(data, function(key, val) {
$("#cnt").empty();
$("#cnt").append('' + val.cnt + '');
$.ajax({
url: "/engine/shop/produse_cos_popup.php?id=" + id_prod + "&color=" + color,
type: "GET",
datatype: 'json',
success: function(data) {
$('#qty').html('Cantitate: ' + data.qty + '');
$('.nr_prod').html('' + data.qty_total + 'produse în cosul dvs');
$('#nume').html('' + data.nume + '');
$('#pret').html('' + data.pret_total + '');
if (data.poza!='') {
$('.produs_img').html(data.poza);
} else {
$('.produs_img').html('<img class="img-responsive" src="/images/no_photo.jpg">');
}
$('#cod').html('<b>Cod Produs:</b ' + data.code + '');
$('#culoare').html('<b>Culoare:</b> ' + data.culoare + '');
$('#greutate').html('<b>Greutate:</b> ' + data.greutate +'');
$('#viteza').html('<b>Viteza maximă:</b> ' + data.viteza + '');
$('#autonomie').html('<b>Autonomie:</b> ' + data.autonomie + '');
$('#putere').html('<b>Putere motor:</b> ' + data.putere + '');
$('#detalii_prod').modal('show');
}
});
});
});
}
});
});
Here is the JSON returned. As you can see the variable code is there. It displays `Cod Produs: but without the value.
{
"qty": "4",
"poza": "<img class=\"img-responsive\" src=\"images\/trotineta_verde.png\">",
"id": "1",
"nume": "Eco",
"code": "etw1",
"greutate": "10.7 kg",
"viteza": "27 km\/h",
"autonomie": "30 km",
"putere": "350 Watt",
"culoare": "verde",
"pret_total": "37560",
"qty_total": "18"
}
You are not closing the </b
Change
$('#cod').html('<b>Cod Produs:</b ' + data.code + '');
For
$('#cod').html('<b>Cod Produs:</b> ' + data.code + '');

Categories