I'm using the following ajax:
$.ajax({
type: 'POST',
url: '/search/search.php',
crossDomain: true,
data: {data: data},
dataType: 'json',
async: false,
success: function (response){
if (response.success)
{
$('#search-results').show();
for(field in response.data){
error = response.field_errors[field];
var name = field.name;
var barcode = field.barcode;
var serial = field.serial;
$("#searchname").html(name);
$("#searchbarcode").html(barcode);
$("#searchserial").html(serial);
}
}
else {
console.log("fail");
}
},
});
I'm trying to loop through the rows returned from the php, and put each row as a row in the table of my html.. I get the correct response from the php, but my loop doesn't show anything in the html.
HTML Table
<table class="table" id="search-results" style="display:none;">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Serial</th>
<th>Barcode</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td id="searchname"></td>
<td id="searchbarcode"></td>
<td id="searchserial"></td>
</tr>
</tbody>
</table>
PHP
$json = array();
if($num > 0)
{
$json['success'] = TRUE;
$i = 0;
while ($row = mysql_fetch_array($sql))
{
$json[$i]['data']['name'] = $row['name'];
$json[$i]['data']['barcode'] = $row['barcode'];
$json[$i]['data']['serial'] = $row['serial'];
$i++;
}
}
else
{
$json['success'] = FALSE;
}
echo json_encode($json);
You can use jquery .each(). to itterate the array, and jquerys .append() to add the table rows:
If the data is an array of objects:
$.each(response.data, function( index, item ) {
$('#search-results').append('<tr><td>' + item.name + '</td><td>' + item.barcode + '</td><td>' + item.serial + '</td><td></tr>');
});
If its an array of arrays:
$.each(response.data, function( index, item ) {
$('#search-results').append('<tr><td>' + item['name'] + '</td><td>' + item['barcode'] + '</td><td>' + item['serial'] + '</td><td></tr>');
});
https://api.jquery.com/jQuery.each/
EDIT you php creates odd json, hence your problems. Fix it up:
$json = array();
if($num > 0)
{
$json['success'] = TRUE;
while ($row = mysql_fetch_array($sql))
{
$json['data'][]=array('name'=>$row['name'], 'barcode'=>$row['barcode'], 'serial'=>$row['serial']);
}
}
else
{
$json['success'] = FALSE;
}
echo json_encode($json);
Related
My default start page has no data
Then filter out the data in the database after the two drop-down list
I hope that the filtered data can be displayed in pagination if there are more than ten records.
But I don't know how to do.
I'm new in this.
Here is my javascript
<script type="text/javascript">
$(document).ready(function () {
$("#CITY").change(function () { ChangeCity(); });
$("#AREA").change(function () { ChangeArea(); });
$(document).on('submit', '#ButtonSubmit', function () {
return false;
});
})
function SetareaEmpty() {
$('#CITY').empty();
$('#CITY').append($('<option></option>').val('').text('select'));
}
function ChangeCity() {
var selectedCity = $.trim($('#CITY option:selected').val());
if ($.trim(selectedCity.length) > 0) {
ChangeArea(selectedCity);
}
else {
SetareaEmpty()
}
}
function ChangeArea(selectedCity) {
$.ajax({
type: "POST",
url: '#Url.Action("GetSecondDDL", "Getarea")',
dataType: "json",
data: { cityName: selectedCity },
success: function (mems) {
if (mems.length > 0) {
$('#AREA').empty();
$('#AREA').append($('<option></option>').val('').text('select'));
}
$.each(mems, function (i, member) {
$("#AREA").append($('<option></option>').val(member).text(member));
});
}
});
}
function SerchallData(selectedCity) {
var selectedCity = $('#CITY option:selected').val();
var selectedValue = $('#AREA option:selected').val();
if ($.trim(selectedValue).length > 0) {
$.ajax({
url: '#Url.Action("Getmap", "Getarea")',
data: { cityName: selectedCity, areaName: selectedValue },
type: 'POST',
dataType: 'json',
success: function (data) {
$('#Mytable>tbody').empty();
for (var i = 0; i < data.length; i++) {
var row = $('<tr><td>'>+</td><td>' + data[i].ID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Address + '</td><td>' + data[i].Phone + '</td><td>' +'</td></tr>');
$('#Mytable>tbody').append(row);
}
$('#Mytable').show(); //show filter data
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
}
}
my dropdownlist is use js to connection
filter data also
that's means after user selected city and area
data will be displayed
here is my html:
<form>
<div class="row well">
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">City</span>
<p>
#Html.DropDownList("City", (IEnumerable<SelectListItem>)ViewBag.Allcity, "Please select", new { id = "CITY" })
</p>
</div>
</div>
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">Area</span>
<p> <select id="AREA" name="AREA"><option>Please select</option></select></p>
</div>
</div>
<div class="col-lg-2">
<button type="button" onclick="SearchallData()" id="ButtonSubmit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span>search
</button>
</div>
</div>
<table id="Mytable" class="table table-bordered table-hover" style="display:none;">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
//first page table will not show any data so is null
</tbody>
and my controller
public async Task<ActionResult> Index()
{
var b = new GetCollection();
var areasource = await b.GetInserchdata();
ViewBag.AllCity = areasource.Select(s => s.City).Distinct().Select(item => new SelectListItem()
{
Text = item,
Value = item
});
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connstr))
{
con.Open();
string q = "Select * from Shopmap";
SqlDataAdapter da = new SqlDataAdapter(q, con);
da.Fill(dt);
}
return View(dt);
}
//js for first selected dropdownlist
[HttpPost]
public async Task<JsonResult> GetSecondDDL(string cityName)
{
var CitySlectList = this.GetSelectList(await GetCity(), cityName);
if (string.IsNullOrEmpty(cityName))
{
return Json(new EmptyResult());
}
var AreaSlectList = await this.GetArea(cityName);
return Json(AreaSlectList);
}
//js for selected second dropdownlist then search data
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)
{
var b = new GetCollection();
List<Inserch> shop = b.GetDBdata();
var a = shop.FindAll(x => x.Address.Contains(cityName));
var Alldata = a.FindAll(x => x.Address.Contains(areaName)).AsEnumerable();
if (string.IsNullOrEmpty(areaName))
{
return Json(new EmptyResult());
}
return Json(Alldata);
}
I think it will use js to do what I want
then maybe c# code will put in
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)->this function
please tell me what to do
I desperately need.
thank's.
Pagination for Dropdownlist filter data in ASP.NET MVC
You can achieve that in following way:
HTML
<table id="userTable_info">
<thead>
<tr>
<th>Id </th>
<th>Controller </th>
<th>Page_name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
Script:
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#userTable_info').hide();
//On Submit Method
$("#Submit").click(function () {
var ddlCategory = parseInt($("#ddlCategory").val());
var ddlSubCategorie = parseInt($("#ddlSubCategorie").val());
$.ajax({
type: "POST",
url: 'http://localhost:5094/Member/GetShopmap',
dataType: "json",
data: { cityName: ddlCategory, areaName: ddlSubCategorie },
success: function (response) {
console.log(response);
$.each(response, function (index, value) {
var tr = "<tr>";
tr += "<td>" + value.ulogo_id + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.page_name + "</td>";
tr += "<td>" + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
$('#userTable_info').show();
}
});
});
});
</script>
}
Output:
Note: Based on your table defination please implement the neccessary chnages. It ill work as expected.
I am trying to make a CRUD table using laravel and AJAX. Trying out the tutorial from Webslesson. Here is the tutorial link : https://www.webslesson.info/2018/12/live-table-add-edit-delete-in-laravel-using-ajax-jquery.html
I've tried may ways and it doesnt seem to work.
Here is my Javascript code.
$(document).ready(function(){
fetch_data();
function fetch_data()
{
$.ajax({
// url:"/enquiry/fetch_data",
url:"{{url('/enquiry/fetch_data')}}",
dataType:"json",
success:function(data)
{
var html = '';
html += '<tr>';
html += '<td contenteditable id="ac_assign"></td>';
html += '<td contenteditable id="item_cat"></td>';
html += '<td contenteditable id="itemDesc"></td>';
html += '<td contenteditable id="deliveryDate"></td>';
html += '<td contenteditable id="qty"></td>';
html += '<td contenteditable id="unit"></td>';
html += '<td contenteditable id="assetNo"></td>';
html += '<td contenteditable id="remark"></td>';
html += '<td><button type="button" class="btn btn-success btn-xs" id="add">Add</button></td></tr>';
for(var count=0; count < data.length; count++)
{
html +='<tr>';
html +='<td contenteditable class="column_name" data-column_name="ac_assign" data-id="'+data[count].id+'">'+data[count].ac_assign+'</td>';
html += '<td contenteditable class="column_name" data-column_name="item_cat" data-id="'+data[count].id+'">'+data[count].item_cat+'</td>';
html += '<td contenteditable class="column_name" data-column_name="itemDesc" data-id="'+data[count].id+'">'+data[count].itemDesc+'</td>';
html += '<td contenteditable class="column_name" data-column_name="deliveryDate" data-id="'+data[count].id+'">'+data[count].deliveryDate+'</td>';
html += '<td contenteditable class="column_name" data-column_name="qty" data-id="'+data[count].id+'">'+data[count].qty+'</td>';
html += '<td contenteditable class="column_name" data-column_name="unit" data-id="'+data[count].id+'">'+data[count].unit+'</td>';
html += '<td contenteditable class="column_name" data-column_name="assetNo" data-id="'+data[count].id+'">'+data[count].assetNo+'</td>';
html += '<td contenteditable class="column_name" data-column_name="remark" data-id="'+data[count].id+'">'+data[count].remark+'</td>';
html += '<td><button type="button" class="btn btn-danger btn-xs delete" id="'+data[count].id+'">Delete</button></td></tr>';
}
$('tbody').html(html);
}
});
}
var _token = $('input[name="_token"]').val();
$(document).on('click', '#add', function(){
var ac_assign = $('#ac_assign').text();
var item_cat = $('#item_cat').text();
var item_cat = $('#itemDesc').text();
var item_cat = $('#deliveryDate').text();
var item_cat = $('#qty').text();
var item_cat = $('#unit').text();
var item_cat = $('#assetNo').text();
var item_cat = $('#remark').text();
if(ac_assign != '' || item_cat != '' || itemDesc != '' || deliveryDate != '' || qty != '' || unit != '' || assetNo != '' || remark != '' )
{
$.ajax({
url:"{{ route('enquiry.add_data') }}",
method:"POST",
data:{ac_assign:ac_assign, item_cat:item_cat, itemDesc:itemDesc, deliveryDate:deliveryDate, qty:qty, unit:unit, assetNo:assetNo, remark:remark, _token:_token},
success:function(data)
{
$('#message').html(data);
fetch_data();
}
});
}
else
{
$('#message').html("<div class='alert alert-danger'>Both Fields are required</div>");
}
});
$(document).on('blur', '.column_name', function(){
var column_name = $(this).data("column_name");
var column_value = $(this).text();
var id = $(this).data("id");
if(column_value != '')
{
$.ajax({
url:"{{ route('enquiry.update_data') }}",
method:"POST",
data:{column_name:column_name, column_value:column_value, id:id, _token:_token},
success:function(data)
{
$('#message').html(data);
}
})
}
else
{
$('#message').html("<div class='alert alert-danger'>Enter some value</div>");
}
});
$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
if(confirm("Are you sure you want to delete this records?"))
{
$.ajax({
url:"{{ route('enquiry.delete_data') }}",
method:"POST",
data:{id:id, _token:_token},
success:function(data)
{
$('#message').html(data);
fetch_data();
}
});
}
});
});
Here is my blade
<div class="panel-body">
<div id="message"></div>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<!-- <th>NO</th> -->
<th>A/C ASSIGN</th>
<th>ITEM CATEGORY</th>
<th>DELIVERY DATE</th>
<th>ITEM DESC</th>
<th>QTY</th>
<th>UNIT</th>
<th>ASSET NO</th>
<th>REMARK</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
{{ csrf_field() }}
</div>
</div>
Here are the functions in my controller
function fetch_data(Request $request)
{
$data = Enquiry::where('formId', $request->formId)->orderBy('id','desc')->get();
// echo $data;
echo json_encode($data);
}
function add_data(Request $request)
{
if($request->ajax())
{
$data = array(
'no' => $request->no,
'deliveryDate' => $request->deliveryDate,
'ac_assign' => $request->ac_assign,
'item_cat' => $request->item_cat,
'itemDesc' => $request->itemDesc,
'qty' => $request->qty,
'unit' => $request->unit,
'assetNo' => $request->assetNo,
'remark' => $request->remark
);
$id = Enquiry::insert($data);
if($id > 0)
{
echo '<div class="alert alert-success">Data Inserted</div>';
}
}
}
function update_data(Request $request)
{
// if($request->ajax())
// {
$data = array(
$request->column_name => $request->column_value,
);
Enquiry::where('formId', $request->formId)
->update($data);
echo '<div class="alert alert-success">Data Updated</div>';
// }
}
function delete_data(Request $request)
{
// if($request->ajax())
// {
Enquiry::where('id', $request->id)
->delete();
echo '<div class="alert alert-success">Data Deleted</div>';
// }
}
And here is my web.php
Route::get('/enquiry/fetch_data', 'FormController#fetch_data');
Route::post('/enquiry/add_data', 'FormController#add_data')->name('enquiry.add_data');
Route::post('/enquiry/update_data', 'FormController#update_data')->name('enquiry.update_data');
Route::post('/enquiry/delete_data', 'FormController#delete_data')->name('enquiry.delete_data');
This is the error from the console. I have attached an image here.
Thank you.
For some reason i don't know why that happens but here is how to fix it Instead of
npm run dev
just run build
npm run build
Enjoy coding
I've got a JS script that pulls data from an API and merges it all into a table, I need to do this twice for two different sets of data. Individually the scripts work as expected but when they're running on the same page only one of them displays any data.
I know the script tag isn't the best way to use JS but for my purpose everything needs to be contained in one block of html.
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
//Voting totals for current month
var votingURLs = [
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=7ImLVCEQFgOq9Ugz5G569nQJ5akmta8C2ty&month=current&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=eJgmsMaw6Aor1bSD1r9wtyu1mBiLNjWSZW&month=current&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=current&format=json&rank=steamid'
];
var votingLists = [];
var counter = 0;
var finalList = [];
var voters = [];
var votesOfVoters = [];
$(document).ready(function() {
$.each(votingURLs, function(index, value) {
var data;
$.ajax({
dataType: "json",
url: value,
data: data,
success: function(data) {
votingLists[index] = data.voters;
checkCompleteness();
}
});
});
});
function checkCompleteness() {
counter++;
if (counter == (votingURLs.length)) {
evalData();
}
}
function evalData() {
console.log("Start Evaluating");
finalList = votingLists[0];
$.each(votingLists, function(index, list) {
if (index > 0) {
$.each(list, function(index, value) {
var steamid = value.steamid;
var found = false;
$.each(finalList, function(indexF, valueF) {
if (steamid == valueF.steamid) {
valueF.votes = parseInt(valueF.votes) + parseInt(value.votes);
found = true;
return false;
}
});
if (!found) {
finalList.push(value);
}
});
}
});
displayingList(finalList);
}
function displayingList(list) {
console.log("Start Displaying");
list.sort(function(a, b) {
return parseInt(b.votes, 10) - parseInt(a.votes, 10);
});
$.each(list, function(index, value) {
var row = '<tr> <td>' + value.nickname + '</td> <td> ' + value.votes + '</td> </tr>';
$('table[data="current_votes"] tbody').append(row);
});
}
</script>
<script>
//Voting totals for previous month
var votingURLs = [
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=7ImLVCEQFgOq9Ugz5G569nQJ5akmta8C2ty&month=previous&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=eJgmsMaw6Aor1bSD1r9wtyu1mBiLNjWSZW&month=previous&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=previous&format=json&rank=steamid'
];
var votingLists = [];
var counter = 0;
var finalList = [];
var voters = [];
var votesOfVoters = [];
$(document).ready(function() {
$.each(votingURLs, function(index, value) {
var data;
$.ajax({
dataType: "json",
url: value,
data: data,
success: function(data) {
votingLists[index] = data.voters;
checkCompleteness();
}
});
});
});
function checkCompleteness() {
counter++;
if (counter == (votingURLs.length)) {
evalData();
}
}
function evalData() {
console.log("Start Evaluating");
finalList = votingLists[0];
$.each(votingLists, function(index, list) {
if (index > 0) {
$.each(list, function(index, value) {
var steamid = value.steamid;
var found = false;
$.each(finalList, function(indexF, valueF) {
if (steamid == valueF.steamid) {
valueF.votes = parseInt(valueF.votes) + parseInt(value.votes);
found = true;
return false;
}
});
if (!found) {
finalList.push(value);
}
});
}
});
displayingList(finalList);
}
function displayingList(list) {
console.log("Start Displaying");
list.sort(function(a, b) {
return parseInt(b.votes, 10) - parseInt(a.votes, 10);
});
$.each(list, function(index, value) {
var row = '<tr> <td>' + value.nickname + '</td> <td> ' + value.votes + '</td> </tr>';
$('table[data="old_votes"] tbody').append(row);
});
}
</script>
<div>
<table data="current_votes" id="current_totals">
<tr>
<th colspan="2">Totals</th>
</tr>
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
<div>
<table data="old_votes" id="old_totals">
<tr>
<th colspan="2">Totals</th>
</tr>
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
please take a look of below code. i added one extra parameter to distinguish current and old url and based on that in displayingList() we append data.
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
//Voting totals for current month
var current_votingURLs = [
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=7ImLVCEQFgOq9Ugz5G569nQJ5akmta8C2ty&month=current&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=eJgmsMaw6Aor1bSD1r9wtyu1mBiLNjWSZW&month=current&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=current&format=json&rank=steamid'
];
var old_votingURLs = [
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=7ImLVCEQFgOq9Ugz5G569nQJ5akmta8C2ty&month=previous&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=eJgmsMaw6Aor1bSD1r9wtyu1mBiLNjWSZW&month=previous&format=json&rank=steamid',
'https://ark-servers.net/api/?object=servers&element=voters&limit=1000&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=previous&format=json&rank=steamid'
];
var votingLists = [];
var counter = 0;
var finalList = [];
var voters = [];
var votesOfVoters = [];
var apiCounter = 0;
$(document).ready(function() {
function baseFunction(votingURLs, urlType){
$.each(votingURLs, function(index, value) {
var data;
$.ajax({
dataType: "json",
url: value,
data: data,
success: function(data) {
apiCounter++;
console.log(data);
votingLists[index] = data.voters;
checkCompleteness(votingURLs, urlType);
}
});
});
}
baseFunction(current_votingURLs,'current');
baseFunction(old_votingURLs,'old');
});
function checkCompleteness(votingURLs, urlType) {
counter++;
console.log('In checkCompleteness');
//if (counter == (votingURLs.length)) {
evalData(urlType);
//}
}
function evalData(urlType) {
console.log("Start Evaluating");
console.log("Start Evaluating", urlType);
finalList = votingLists[0];
$.each(votingLists, function(index, list) {
if (index > 0) {
$.each(list, function(index, value) {
var steamid = value.steamid;
var found = false;
$.each(finalList, function(indexF, valueF) {
if (steamid == valueF.steamid) {
valueF.votes = parseInt(valueF.votes) + parseInt(value.votes);
found = true;
return false;
}
});
if (!found) {
finalList.push(value);
}
});
}
});
displayingList(finalList, urlType);
}
function displayingList(list, urlType) {
console.log("Start Displaying");
console.log("urlType", urlType);
list.sort(function(a, b) {
return parseInt(b.votes, 10) - parseInt(a.votes, 10);
});
if(urlType == 'current') {
$.each(list, function(index, value) {
var row = '<tr> <td>' + value.nickname + '</td> <td> ' + value.votes + '</td> </tr>';
$('table[data="current_votes"] tbody').append(row);
});
}else {
$.each(list, function(index, value) {
var row = '<tr> <td>' + value.nickname + '</td> <td> ' + value.votes + '</td> </tr>';
$('table[data="old_votes"] tbody').append(row);
});
}
console.log(apiCounter);
}
</script>
<div>
<table data="current_votes" id="current_totals">
<tr>
<th colspan="2">Totals</th>
</tr>
<tr>
<th>Username new</th>
<th>Votes</th>
</tr>
</table>
</div>
<div>
<table data="old_votes" id="old_totals">
<tr>
<th colspan="2">Totals</th>
</tr>
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
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.
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();
}