input text is not validated by codeigniter - javascript

I have a password change form and when submit it only two inputs are validated and input with name "confirm-new-password" is not validated. what is my wrong?
please help me.
HTML and JS CODE
$(function($) {
$.fn.ajaxForm = function(url, data, msgHolderId) {
var self = this;
var result;
return $(self).bind('submit', function(e) {
e.preventDefault();
if (data != null)
data = "&" + $.param(data);
alert(data);
$.ajax({
url: '<?= base_url() ?>' + url,
async: false,
cache: false,
data: $(self).serialize() + data,
type: 'POST',
dataType: 'json',
success: function(response) {
$('#' + msgHolderId).html(response.msg);
}
});
});
}
}(jQuery));
$(document).ready(function() {
$('#password-change-form').ajaxForm('user/settings/password_change', null, 'msg-holder');
});
MY HTML FORM
<form id="password-change-form">
<table class="table table-bordered table-responsive table-condensed table-hover">
<tr>
<td colspan="3" style="background-color: #e8e8e8">Password Update</td>
</tr>
<tr>
<td style="width:20%">Current password</td>
<td style="width:50%"><input type="password" class="form-control" name="current-password" id="current-password" /></td>
<td></td>
</tr>
<tr>
<td style="width:20%">New Password</td>
<td style="width:50%"><input type="password" class="form-control" name="new-password" id="new-password" /></td>
<td></td>
</tr>
<tr>
<td style="width:20%">Confirm new password</td>
<td style="width:50%"><input type="password" class="form-control" name="confirm-new-password" id="confirm-new-password" /></td>
<td></td>
</tr>
<tr>
<td style="width:20%"></td>
<td colspan="2" style="width:50%"><input type="submit" class="btn btn-default" value="ذخیره تغییرات" /></td>
</tr>
</table>
</form>
SERVER SIDE CODE
$this->form_validation->set_rules('current-password', 'A', 'trim|callback_password_check');
$this->form_validation->set_rules('new-password', 'B', 'trim|required|min_length[8]');
$this->form_validation->set_rules('confirm-new-password', 'C', 'trim|matches[new-password]');
if($this->form_validation->run())
$this->Common_db_actions_model->update_data('users' ,array('password' => $hash_new_password) ,array('user_id' => $this->active_user['user_id']));

try this
$this->form_validation->set_rules('password', 'Password', 'required|matches[confirm-new-password]');
$this->form_validation->set_rules('confirm-new-password', 'Password Confirmation', 'required');

Try this code:
$this->form_validation->set_rules('current_pwd', 'Current password','required');
$this->form_validation->set_rules('new_pwd', 'New password' ,'required|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confirm_pwd', 'Confirm password','required|matches[new_pwd]');
Then change your input name.

Related

How to push Json object to Json array using for loop?

I have a html table where onclick dynamically rows added. I need to convert that row textbox values into JSON array.
Note: Ajax must be used because I need to save data to sql server.
Here is my attempt.
$(function() {
$("[id*=btnSave]").click(function() {
$("[id*=data_table] tbody").each(function() {
var arr = [];
var user = {};
for (i = 0; i <= 1; i++) {
user.DueDate = $(this).find('tr:eq(' + i + ') td:eq(0) input').val();
user.DueAmount = $(this).find('tr:eq(' + i + ') td:eq(1) input').val();
arr.push(user); // Json array has every json object value
$.ajax({
async: true,
cache: false,
type: "POST",
url: "Default.aspx/Save",
data: JSON.stringify(user),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Data added successfully.");
alert(JSON.stringify(user)); //Json object value //Alert 2
alert(JSON.stringify(arr)); //Json array value //Alert 3
}
}); //End of ajax
return false;
} //End of for loop
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="3" cellpadding="3" id="data_table" width="50%">
<thead>
<tr>
<th width="30%">Due date</th>
<th width="26%">Amount Due</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td width="30%">
<input type="text" id="Text1" autocomplete="off" placeholder="Due Date" runat="server" />
</td>
<td width="25%">
<input type="text" runat="server" id="new_Amount_1" placeholder="0.00" autocomplete="off" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" value="Add row" id="btnAddRow" />
<input type="button" value="Save" id="btnSave" />
</td>
</tr>
</tfoot>
</table>
I used for loop to get every dynamically added row values.
My output should be like this.
Alert2 Json object format
{"DueDate":"17/09/2019","DueAmount":"100"}
Alert3 Json array format
[{"DueDate":"17/09/2019","AmountDue":"100"},{"DueDate":"18/09/2019","AmountDue":"200"},{"DueDate":"19/09/2019","AmountDue":"300"}]
But in My output Alert3 I am getting first object only
[{"DueDate":"17/09/2019","DueAmount":"100"}]
What I have done wrong? I think for loop is not correct. Please help me with that.
Yes, you can use .serialize() or .serializeArray() and these two functions only runs on a form tag.
In your code if you are adding tr tag each time that you press btnAddRow, your for loop is wrong:
for (i = 0; i <= 1; i++)
Replace with:
for (i = 0; i <= $(this).find('tr').length; i++)
Instead of looping this, you can directly use the serializeArray or serialize if you need a custom format
$("form").on("submit", function(event) {
event.preventDefault();
console.log($(this).serializeArray());
$.ajax({
async: true,
cache: false,
type: "POST",
url: "Default.aspx/Save",
data: JSON.stringify($(this).serializeArray()),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
console.log("Data added successfully.");
}
}); //End of ajax
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<form>
<table cellspacing="3" cellpadding="3" id="data_table" width="50%">
<thead>
<tr>
<th width="30%">Due date</th>
<th width="26%">Amount Due</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td width="30%">
<input type="text" name="Text1" autocomplete="off" placeholder="Due Date" runat="server" />
</td>
<td width="25%">
<input type="text" runat="server" name="new_Amount_1" placeholder="0.00" autocomplete="off" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" value="Add row" id="btnAddRow" />
<input type="submit" value="Save" id="btnSave" />
</td>
</tr>
</tfoot>
</table>
</form>

how to hide datatable rows where code is have "." e.g 1.1, 1.2 through jquery?

I take data of two inputs to another page through ajax. I used these two values in the query and shown the result of the select query in a data table which is return back to success function and shown in the table on the main page.
After that, I want to use a condition that data with "." (accounting->subaccounts) hide unless He clicks a button.
I just need an idea to hide it I can do more. let me show you my code.
This is the button:
<input type="button" id="generate" onclick="getData();" value="Generate"
class="btn btn-block btn-primary btn-sm" />
The div where i shown the table:
<div class="col-lg-12 col-sm-12 col-xs-12 col-md-12" id="tab"></div>
the ajax function:
function getData() {
var date = $("#date").val();
var classId = $("#class").val();
$.ajax({
url: "ajax/getTrailBalanceData.php",
type: "POST",
data: {
"date": date,
"classId": classId,
},
cache: false,
async: false,
success: function (data) {
//alert(data);
$("#tab").html(data);
var row_main_code = $("#main_code").val();
if (row_main_code.indexOf(".") > -1) {
// $("#tbl_row").addClass("hide");
} else {
// $("#tbl_row").removeClass("hide");
// $("#main_code").parents("tr").hide();
// $("#tbl_row").addClass("hide");
// $("#main_code").val("hide");
}
}
});
}
The if(rowmaincode.indexof('.')>-1) condition in "success" I tried but not give desirable result I am confused I don't know why but let me show you the other page code:
<table id="trail_balance_list" class="table table-bordered table-condensed bootstrap-datatable datatable responsive">
<thead id="table_head">
<tr class="bg-success">
<th class=" text-center">Code</th>
<th class=" text-center">Account Title</th>
<th class=" text-center" >Debit</th>
<th class=" text-center" >Credit</th>
<th class=" text-center" >Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr id="tbl_row" class="">
<td><?php echo $row['main_code']; ?><input type="hidden" id="main_code" value="<?php echo $row['main_code']; ?>" /></td>
<td><?php echo $row['account_title']; ?></td>
<td></td>
<td></td>
<td class="text-center"><button class="btn btn-info"><i class="fa fa-arrow-down"></i></button></td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
<tr>
<th><input type="hidden" id="total_credit_input" name="total_credit" value="0" /></th>
<th><input type="hidden" id="total_debit_input" name="total_debit" value="0" /></th>
<td class="bg-warning text-center" id="total_debit">0.00</td>
<td class="bg-warning text-center" id="total_credit" >0.00</td>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
$("#trail_balance_list").dataTable();
});
</script>
the result I get is like : (see image), I want to show only like 1,2,3,4
You have implement a similar idea in your code, hope you can do that. I have added a sample below.
$('body').on('click', '#act_button', function() {
$('#trail_balance_list > tbody > tr').each(function() {
if ($(this).find('td:first').text().indexOf('.') >= 0) {
$(this).hide();
} else {
$(this).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="act_button">hide decimal rows</button>
<table id="trail_balance_list" border="1">
<tbody>
<tr>
<td>1</td>
<td>222</td>
</tr>
<tr>
<td>33.3</td>
<td>444</td>
</tr>
<tr>
<td>555</td>
<td>666</td>
</tr>
<tr>
<td>77</td>
<td>666</td>
</tr>
</tbody>
</table>

Jquery executes Error section by default - Servlet

I am new to Ajax and JQuery. I am attempting to insert data into my database without submitting the form. The data gets inserted into the table but:
I am not able to get either the Error Message or Success Message on My jsp. It Comes as [object Object]
Looks like the success section of the Jquery is not executed at all
My Jquery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {
//On Button Click
$("#countrybutton").click(function () {
//Get Text box values
var country = $("#country").val();
var continent = $("#continent").val();
var region = $("#region").val();
var population = $("#population").val();
var capital = $("#capital").val();
$.ajax({
url: 'do?MOD=BOK&ACT=domcountry&country=' + country + "&continent=" + continent + "&region=" + region + "&population=" + population + "&capital=" + capital,
dataType: "json",
type: "Post",
success: function (result) {
$("#message").text(result);
//Clear Textbox data
$("#country").val('');
$("#continent").val('');
$("#region").val('');
$("#population").val('');
$("#capital").val('');
},
error: function (responseText) {
$("#message").text(responseText);
}
});
});
});
</script>
My JSP
<table width="100%" border="0" align="left" cellpadding="5" cellspacing="1">
<th colspan="5" align="left" scope="col"></th>
<tr>
<td colspan="2" id="message" style="color: red; font-size: 14px;"></td>
</tr>
<tr>
<td> </td>
<td>Country Name</td>
<td style="color: red">*</td>
<td><label>
<input name="country" value="${country}" onkeyup="this.value = this.value.toUpperCase();" type="text" id="country"/>
</label></td>
<td> </td>
<td>Continent Name</td>
<td style="color: red">*</td>
<td><label>
<input name="continent" value="${continent}" onkeyup="this.value = this.value.toUpperCase();" type="text" id="continent"/>
</label></td>
</tr>
<tr>
<td> </td>
<td>Region</td>
<td style="color: red">*</td>
<td><label>
<input name="region" value="${region}" onkeyup="this.value = this.value.toUpperCase();" type="text" id="region"/>
</label></td>
<td> </td>
<td>Population</td>
<td style="color: red">*</td>
<td><label>
<input name="population" value="${population}" type="text" id="population"/>
</label></td>
<td></td>
</tr>
<tr>
<td> </td>
<td>Capital</td>
<td style="color: red">*</td>
<td><label>
<input name="capital" value="${capital}" type="text" id="capital"/>
</label></td>
<td> </td>
</tr>
</table>
</div>
<div>
<table width="100%" border="0" align="left" cellpadding="5" cellspacing="1">
<th colspan="5" align="left" scope="col"></th>
<tr>
<td> </td>
<td><div align="right">
<input type="reset" name="Submit2" value="Reset" class="redButton" />
</div></td>
<td><label>
<input name="Submit" class="redButton" type="button" id="countrybutton" onclick="MM_validateForm('country', '', 'R', 'continent', '', 'R', 'region', '', 'R', 'population', '', 'R',
'capital', '', 'R');
return document.MM_returnValue" value="Submit" />
<td> </td>
</tr>
</table>
And My servlet section:
response.setContentType("application/json");
String country = request.getParameter("country");
String continent = request.getParameter("continent");
String region = request.getParameter("region");
int population = Integer.parseInt(request.getParameter("population"));
String capital = request.getParameter("capital");
String returnMessage;
if (Countries.addCountry(country, continent, region, population, capital)) {
returnMessage = "Record Inserted.";
} else {
returnMessage = "Unable to Insert Record.";
try {
throw new InsertException("Unable to Insert record");
} catch (InsertException ex) {
log.debug(ex.getMessage());
}
}
new Gson().toJson(returnMessage, response.getWriter());
response.sendRedirect("index.jsp");
What am I missing?
Try remove this line:
response.sendRedirect("index.jsp");
and to get exception in Ajax error, you will need set http code 500 in response, add this inside your "else":
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
Servlet final:
response.setContentType("application/json");
String country = request.getParameter("country");
String continent = request.getParameter("continent");
String region = request.getParameter("region");
int population = Integer.parseInt(request.getParameter("population"));
String capital = request.getParameter("capital");
String returnMessage;
if (Countries.addCountry(country, continent, region, population, capital)) {
returnMessage = "Record Inserted.";
} else {
returnMessage = "Unable to Insert Record.";
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
try {
throw new InsertException("Unable to Insert record");
} catch (InsertException ex) {
log.debug(ex.getMessage());
}
}
new Gson().toJson(returnMessage, response.getWriter());

Need to load dialog popup with Database value

I need to open a jquery dialog popup with data loaded from database. I am able to see the result data in controller but not able view the same in dialog popup.
Any help on this pls?
Here is my code:
popup.jsp
<div id="addDeployment" style="display: none">
<table id="addDep">
<tbody>
<tr>
<td width="50%"><label id="AddDeployedCityLab">Deployed City</label></td>
<td width="50%"><input type="text" name="AddDeployedCity" id="AddDeployedCity" value="" /></td>
</tr>
<tr>
<td width="50%"><label id="AddDeployedStateLab">Deployed State</label></td>
<td width="50%"><input type="text" name="AddDeployedState" id="AddDeployedState" value=""></td>
</tr>
<tr>
<td width="50%"><label id="AddDeployedTerrirotyLab">Territory Name</label></td>
<td width="50%"><input type="text" name="AddDeployedTerriroty" id="AddDeployedTerriroty" value=${territoryName}></td>
</tr>
<tr>
<td width="50%"><label id="AddDeployedEffDateLab">Effective Date</label></td>
<td width="50%"><input type="text" name="AddDeployedEffDate" id="AddDeployedEffDate" value=${effectiveDate}></td>
</tr>
<tr>
<td width="50%"><label id="AddDeployedExpDateLab">Expiry Date</label></td>
<td width="50%"><input type="text" name="AddDeployedExpDate" id="AddDeployedExpDate" value=${expiryDate}></td>
</tr>
<tr>
<td width="50%"><label id="AddDeployedZipLab">Zipcodes</label></td>
<td width="50%">
<select id="AddDeployedZip" multiple="multiple">
</select>
</td>
</tr>
</tbody>
</table>
</div>
jQuery Code:
$("#addDeploymentBut").click(function(){
var usw=$("#DeployGrid").jqGrid("getCell",deployVal,"usw");
var deploymentTyp=$("#DeployGrid").jqGrid("getCell",deployVal,"deploymentTyp");
var territory=$("#DeployGrid").jqGrid("getCell",deployVal,"territoryName");
var effDate=$("#DeployGrid").jqGrid("getCell",deployVal,"effectiveDate");
var expDate=$("#DeployGrid").jqGrid("getCell",deployVal,"expiryDate");
var passParam="/Scheduling/deploymentAddModal?deployType="+deploymentTyp+"&usw="+usw+"&territory="+territory+"&effDate="+effDate+"&expDate="+expDate;
$("#addDeployment").dialog({
title: "Add Deployment",
width: 430,
height: 320,
modal: true,
open: function () {
/*$("#addDeployment").load(passParam,function(event){
event.preventDefault();
}); */
$.ajax({
type : "POST",
url : passParam,
async : false,
dataType: "json",
success : function(data) {
$("#addDeployment").load("deploymentAddModal.jsp");
}
});
},
buttons: {
Close: function() {
$("#addDeployment").dialog('close');
}
}
});
})
another jsp
<input type="button" id="addDeploymentBut" value="Add" />
look at id="addDeployment" I see that it is always display:none
remove display:none thru javascript. like display:inline
document.getElementById('addDeployment').style.display = 'block';
document.getElementById('addDeployment').style.display = 'inline';

Typeahead Bootstrap does not work in remote

I have the following problem. Using Bootstrap Typeahead in a field on a form. When i run it on localhost it works perfect, but when i run it from another PC in network does not work. What can be happening?
JavaScript:
$(function() {
$("#typeahead").typeahead({
source: function (query, process) {
$.ajax({
url: 'data.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
}
});
}
});});
PHP:
if (isset($_POST['query'])) {
require_once('conexion.php');
$query = $_POST['query'];
$sql = "SELECT * FROM tab_medicinas_2 WHERE descripcion LIKE '%".$query."%'";
$res = mysql_query($sql) or die(mysql_error());
while($fila = mysql_fetch_assoc($res))
{
$return[] = $fila['descripcion']." (".$fila['um'].")";
}
echo json_encode($return); }
HTML:
<div id="tab4" class="tab-content-1">
<table class="table table-bordered">
<tr>
<td width="28%">Denominación según DCI, especificaciones técnicas, unidad de manejo</td>
<td width="24%">Dosis</td>
<td width="24%">Duración del tratamiento</td>
<td width="8%">Cant. Req.</td>
<td width="16%">Indicación Específica</td>
</tr>
<tr>
<td width="28%">
<input name="descripcion" class="span4" id="typeahead" type="text" data-provide="typeahead" />
</td>
<td width="24%">
<input name="dosis" class="span3" id="dosis" type="text" />
</td>
<td width="24%">
<input name="duracion" class="span3" id="duracion" type="text" />
</td>
<td width="8%">
<input name="cantidad" class="span1" id="cantidad" type="text" />
</td>
<td width="16%">
<input name="indicacion" class="span2" id="indicacion" type="text" />
</td>
</tr>
</table>

Categories

Resources