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();
}
Related
I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message
Failed to load resource: the server responded with a status of 404 (Not Found)
The same error message is shown for submit.php and refresh.php.
Here's my code:
JS
//CHAT FUNCTION
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
chatClass.php
<?PHP
class chatClass
{
public static function getRestChatLines($id)
{
$arr = array();
$jsonData = '{"results":[';
$statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$statement->bind_param( 'i', $id);
$statement->execute();
$statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
$line = new stdClass;
while ($statement->fetch()) {
$line->id = $id;
$line->usrname = $usrname;
$line->color = $color;
$line->chattext = $chattext;
$line->chattime = date('H:i:s', strtotime($chattime));
$arr[] = json_encode($line);
}
$statement->close();
$jsonData .= implode(",", $arr);
$jsonData .= ']}';
return $jsonData;
}
public static function setChatLines( $chattext, $usrname, $color) {
$statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
$statement->bind_param( 'sss', $usrname, $color, $chattext);
$statement->execute();
$statement->close();
}
}
?>
submit.php
<?php
require_once( "chatClass.php" );
$chattext = htmlspecialchars( $_GET['chattext'] );
chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>
refresh.php
<?php
require_once( "chatClass.php" );
$id = intval( $_GET[ 'lastTimeID' ] );
$jsonData = chatClass::getRestChatLines( $id );
print $jsonData;
?>
I have problem to set the AJAX variable in use in my PHP code
When I change the value of area the following function will be called:
function find_map(){
var value1 = $("#area").val();
var value2 = $("#city").val();
$.ajax({
url :"find_my_map.php", // json datasource
type: "post", // method , by default get
dataType:"json",
data:
{
area_id:value1,
city_id:value2
},
success: function(data)
{
console.log(data);
$.each(data, function(index, element) {
alert("area_name:" + element.area_name);
alert("city_name:" + element.city_name);
var map_area_name= element.area_name;
var map_city_name= element.city_name;
$("#map_area_name").val(map_area_name);
$("#map_city_name").val(map_city_name);
});
},
error:function(data){
console.log(data);
}
});
}
find_my_map.php file
include_once("config.php");
if(isset($_POST['area_id']) && isset($_POST['city_id']))
{
$area_id = $_POST['area_id'];
$city_id = $_POST['city_id'];
$sql = "SELECT * FROM area a, city c WHERE a.city_id=c.city_id AND c.city_id='$city_id' AND a.area_id='$area_id'";
$qry = mysql_query($sql);
while($fetch = mysql_fetch_array($qry))
{
$area_name=$fetch['area_name'];
$city_name=$fetch['city_name'];
$data[]=array(
'area_name' => $area_name,
'city_name' => $city_name
);
}
$json_data = array($data);
echo json_encode($data);
}
this is my php code
<?php
echo $address ="here i want to use **map_area_name AND map_city_name**"; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$area_latitude = $output->results[0]->geometry->location->lat;
$area_longitude = $output->results[0]->geometry->location->lng;
echo "<br><input type='text' name='area_latitude' id='area_latitude'value='".$area_latitude."'> <br>";
echo "<input type='text' name='area_longitude' id='area_longitude' value='".$area_longitude."'>";
?>
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'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);
i use select2, i want to format my results like
name, first.
$("#id").select2({
minimumInputLength : 0,
allowClear: true,
ajax : {
url : "Form/page.php",
dataType : 'json',
data : function (term, page) {
return {
q : term
};
},
results: function (data, page) {
return { results : data.ex};
},
formatResult : function formatResult(ex) {
return '<b>' + ex.name + '</b>';
}
}
});
my php file like
while($r=mysql_fetch_array($m)) {
$rows['id']=$r['id'];
$rows['text']=$r['name'];
$rows['first']=", ". $r['first'];
$rows2[]=$rows;
}
print json_encode($rows2);
how can i do that, thanks
I think the php code has to be like this:
while($r=mysql_fetch_array($m)) {
$rows['id']=$r['id'];
$rows['name']=$r['name'];
$rows['first']=$r['first'];
$rows2[]=$rows;
}
print json_encode($rows2);
So, you pass an array of json objects with an id, name and first.
Change the return of formatResult to:
return '<b>' + ex.name + '</b>, ' + ex.first;
PHP example reposted from the Select2 - source example:
https://github.com/ivaynberg/select2/wiki/PHP-Example
In JS:
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
and in PHP:
<?php
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
?>