I'm a bit lost at the moment since my code seems to work but my table is not interested. xD
I'm loading data from my db into a table and i want it to be "auto-updated" every three seconds. My JSON data is correct and the js-console displays the updated data. But my table doesn't want to display it so I have to refresh the entire page. However that's not what I want to do.
Here is my code
(HTML+JS):
<script>
$(document).ready(function() {
setInterval(function() {``
$.ajax({
url: "myStuff.php",
success: function(data) {
console.log(data);
myRecords = $.parseJSON(data);
$("#dynatable").dynatable({
dataset: {
records: myRecords
}
});
}
});
}, 3000);
});
<table id="dynatable">
<thead>
<th>test1</th>
<th>test2</th>
</thead>
<tbody>
</tbody>
</table>
PHP:
$response = array();
while ($zeile = mysqli_fetch_array($db_erg, MYSQL_ASSOC)) {
$response [] = array(
"test1" => $zeile['wasd'],
"test2" => $zeile['wasdf']
);
}
echo json_encode($response);
When I add data to my database the returned JSON data is updated, i see it in the js-console. Problem is that my table doesn't want to display it, it just shows the "old" data.
Any suggestions to solve this?
-------------------------------------------------------------
EDIT:
I got it now! This helped me solve my problem. Thanks for the help! :)
Here is my code:
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: "myStuff.php",
success: function(data) {
console.log(data);
var myRecords = $.parseJSON(data);
var dynatable = $('#dynatable').dynatable({
dataset: {
records: myRecords
}
}).data('dynatable');
dynatable.settings.dataset.originalRecords = myRecords;
dynatable.process();
}
});
}, 3000);
});
this code can also update the table.
<script>
$(document).ready(function() {
var mytable = $("#dynatable");
setInterval(function() {
$.ajax({
url: "do.php",
success: function(data) {
myRecords = $.parseJSON(data);
mytable.dynatable({
dataset: {
records: myRecords
}
});
mytable.data('dynatable').settings.dataset.records = myRecords;
mytable.data('dynatable').dom.update();
console.log(data);
}
});
},
1000);
});
</script>
Related
I want to remove the deleted row from the table but it's not working with me. I tried the below code:
Scenario: When a user click on delete link/button, it sends a delete request and deletes data from Database so it should update the table front end view and should remove the clicked deleted row on success.
// Delete remedy which is linked with a Symptom ( Symptoms Table )
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
$.SmartMessageBox({
title: "Delete Remedy",
content: "Remedy Entry will be deleted, are you sure ?",
buttons: "[YES][NO]"
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-remedy-from-symptom') ?>',
success: function(data) {
$("#deleteMessage").show().delay(5000).fadeOut();
$(this).closest('tr').remove();
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
I tried $(this).parent().closest('tr').remove(); also on success but not working.
HTML markup:
<table id="cx-records-table" class="table display table-striped table-bordered" width="100%">
<thead>
<tr>
<th>
Title
</th>
<th>
Delete
</th>
</tr>
<?php foreach($remedies as $key => $remedy){ ?>
<tr>
<td class="all"><?php echo $remedy['title']; ?><br></td>
<td><a class="cx-action remedy-row-delete" href="javascript:void(0)" data-id="{{remedy['id']}}"><i class="fa fa-trash-o"></i></a></td>
</tr>
<?php } ?>
</thead>
<tbody></tbody>
</table>
Thanks
because $(this) inside of ajax function is different than from outside you should do something like this
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
var $this = $(this) // <--- 1. Add this line
$.SmartMessageBox({
...
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
...
success: function(data) {
...
$this.closest('tr').remove(); // <----change this and will works well
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
try this
// Delete remedy which is linked with a Symptom ( Symptoms Table )
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
var self = this;
$.SmartMessageBox({
title: "Delete Remedy",
content: "Remedy Entry will be deleted, are you sure ?",
buttons: "[YES][NO]"
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-remedy-from-symptom') ?>',
success: function(data) {
$("#deleteMessage").show().delay(5000).fadeOut();
$(self).closest('tr').remove();
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
I have this php
include_once($preUrl . "openDatabase.php");
$sql = 'SELECT * FROM dish';
$query = mysqli_query($con,$sql);
$nRows = mysqli_num_rows($query);
if($nRows > 0){
$dishes = array();
while($row = $query->fetch_assoc()) {
$dishes[] = $row;
}
}else{
$dishes = "cyke";
}
echo json_encode($dishes , JSON_FORCE_OBJECT);
and this ajax (in framework7)
myApp.onPageInit('dailyMenu',function() {
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.log(data);
});
});
What i get in the ajax data is
{"0":{"idC":"2","title":"helloWorld1","subtitle":"hellsubWorld","price":"16.5","img":"img/testeImg.jpg","soldout":"0"},"1":{"idC":"3","title":"helloworld2","subtitle":"hellosubWorld2","price":"20.5","img":"img/testeImg.jpg","soldout":"1"}}
I already tried data.[0]; data.['0']; data.0; data0 when i use data["0"] just gives me the '{'.
I want to acess the title and the rest inside that 0. to do a cicle for where i will print multiple divs where i only change the array position in a html page.
Exemple
for(...){
innerhtml += <div clas="">
<div class""> data(position i).title </div>
<div> data(position i) subtitle</div>
</div>
}
try this one (after callback add type: json)
$$.post('url', {}, function (data) {
var obj = JSON.parse(data);
console.log(obj);
alert(obj["1"].title);
});
or maybe you can use JSON.parse(data);
Since you are receiving a json data as response, you should use this:
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.dir(data);
},'json');
Pay attention to },'json');on end of the code, now the $$.post is reading the response as a JSON.
If you aren't doing any update to data base, you could use:
$$.getJSON('http://theIP/eatsServer/dailyMenu.php',{}, function (data) {
console.dir(data);
});
This is the way with $$.ajax:
$$.ajax({
url: "url_here",
method: "POST",
dataType:"json",
data: {},
success: function(r){
// response r.
}, error: function(error){
//error
}
});
why is this my data table not reloading?. In my situation, I have a data table named table_clinics that I declared global in my javascript, now I have other function to add a data within the data table, I want to prevent refresh that is why I want my data table to be reloaded after adding new data. Am I doing it wrong?.
Here is my code:
<script type="text/javascript">
var table_clinics;
$(document).ready(function() {
table_clinics = $('#dataTables-clinics').dataTable();
});
function show_clinics() {
$("#dataTables-clinics").dataTable().fnDestroy();
table_clinics = $('#dataTables-clinics').DataTable({
"ajax": {
"url": "<?php echo site_url('clinic_admin/myclinics')?>",
"type": "POST",
},
responsive: true,
bInfo: false,
});
}
</script>
now I have a function to add data from the data table and after success, i want to refresh my data table. Here is my function: i tried : table_clinics.ajax.reload(null,false); but it doesn't reload my data table. how can I do this?
function create_clinic() {
$('#btnCreateClinic').text('Saving...');
$('#btnCreateClinic').attr('disabled',true);
$.ajax({
url : siteurl+"clinic_admin/create_clinic",
type: "POST",
data: $('#frm_create_clinic').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) {
table_clinics.ajax.reload(null,false);
alert('Added Sucessfuly');
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
$('#btnCreateClinic').text('Save'); //change button text
$('#btnCreateClinic').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding data' + jqXHR+ textStatus +errorThrown);
$('#btnCreateClinic').text('Save');
$('#btnCreateClinic').attr('disabled',false);
}
});
}
also tried this:
if(data.status) {
table_clinics = $("#dataTables-clinics").dataTable( { bRetrieve : true } );
table_clinics.fnDraw();
// Hide all tables
$('dataTables-clinics').hide();
// Show the refreshed
$('dataTables-clinics').show();
alert('Added Sucessfuly');
}
also i tried this one:
and i add https://cdn.datatables.net/plug-ins/1.10.15/api/fnReloadAjax.js.
if(data.status) {
table_clinics.fnReloadAjax('<?php echo site_url('"clinic_admin/myclinics"')?>');
table_clinics.fnReloadAjax();
alert('Added Sucessfuly');
}
Reload You datatable , Try this
$('#dynamic-table').DataTable().ajax.reload(); // id of table
You must call draw() on the datatable object.
var oTable = $('#yourDataTable').dataTable();
oTable.fnDraw();
See the example i have done. Click on Add New Data button in jsfiddle
I want to delete data from database without refreshing the page. My code is working but after deleteing a product needs to refresh the page. I want something like this
Here is my js code:
<script>
$(document).on('click', '.delete-it', function() {
var id = $(this).attr('delete-id');
bootbox.confirm("Are you sure?", function(result) {
if (result) {
$.ajax({
type: "POST",
async: false,
url: "delete_product.php",
data: {
object_id: id
},
dataType: 'json',
success: function(data) {
location.reload();
}
});
}
});
return false;
});
</script>
and the delete_product php code:
<?php
// check if value was posted
if($_POST){
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare product object
$product = new Product($db);
// set product id to be deleted
$product->id = $_POST['object_id'];
// delete the product
if($product->delete()){
echo "Object was deleted.";
}
// if unable to delete the product
else{
echo "Unable to delete object.";
}
}
?>
Please show me a way to make it!
I see no place where the you're targeting something in the page, but this is what I would use:
<script>
function swapContent(href, url_data, target) {
$.ajax({
type: 'GET',
cache: false,
url: href+'?' + url_data, //add a variable to the URL that will carry the value in your i counter through to the PHP page so it know's if this is new or additional data
success: function (data) { // this param name was confusing, I have changed it to the "normal" name to make it clear that it contains the data returned from the request
//load more data to "target" value div
target.innerHTML = (data); // as above, data holds the result of the request, so all the data returned from your results.php file are in this param but please see below
}
})
}
$(document).on('click', '.delete-it', function() {
var id = $(this).attr('delete-id');
bootbox.confirm("Are you sure?", function(result) {
if (result) {
swapContent(base_url, url_data, target) //set variables
}
});
return false;
});
</script>
note: because of how much ajax I use, I keep an ajax function by itself
I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
$(document).ready(function () {
$('#submitbutton').click(function () {
$.ajax({
url: "../../index.php/testcontroller/getdatabasedata",
data: {
'searchvalue' : $('#inputtext').val()
},
method: 'GET'
}).done(function (data) {
var dataarray = data.split('##');
$('#question').html(dataarray[ 1 ]);
$('#answer1').html(dataarray[ 2 ]);
});
return false;
});
});
</script>
</body>
Controller
public function getdatabasedata()
{
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
$movie = $this->testmodel->findquestion($year);
$moviesstring = implode(",", $movie);
echo $moviesstring;
}
Model
function findquestion($searchvalue)
{
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
var_dump($res)
if ($res->num_rows() == 0)
{
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Script:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
var data = {'searchvalue' : $('#inputtext').val() };
$.ajax ({
url : target_url,
type: 'GET',
data: data,
cache: false,
success: function(controller_data)
{
var dataarray = controller_data.split('#');
$('#question').html(dataarray[1]);
$('#answer1').html(dataarray[3]);
},
});
return false;
});
});
</script>
.bind("click",function() - add quotes to click event.
var dataarray = controller_data.split('#'); - split
data caracter must match character in implode function in controller.
Controller:
public function getdatabasedata(){
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
$movie = $this->testmodel->findquestion($year);
$separated = implode("#", $movie);
echo $separated;
}
Hope this helped.
I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
$.ajax
(
{
url : target_url,
type: "GET",
// data: {'searchvalue' : $('#inputtext').val()},
cache: false,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error during loading ....");
}
});
});// end loading via ajax
and in your controller just echo something
public function getdatabasedata()
{
//$this->load->model('testmodel');
//$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
//$movie = $this->testmodel->findquestion($year);
//$moviesstring = implode(",", $movie);
//echo $moviesstring;
echo "hello";
}