POST Ajax request - javascript

I'm working on an old project that wasn't developed by me at first. I need to make an Ajax request so that the values contained in the fields (more on that later) be sent to a php script which will then return their values into the correct td.
Here is the JavaScript/jQuery code.
$(function ()
{
$('form').on('submit', function (e)
{
e.preventDefault();
$.ajax
({
type: 'post',
url: 'envoi_dispo_semaine.php',
data: $('form').serialize(),
success: function ()
{
alert('Le planning a été mis à jour.');
}
});
});
jQuery(document).ready(function date()
{
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var today = new Date(this.getFullYear(),this.getMonth(),this.getDate());
var dayOfYear = ((today - onejan +1)/86400000);
return Math.ceil(dayOfYear/7)
};
var today = new Date();
var t = today.getWeek();
})
jQuery(document).ready(function()
{
jDispo = {};
jCharge = {};
jSolde = {};
var d = 0;
var c = 0;
var s = 0;
jQuery('.DISPO').each(function()
{
jDispo[d] = jQuery(this).val();
d++;
});
jQuery(".CHARGE").change(function()
{
var totalCharge = 0;
if(jQuery(".CHARGE").length > 0)
{
jQuery(".CHARGE").each(function()
{
jCharge[c] = jQuery(this).val();
c++;
totalCharge = totalCharge + jQuery(this).val();
});
}
jQuery('.SOLDE').each(function()
{
jSolde[s] = jQuery(this).val();
$.ajax(
{
type:'post',
url:'check_charge.php',
data:{charge : jCharge[s],solde : jSolde[s],dispo : jDispo[s],action:"update_site"},
success: function()
{
$('jSolde[s]').empty();
$('jSolde[s]').append();
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
s++;
});
});
});
$(document).ready(function()
{
if ($("#tab_projets table tbody tr:eq(2) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(2) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(2) td:contains('-')").css('font-color', 'black');
}
if ($("#tab_projets table tbody tr:eq(5) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(5) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(5) td:contains('-')").css('font-color', 'black');
}
if ($("#tab_projets table tbody tr:eq(8) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(8) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(8) td:contains('-')").css('font-color', 'black');
}
});
});
And here is check_charges.php:
<?php
include('connexion_db.php');
$charge = $_POST['charge'];
$dispo = $_POST['dispo'];
$solde = $_POST['solde']; //I'll need this one later on.
$res = $dispo - $charge;
echo $res;
?>
I also have some php code that allows me to generate a table (it's in the same file as the javascript):
<thead>
<?php
echo " <td colspan=2>Semaine n°</td>
<td>Retard</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
echo "<form action=\"envoi_dispo_semaine.php\" method=\"post\">
<td>
<input type=\"hidden\" name=\"semaine_id\" value=\"".$i."\" />".$i."</td>";
}
?>
</thead>
<tbody>
<?php
foreach($users as &$myUser)
{
echo " <tr class=".$myUser.">
<td width=66% rowspan=3><input type=\"hidden\" name=\"login\" value=\"".$myUser."\" onblur=\"updateCharge\"/>".$myUser."</td>
<td width=34%>Disponibilité</td>
<td rowspan=3></td>
";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$req = "
SELECT Nb_max_jours FROM Dispo_par_semaine WHERE login = '".$myUser."' AND semaine_id = ".$i;
$query = requete_is_plancharges($req);
$row = mysql_fetch_row($query);
$affichageDispo = $row[0];
if ($affichageDispo == "")
{
$affichageDispo = 3;
}
echo "
<td>
<input class=\"DISPO\" type=\"number\" name=\"disponibilite[]\" value=".$affichageDispo." min=\"0\" max=\"5\" step=\"0.5\" class=\"input\"/>
</td>
";
}
echo"
</tr>
<tr class=".$myUser.">
<td width=34%>Charge</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$reqTache = "
SELECT tache_id
FROM Tache
WHERE ebi_id = ".$ebi."
AND demande_id = ".$demande."
AND action_id = ".$action;
$resultatTache_id = requete_is_plancharges($reqTache);
$maTache = mysql_fetch_object($resultatTache_id);
$req_Charge = "
SELECT COUNT(charge) as charge_tache
FROM Charge_par_tache
WHERE tache_id =".$maTache->tache_id.
" AND semaine_id =".$i.
" AND login = '".$myUser."'";
$resultat_requete_Charge = mysql_fetch_object(requete_is_plancharges($req_Charge));
if ($resultat_requete_Charge->charge_tache > 0)
{
$req = "
SELECT Charge_par_tache.charge
FROM Charge_par_tache, Tache
WHERE Charge_par_tache.tache_id = Tache.tache_id
AND Tache.ebi_id = ".$ebi."
AND Tache.demande_id = ".$demande."
AND Tache.action_id = ".$action."
AND Charge_par_tache.login = '".$myUser."'
AND Charge_par_tache.semaine_id = ".$i;
$Charge = mysql_fetch_object(requete_is_plancharges($req));
} else
{
$Charge->charge = "";
}
echo " <input type = \"hidden\" name = \"tache_id\" value=".$maTache->tache_id.">
<td class=\"CHARGE\">";
$query = requete_is_plancharges($req);
$row = mysql_fetch_array($query);
$affichageCharge = $row[0];
echo " <input class=\"CHARGE\" type=\"number\" name=\"charge[]\" value=".$Charge->charge." min=\"0\" step=\"0.5\"/>
</td>";
}
echo"
</tr>
<tr class=".$myUser.">
<td width=34%>Solde</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$req1 = "
SELECT charge FROM Charge_par_tache WHERE login = '".$myUser."' AND semaine_id = ".$i;
$req2 = "
SELECT Nb_max_jours FROM Dispo_par_semaine WHERE login = '".$myUser."' AND semaine_id = ".$i;
$query1 = requete_is_plancharges($req1);
$row1 = mysql_fetch_row($query1);
$query2 = requete_is_plancharges($req2);
$row2 = mysql_fetch_row($query2);
$solde=$row2[0]-$row1[0];
echo "<td class=\"SOLDE\"><input type=\"hidden\" class=\"SOLDE\" value=".$solde."/> ".$solde."</td>";
}
?>
</tr>
<?php
}
?>
</tbody>
</table>
<p><input type="submit" name="submit" value="Mise à jour"></p>
</form>
The problem is that I can't seem to retrieve $res. I'm just starting Ajax so I really don't know what to do, and couldn't find the answer on the Internet as I use a js array to store my values.

If I understand your problem you want to get the response value of "check_charges.php", that it is the $res value, isn't it? The value will be returned in the first parameter of success function of your ajax.
Your code:
jQuery('.SOLDE').each(function()
{
jSolde[s] = jQuery(this).val();
$.ajax(
{
type:'post',
url:'check_charge.php',
data:{charge : jCharge[s],solde : jSolde[s],dispo : jDispo[s],action:"update_site"},
success: function(data)
{
// Store where you want the data value
alert('res value: ' + data);
$('jSolde[s]').empty();
$('jSolde[s]').append();
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
s++;
});
I hope I have helped you.

Related

How to store data from html page to the database?

I'm trying to store star rating data though HTML page in database using ajax, php and JavaScript. For some reason it's not working, I've posted all the codes below.
Is there any other option to make star rating dynamic in html page.
here is index.html code
<html>
<body>
<div class="py-2">
<input name="rating" value="0" id="rating_star" type="hidden" postID="1" />
<span class="overall-rating pl-2" property="aggregateRating" typeof="AggregateRating"> (Average Rating <span id="avgrat" property="ratingValue"></span> Based on <span id="totalrat" property="ratingCount"></span> Reviews) <span id="msg"></span> </span> </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="rating.js"></script>
</body>
</html>
here is rating.js code
(function ($) {
$.fn.rating_widget = function (options) {
var settings = $.extend({
starLength: "5",
initialValue: "0",
imageDirectory: "http://softhubs.website/img/star.png",
inputAttr: null
}, options);
var el = $(this);
var initVal = settings.initialValue;
var avgVal = parseInt($("#avgrat").text());
var ul = $("<ul>");
ul.addClass("rating_widget");
for (var i = 1; i <= settings.starLength; i++) {
if (i <= avgVal) {
ul.append('<li style="background-image:url(' + settings.imageDirectory + '/star.png);background-position:0px -28px;"><span>' + i + '</span></li>');
} else {
ul.append('<li style="background-image:url(' + settings.imageDirectory + '/star.png)"><span>' + i + '</span></li>');
}
}
ul.insertAfter(el);
el.next("ul").children("li").hover(function () {
$(this).parent().children("li").css('background-position', '0px 0px');
var a = $(this).parent().children("li").index($(this));
$(this).parent().children("li").slice(0, a + 1).css('background-position', '0px -28px');
}, function () {
if (initVal == "") {
$(this).children("li").slice(0, initVal).css('background-position', '0px 0px');
} else {
$(this).children("li").css('background-position', '0px 0px');
$(this).children("li").slice(0, initVal).css('background-position', '0px -28px');
}
});
el.next("ul").children("li").click(function () {
var a = $(this).parent().children("li").index($(this));
var attrVal = (settings.inputAttr != '') ? el.attr(settings.inputAttr) : '';
initVal = a + 1;
ajaxPostRating(initVal, attrVal);
});
function ajaxPostRating(val, attrVal) {
$.ajax({
type: 'POST',
url: 'rating.php',
data: 'postID=' + attrVal + '&ratingPoints=' + val,
dataType: 'json',
success: function (data) {
if (data.status == "ok") {
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_Number);
} else if (data.status == "no") {
$('#msg').text("You are not allow to rate again.");
$("#msg").addClass("text-danger");
} else {}
},
error: function (xhr) {
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
}
}
}(jQuery));
$(function () {
$("#rating_star").rating_widget({
inputAttr: "postID"
});
});
here is rating.php code
<?php
include_once 'db.php';
if(!empty($_POST['ratingPoints'])){
$postID = $_POST['postID'];
$ratingNum = 1;
$ratingPoints = $_POST['ratingPoints'];
//Check the rating row with same post ID
$prevRatingQuery = "SELECT * FROM post_rating WHERE post_id = ".$postID;
$prevRatingResult = $db->query($prevRatingQuery);
if($prevRatingResult->num_rows > 0):
$prevRatingRow = $prevRatingResult->fetch_assoc();
$ratingNum = $prevRatingRow['rating_number'] + $ratingNum;
$ratingPoints = $prevRatingRow['total_points'] + $ratingPoints;
//Update rating data into the database
$query = "UPDATE post_rating SET rating_number = '".$ratingNum."', total_points = '".$ratingPoints."', modified = '".date("Y-m-d H:i:s")."' WHERE post_id = ".$postID;
$update = $db->query($query);
else:
//Insert rating data into the database
$query = "INSERT INTO post_rating (post_id,rating_number,total_points,created,modified) VALUES(".$postID.",'".$ratingNum."','".$ratingPoints."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
$insert = $db->query($query);
endif;
//Fetch rating deatails from database
$query2 = "SELECT rating_number, FORMAT((total_points / rating_number),1) as average_rating FROM post_rating WHERE post_id = ".$postID." AND status = 1";
$result = $db->query($query2);
$ratingRow = $result->fetch_assoc();
if($ratingRow){
$ratingRow['status'] = 'ok';
}else{
$ratingRow['status'] = 'err';
}
//Return json formatted rating data
echo json_encode($ratingRow);
}
?>
db.php
<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'post_rating';
$conn = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);
?>
rating.sql
CREATE TABLE IF NOT EXISTS `post_rating` (
`rating_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`rating_number` int(11) NOT NULL,
`total_points` int(11) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1 = Block, 0 = Unblock'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
it is not working, can anyone guide me to resolve this problem?

I can't save specific selected value. it saved all data from database

i am inserting multiple data. what happen is when i select a project from drop down list. it save all data from selection. please check the image below first
function sample($con){
$select = "SELECT * FROM project_tbl";
$select_result = mysqli_query($con,$select);
if (mysqli_num_rows($select_result)> 0) {
while ($row = mysqli_fetch_assoc($select_result)) {
echo "<option value=".$row['project_name'].">" .$row['project_name']."</option>";
}
}
}
*html codes (i used drop down list to populate data from database)
<td class="pro">
<select class="pro">
<option value=""><?php sample($con); ?></option>
</select>
</td>
*ajax codes (adding, saving and removing)
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td class='pro'><select class='pro'><option value=''><?php sample($con); ?></option></select></td>";
html_code += "<td contenteditable='true' class='desc'></td>";
html_code += "<td contenteditable='true' class='comp'></td>";
html_code += "<td contenteditable='true' class='entry'></td>";
html_code += "<td contenteditable='true' class='remarks'></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-outline-danger btn-xs remove' title='remove'><i class='fa fa-times' aria-hidden='true'></i></button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var desc = [];
var pro = [];
var comp = [];
var entry = [];
var remarks = [];
$('.desc').each(function(){
desc.push($(this).text());
});
$('.pro').each(function(){
pro.push($(this).text());
});
$('.comp').each(function(){
comp.push($(this).text());
});
$('.entry').each(function(){
entry.push($(this).text());
});
$('.remarks').each(function(){
remarks.push($(this).text());
});
$.ajax({
url:"insert_inspection.php",
method:"POST",
data:{desc:desc, pro:pro, comp:comp, entry:entry, remarks:remarks},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
$('select').prop('selectedIndex',0);
for(var i=2; i<= count; i++){
$('tr#'+i+'').remove();
}
}
});
});
});
Here is what happen when I save.
database
I am new in PHP.
insert_inspection.php
<?php
$con = mysqli_connect("localhost", "root", "", "pms");
if (isset($_POST["desc"])){
$desc = $_POST["desc"];
$pro = $_POST["pro"];
$comp = $_POST["comp"];
$entry = $_POST["entry"];
$remarks = $_POST["remarks"];
$query = '';
for($count = 0; $count<count($desc); $count++){
$desc_clean = mysqli_real_escape_string($con, $desc[$count]);
$pro_clean = mysqli_real_escape_string($con, $pro[$count]);
$comp_clean = mysqli_real_escape_string($con, $comp[$count]);
$entry_clean = mysqli_real_escape_string($con, $entry[$count]);
$remarks_clean = mysqli_real_escape_string($con, $remarks[$count]);
if($desc_clean != '' && $pro_clean != '' && $comp_clean != '' && $entry_clean != '' && $remarks_clean != ''){
$query .= 'INSERT INTO `inspection_tbl`(`description`, `project_name`, `completion`, `entry`, `remarks`) VALUES("'.$desc_clean.'", "'.$pro_clean.'", "'.$comp_clean.'", "'.$entry_clean.'", "'.$remarks_clean.'");
';
}
}
if($query != ''){
if(mysqli_multi_query($con, $query)){
echo 'Item Data Inserted';
}else{
echo 'Error';
}
}else{
echo 'All Fields are Required';
}
}
?>
it is saved as such because your select element only has one option value
modify it from:
<td class="pro"> <select class="pro"> <option value=""><?php sample($con); ?></option> </select> </td>
to:
<td class="pro">
<select class="pro">
<option value=""></option>
<?php sample($con); ?>
</select>
</td>
and modify your select element handler to push only your selected item
something like this:
$('.pro').each(function(){
if($(this).prop("selected")) {
pro.push($(this).text());
}
});
or modify this part to something like:
$(".pro > option:selected").each(function(){
pro.push($(this).text());
});

Cloned elements' events corresponding to all elements in the form

I successfully cloned my table rows, which has values retrieved from database. However I have few issues with it.I used class for all the elements as clone will duplicate IDs.No the problem raises because it unable to target each element uniquely. WHat's the way to do make each element / row unique here?
How the functions work:
When first select box selected, item for that selected id would appear in the next column.Followed by price textbox and quantity textbox. WHen both are filled up, last textbox for total amount would automatically appear.
Issues with the cloning are:
* WHen select box selected from the first/original row, all cloned items are updated with the value.Same goes for amount textbox and vise-versa.
My script:
<script>
var harga;
var qty;
$("input[name^=harga]").on("keyup", function () {
alert($(this).attr("id"));
console.log($(this).val());
harga = $(this).val();
});
$(".qty").on("keyup", function () {
console.log($(this).val());
qty = $(this).val();
var amount = harga * qty;
$(".amount").val(amount);
});
$(document).ready(function () {
$(".sub_item").hide();
$('.gr').change(function () {
var gr_id = $(this).find('option:selected').val();
console.log(gr_id);
var agency_id = '<?php echo $_SESSION['
agency_id
'];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path + "get-item.php?group=" + gr_id + "&agency=" + agency_id, //Relative or absolute path to response.php file
data: data,
success: function (data) {
$(".sub_item").show();
$(".it_id").empty();
for (i = 0; i < data.length; i++) {
$(".it_id").append("<option value='" + data[i].item_id + "'>" + data[i].item_name + "</option>");
}
if (data.length == "") {
$(".it_id").append("<option>No items found</option>");
}
console.log(data);
}});//end success
/*show branch ends*/
});
});
$("#more_items").on("click", function () {
alert("Hi");
$(".clone_this").clone(true, true).insertBefore("#last_e");
});
$(function () {
$("#hide1").hide();
$("#hide2").hide();
$("#hide3").hide();
$('#faktor').change(function () {
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide1").show();
} else {
$("#hide1").hide();
}
});
$('#insurance').change(function () {
$("#hide2").show();
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide2").show();
} else {
$("#hide2").hide();
}
});
$('#bon').change(function () {
$("#hide3").show();
var val = $(this).val();
//alert($(this).val());
if ($.trim(val) == 1) {
$("#hide3").show();
} else {
$("#hide3").hide();
}
});
});
</script>
Form
<form action="#" method="POST" id="submit_item">
<input type="text" name="contract_id" value="" id="contract_id2"/>
<table>
<tr>
<th>Group Item</th>
<th>Nama Item</th>
<th>Harga</th>
<th>Kuantiti</th>
<th>Amount</th>
</tr>
<tr class="clone_this">
<td>
<select name='group' style="width:80px;" class="gr">
<option>Choose group</option>
<?php
$group = $agency->show_all_group();
foreach ($group as $k => $v) {
$i = 0;
$i++;
?>
<option value="<?php echo $v['group_id'] ?>"><?php echo $v['group_name'] ?></option>
<?php
}
?>
</select>
</td>
<td class="sub_item">
<select name='item' style="width:100px;" class="it_id">
</select>
</td>
<td><input type="text" name="harga_<?php echo $i; ?>[]" id="<?php echo $i; ?>" value="" class="harga"/></td>
<td>
<input type='text' size='2' value="" name='qty[]' class='qty'/>
</td>
<td><input type="text" name="amount[]" class="amount" value=""/></td>
</tr>
<tr id="last_e">
<td colspan="3"><input type="submit" name="submit" value="Next" id="item_s"/></td>
<td><input type="button" value="Add more items" id="more_items"/></td>
</tr>
</table>
</form>
You need find the relative elements to update so
$(document).ready(function () {
$('#submit_item').on('keyup', '.qty, .harga', function () {
var $tr= $(this).closest('tr');
$tr.find('.amount').val($tr.find('.harga').val() * $tr.find('.qty').val() || 0)
})
$(".sub_item").hide();
$('#submit_item').on('change', '.gr', function () {
var $this = $(this),
$tr = $this.closest('tr'),
gr_id = $this.find('option:selected').val(),
$subitem = $tr.find('.sub_item'),
$it_id = $tr.find('.it_id');
var agency_id = '<?php echo $_SESSION['agency_id'];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path+"get-item.php?group="+gr_id+"&agency="+agency_id, //Relative or absolute path to response.php file
data: data,
success: function (data) {
$subitem.show();
$it_id.empty();
for (i = 0; i < data.length; i++) {
$it_id.append("<option value='" + data[i].item_id + "'>" + data[i].item_name + "</option>");
}
if (data.length == "") {
$it_id.append("<option>No items found</option>");
}
console.log(data);
}
}); //end success
/*show branch ends*/
});
});
Demo: Fiddle

AJAX success can't populate data to table HTML

I use ajax to filter data on the table. But when success call, data didn't show on the table. Data on the table disappear.
This my script code :
$(document).ready(function() {
$("#inputJenis").change(function() {
var key = $(this).val();
var jenis_semester = 'key=' + key;
$.ajax({
type: "POST",
url: '<?php echo base_url("search/filter") ?>',
data: jenis_semester,
dataType: 'json',
success: function(data) {
$('table tbody').html(data);
},
error: function(XMLHttpRequest) {
alert(XMLHttpRequest.responseText);
}
});
});
});
This is my controller :
public function filter()
{
$this->load->helper('url');
$key = $this->input->post('key');
if ( $key == 'Ganjil' ) {
$this->load->model('filter_model', 'filter');
$data['semester'] = $this->filter->getGanjil($key);
} else {
$this->load->model('filter_model', 'filter');
$data['semester'] = $this->filter->getGenap($key);
}
$this->load->view('tambah_semester', $data);
echo json_encode($data);
}
This is my model :
public function getGanjil($key)
{
$sql = "SELECT * FROM tahunajaran WHERE jenis = 'Ganjil'";
$data = $this->db->query($sql);
$index = 1;
foreach ($data->result() as $row) {
$dataSemester[$index] = array('id_tahun_ajaran' =>$row->id_tahun_ajaran,
'awal_semester' =>$row->awal_semester ,
'akhir_semester'=> $row->akhir_semester,
'tahun_ajaran'=>$row->tahun_ajaran,
'jenis'=>$row->jenis,
'nama_semester'=>$row->nama_semester );
$index++;
}
return $dataSemester;
}
public function getGenap($key)
{
$sql = "SELECT * FROM tahunajaran WHERE jenis = 'Genap'";
$data = $this->db->query($sql);
$index = 1;
foreach ($data->result() as $row) {
$dataSemester[$index] = array('id_tahun_ajaran' =>$row->id_tahun_ajaran,
'awal_semester' =>$row->awal_semester ,
'akhir_semester'=> $row->akhir_semester,
'tahun_ajaran'=>$row->tahun_ajaran,
'jenis'=>$row->jenis,
'nama_semester'=>$row->nama_semester );
$index++;
}
return $dataSemester;
}
I want to show data on the table HTML
<table class="footable table table-striped" data-page-size="10">
<thead>
<tr>
<td id="colNomer">Id</td>
<td id="colNama">Nama</td>
<td id="colTanggal">Awal semester</td>
<td id="colTanggal">Akhir semester</td>
<td id="colTanggal">Tahun ajaran</td>
<td id="colNama">Jenis</td>
<td id="colAksi">Aksi</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
May we fill table on the success call ajax. This is the pict
the data can't populate on the table
I would separate your controller methods, one for AJAX call, the other for your normal view like so:
public function doFilter($key) {
$this->load->helper('url');
$this->load->model('filter_model', 'filter');
if ($key == 'Ganjil') {
$data['semester'] = $this->filter->getGanjil($key);
} else {
$data['semester'] = $this->filter->getGenap($key);
}
return $data;
}
public function getFilterJson() {
$key = $this->input->post('key');
$data = $this->doFilter($key);
echo json_encode($data);
}
public function filter() {
$key = $this->input->post('key');
$data = $this->doFilter($key);
$this->load->view('tambah_semester', $data);
}
you also need to pass an object to your AJAX call and add the new URL we created in the controller, I would also use jquery's $.post() , so change your JS like this:
$(document).ready(function() {
$("#inputJenis").change(function() {
$('table tbody').empty();//this will make sure the table is empty first
var key = $(this).val();
var postdata = {key: key};
var url = '<?php echo base_url("search/getFilterJson") ?>';
$.post(url, postdata, function(result) {
console.log(result);
if (result) {
var obj = JSON.parse(result);
$.each(obj, function(key, line) {
var elem = '<tr>\n\
<td>' + line.id + '</td>\n\
<td>' + line.Nama + '</td>\n\
<td>' + line.Awal + '</td>\n\
<td>' + line.Akhir + '</td>\n\
<td>' + line.Tahun + '</td>\n\
<td>' + line.Jenis + '</td>\n\
<td>' + line.Aksi + '</td>\n\
</tr>';
$('table tbody').append(elem);
});
} else {
//your error code
}
});
});
});
And your model, has too much going on. You should use Codeigniter's functions, like this:
public function getGanjil($key) {
$this->db->select("*");
$this->db->from("tahunajaran");
$this->db->where("jenis", "Ganjil");
$data = $this->db->get();
return $data->result_array();
}
public function getGenap($key) {
$this->db->select("*");
$this->db->from("tahunajaran");
$this->db->where("jenis", "Genap");
$data = $this->db->get();
return $data->result_array();
}

how to handle scroll up and scroll down with ajax request?

Here I am uploading this link http://harvey.binghamton.edu/~rnaik1/myForm.html where you can see how my scroll up n down button is working in javascript but now I am working with Ajax request to a php script on the server to retrieve all of the data from the database table.
Here is the link for the work i have done:http://harvey.binghamton.edu/~rnaik1/myScrollform.html
Everything is working fine for me except scroll up and scroll down button.
Once you add 5 records in a list after entering 6th record it will show latest 5 records.
I want to make the scrollup and down button working for myScrollform.html in the same way as in myForm.html. Any help would be helpful to me and appreciated.
Here is my code:
<html>
<head>
<title>My Scrolling Data Form</title>
<script src="./jquery-1.11.0.min.js"></script>
</head>
<body bgcolor="silver">
<center><h1>My Scrolling Data Form</h1>
<div id="scrollbar">
<input type="button" name="up" id="scrollup" value="Scroll Up" >
<input type="button" name="up" id="scrolldown" value="Scroll Down">
</div>
<div id="mydata" style="height: 200px; overflow-y: scroll">
Currently we have no data
</div>
<hr>
<div id="addformdata">
<form name="addForm" >
To add data to the list, fill in the form below and click on "Add"
<br>
<td><input type="text" id="name" name="namei" value=""></td>
<td><input type="text" id="ssn" name="ssni" value="" ></td>
<td><input type="text" id="date" name="birthi" value="" ></td>
<td><input type="text" id="currency" name="xxxxi" value=""></td>
<input type="button" name="add" value="Add" onclick="validateForm(); return false;">
</form>
</div>
</center>
</body>
</html>
<script type="text/javascript">
// Arrays to store values
var name_Array=new Array();
var ssn_Array=new Array();
var date_Array=new Array();
var currency_Array=new Array();
var Index = 0;
var first = 0;
var last = 0;
var scrolled = 0;
var random_Array=new Array();
$(document).ready(function(){
fetchdata();
$("#scrollup").on("click" ,function(){
// alert('hi');
// scrolled=scrolled+100;
$("#mydata").animate({
scrollTop: 0
}, 800);
});
$("#scrolldown").on("click" ,function()
{
// console.log($elem.height());
$("#mydata").animate({
scrollTop: 5000
}, 800);
});
});
function deleteRecord(id)
{
if(confirm('Are you Sure you Want to delete this record')){
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"action": "delete",
"id": id
},
success:function(data)
{
fetchdata()
console.log('success');
}
});
}
}
function fetchdata()
{
// var scrolled=0
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"action": "fetch"
},
success:function(data)
{
$("#mydata").html('')
$("#mydata").html(data);
console.log('success');
}
});
}
function validateForm()
{
var name = document.getElementById("name");
var ssn = document.getElementById("ssn");
var date = document.getElementById("date");
var currency = document.getElementById("currency");
var error = "";
//Name validation
if(name.value=="")
{
//Check for empty field
name.focus();
error = "Please Enter Name\n";
}
else
{ //format specifier
var letters = /^[a-zA-Z_ ]+$/;
//Check for format validation
if(!name.value.match(letters))
{
name.focus();
error = error + "Name contains only characters and spaces\nPlease Renter Name\n";
}
}
//Date validation
if(date.value=="")
{
//Check for empty field
date.focus();
error = error + "Please Enter Date\n";
}
else
{ //format specifier
var date_regex = /^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$/;
//check for format validation
if(!date.value.match(date_regex))
{
date.focus();
error = error + "Date must be in mm/dd/yyyy format\nPlease Renter Date\n";
}
}
//SSN validation
if(ssn.value=="")
{
//check for empty field
ssn.focus();
error = error + "Please Enter SSN\n";
}
else
{
//format specifier
var numbers = /^\d{3}((-?)|\s)\d{2}((-?)|\s)\d{4}$/g;
//check format validation
if(!ssn.value.match(numbers))
{
ssn.focus();
error = error + "SSN must be in xxx-xx-xxxx format\nPlease Renter SSN\n";
}
}
//Currency validation
if(currency.value=="")
{
//check for empty field
currency.focus();
error = error + "Please Enter Currency\n";
}
else
{
//format specifier
var pattern = /^(\$)\d+(\.\d{1,3})?$/g ;
//check for format validation
if(!currency.value.match(pattern))
{
currency.focus();
error = error + "Currency must be in $xx.xxx format\nPlease Renter Currency\n";
}
}
if(error)
{
alert(error);
return false;
}
else
{
var name = document.getElementById("name").value;
var ssn = document.getElementById("ssn").value;
var date = document.getElementById("date").value;
var currency = document.getElementById("currency").value;
console.log(name)
adduser(name,ssn,date,currency);
return true;
}
}
function insertToList()
{
// call a function to validate the fields
var valid_function = validateForm();
if(valid_function == false)
{
return false;
}
else
{
//get the entered values from fields
var name = document.getElementById("name");
var ssn = document.getElementById("ssn");
var date = document.getElementById("date");
var currency = document.getElementById("currency");
// push the values in the array
name_Array.push(name.value);
ssn_Array.push(ssn.value);
date_Array.push(date.value);
currency_Array.push(currency.value);
// generate and push random number in the array to search the record in array and then delete that record.
random_Array.push(Math.floor((Math.random()*100)+1));// http://stackoverflow.com/questions/8610635/how-do-you-use-math-random-to-generate-random-ints
//function to insert values to list
InsertValues();
// clear the fields after each add
clearFields();
alert("Record is successfully added to above list.");
// set focus back on the name field
name.focus();
}
}
function clearFields()
{
document.getElementById("name").value = "";
document.getElementById("ssn").value = "";
document.getElementById("date").value = "";
document.getElementById("currency").value = "";
}
// function to add to the list
function InsertValues()
{
var temp = 1,temp1 = 1,index = 0,i=0;
index = name_Array.length - 5;
for(i=0;i< name_Array.length;i++)
{
// when only first 5 entries are added to the list
if(name_Array.length>5)
{
// skip the first values so that only top 5 are shown in the list
if(temp>s)
{
if(temp1==5)
{
last = i;
}
else if(temp1==1)
{
first = i;
Index = i;
}
if(temp1<=5)
{
//initialise values of fields to the list
var str = "name" + temp1;
document.getElementById(str).value = name_Array[i];
str = "ssn" + temp1;
document.getElementById(str).value = ssn_Array[i];
str = "birth" + temp1;
document.getElementById(str).value = date_Array[i];
str = "xxxx" + temp1;
document.getElementById(str).value = currency_Array[i];
str = "random" + temp1;
document.getElementById(str).value = random_Array[i];
}
temp1++;
}
}
else
{
var str = "name" + temp;
document.getElementById(str).value = name_Array[i];
str = "ssn" + temp;
document.getElementById(str).value = ssn_Array[i];
str = "birth" + temp;
document.getElementById(str).value = date_Array[i];
str = "xxxx" + temp;
document.getElementById(str).value = currency_Array[i];
str = "random" + temp;
document.getElementById(str).value = random_Array[i];
}
temp++;
}
}
// Delete a record from the list
function delete_a_Record(record)
{
var remove = 0,i=0,j=1;
var name = document.getElementById("name" + record.value);
var delRecord = document.getElementById("random" + record.value);
if(name.value)
{
remove = 1;
}
// check for the existence of record
if(remove == 1)
{
if(confirm("Click on 'OK' to delete the record\n"))
{
while(i < random_Array.length)
{
if(delRecord.value==random_Array[i])
{
// if yes then remove that record from list
name_Array.splice(i, 1);
ssn_Array.splice(i, 1);
date_Array.splice(i, 1);
currency_Array.splice(i, 1);
random_Array.splice(i, 1);
}
i++;
}
// make entire list empty
while(j <= 5)
{
var str = "name" + j;
document.getElementById(str).value = "";
str = "ssn" + j;
document.getElementById(str).value = "";
str = "birth" + j;
document.getElementById(str).value = "";
str = "xxxx" + j;
document.getElementById(str).value = "";
str = "random" + j;
document.getElementById(str).value = "";
j++;
}
//call this function again to insert values in the list
InsertValues();
record.checked = false;
}
}
else
{
alert("Nothing to delete in this record.");
record.checked = false;
}
}
// function to perform scrollUp n scrollDown
function handleScrolling(type)
{
var j,k,temp2 = 1;
// perform scroll only when there are more than 5 records in the list
if(name_Array.length>5)
{ // scroll up
if(type==1)
{
first--; // decrement the pointer to see upper records
if(first>=0)
{
for (j = first; j < name_Array.length; j++) // its showing top most record from jth position
{
var str = "name" + temp2;
document.getElementById(str).value = name_Array[j];
str = "ssn" + temp2;
document.getElementById(str).value = ssn_Array[j];
str = "birth" + temp2;
document.getElementById(str).value = date_Array[j];
str = "xxxx" + temp2;
document.getElementById(str).value = currency_Array[j];
str = "random" + temp2;
document.getElementById(str).value = random_Array[j];
temp2++;
}
}
else
{
alert("Top of the list is reached\n");
first++;// increment the pointer to see lower records
}
}
else // scroll down
{
// increment the start point to see lower records if any
first++;
if(first<=Index)
{
for (k = first; k < name_Array.length; k++) //its showing bottom most record in the list from kth position
{
var str = "name" + temp2;
document.getElementById(str).value = name_Array[k];
str = "ssn" + temp2;
document.getElementById(str).value = ssn_Array[k];
str = "birth" + temp2;
document.getElementById(str).value = date_Array[k];
str = "xxxx" + temp2;
document.getElementById(str).value = currency_Array[k];
str = "random" + temp2;
document.getElementById(str).value = random_Array[k];
temp2++;
}
}
else
{
alert("Bottom most record is reached\n");
first--;//decrement the pointer to see upper records if any
}
}
}
else
{
alert("Scrolling strikes for records more than 5\n");
return false;
}
}
function adduser(name,ssn,date,currency)
{
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"name": name,
"ssn": ssn,
"date": date,
"currency": currency,
"action": "add"
},
success:function(data){
console.log('success');
fetchdata();
}
});
}
</script>
//php file
<?php
extract($_POST);
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error($con));
}
//mysql_select_db("ripal");
mysql_select_db("test");
//$sql = "SELECT * FROM user WHERE id = '" . $q . "'";
if ($action == 'add') {
$sql = "INSERT INTO myform(name,ssn,date,income)VALUES('" . mysql_real_escape_string($name) . "','" . mysql_real_escape_string($ssn) . "','" . mysql_real_escape_string($date) . "','" . mysql_real_escape_string($currency) . "')";
// echo $sql;
mysql_query($sql);
echo mysql_insert_id();
} else if ($action == 'fetch') {
$sql = "select * from myform";
// echo $sql;
$result = mysql_query($sql);
$str = '<form name="myForm">
<table width="page">
<tr>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td></td>
</tr>';
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name = $row['name'];
$ssn = $row['ssn'];
$date = $row['date'];
$currency = $row['income'];
$str.='<tr>
<td><input type="radio" id="' . $id . '" name="del" onclick="deleteRecord(this.id);"></td>
<td><input readonly type="text" value="' . $name . '" id="name1" name="name"></td>
<td><input readonly type="text" value="' . $ssn . '" id="ssn1" name="ssn"></td>
<td><input readonly type="text" value="' . $date . '" id="birth1" name="birth"></td>
<td><input readonly type="text" value="' . $currency . '" id="xxxx1" name="xxxx"><input type="hidden" name="random1" id="random1"></td>
</tr>';
}
}
$str.=' <tr>
<td colspan="5" id="scrollCount" align="center" style="padding-top:10px;"> </td>
</tr>
</table>
</form>';
if (mysql_num_rows($result) == 0) {
echo 'No data in Our Database please add one or more';
} else {
echo $str;
}
} else if ($action = 'delete') {
$sql = "DELETE from myform WHERE id=$id";
// echo $sql;
$result = mysql_query($sql);
echo $result;
}
mysql_close($con);

Categories

Resources