I am using AJAX to load (and subsequently refresh) a JS datatable (v1.10.0). I don't think I'm doing this properly because while I can get the initial table to load, subsequent AJAX requests do not update the table.
I've tried various combinations of the .clear(), .draw() and .rows.add() JS Datatables methods, but nothing seems to work.
jquery code below:
$(document).ready(function() {
$('#results').html('<table id="table-output" class="display" cellspacing="0" width="100%"></table>');
var table_config = {
"bDestroy": true,
"paging": false,
"language": {
"zeroRecords": "No results found",
"processing": "<div align='center'><img src='/static/ajax-loader.gif'></div>",
"loadingRecords": "<div align='center'><img src='/static/ajax-loader.gif'></div>"
}
};
$("form").submit(function(e) {
e.preventDefault();
var form_data = JSON.stringify($(this).serializeArray());
$.ajax({
type: 'POST',
url: /the_url,
data: form_data,
contentType: 'application/json',
dataType: 'json',
success: function(response) {
table_config.data = response.data;
table_config.columns = response.columns;
$('#table-output').dataTable(table_config);
}
});
});
});
I figured it out. Modifying the success function as follows works:
success: function(response) {
$('#results').html('<table id="table-output" class="display" cellspacing="0" width="100%"></table>');
table_config.columns = response.columns;
var table = $('#table-output').DataTable(table_config);
table.clear();
table.rows.add(response.data);
table.draw();
}
You can try :
var table1 = $('#youtblename').DataTable();
var pathp = "/server_processing_pie.php";
tablel.clear();
tablel.draw();
tablel.ajax.url(pathp).load();
Related
I am fetching values from data using where in() mysql query and I got the correct result, but I don't know how to display the result in ajax success.
How do I display company name and email id from result data set?
my ajax code
<script type="text/javascript">
$('#ok').on('click', function() {
var vals = $('#show').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: { vals:vals },
datatype: 'json',
success: function (data) {
alert(data);
$("#result").html(data);
var result = JSON.parse(data);
}
});
});
</script>
my controller code:
function get_company()
{
$vals = $this->input->post('vals');
$query = $this->db->query("SELECT * FROM customer` where company_id IN ($vals) ")->result();
echo json_encode($query);
}
my result:
[{"company_name":"xyz Ltd","company_email":"123#gmail.com"},{"company_name":"wer Jit","company_email":"2222#gmail.com"}]
assuming you get this json in your ajax success:
const json = '[ {
"company_name": "xyz Ltd",
"company_email": "123#gmail.com"
},
{
"company_name": "wer Jit",
"company_email": "2222#gmail.com"
}]
';
const obj = JSON.parse(json);
// you don't need this line, if you have set ajax datatype:'json'
you can get results for a single data set:
console.log(obj[0].company_name);
// this is how to get the first company name of the data set
// expected output: "xyz Ltd"
or you can loop through the whole data set
obj.forEach(element => $("#result").append(element.company_name + '<br>'));
see a working example
conclusion: your ajax function could look just simply like this:
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: {
vals: vals
},
datatype: 'json',
success: function(data) {
obj.forEach(data => $("#result").append(data.company_name + '<br>'));
}
})
I am using laravel, and I want to check if there are new records inserted into the database, I want an Ajax code the returns with the result, I don't know ajax so please help me
this is my controller
public function newrecord($target_id){
$record = Message::where('target_id', $target_id)->get();
return $record->count();
}**strong text**
and this is my ajax code
$(document).ready(function(){
var ajaxCall=function()
{
$.ajax({
url:"{{ url('/record/'.$auth->id) }}" ,
type: "GET",
datatype:"html",
data:{},
success:function(data) {
$('.msgnum').html(data)
console.log('new record);
},
error: function(data) {
console.log('error');
}
});
}
setInterval(ajaxCall,5000);
});
all I get is just a loop or " new record " in the console log
Do I need to return anything to tell that there is a new file, any help?
Try this, of course modify the code to how you want it to work but wrap the whole thing in setInterval, you don't even need the document.ready()
<script type="text/javascript">
setInterval(function() {
$.ajax({
url:"{{ url('/record/'.$auth->id) }}",
type: "GET",
datatype:"html",
data:{},
processData:false,
success: function(data){
$('.msgnum').html(data)
console.log('new record');
error: function(data) {
console.log('error');
}
},
error: function(){}
});
}, 5000);
</script>
I'm trying to remove an object from an ObservableArray after an ajax-call. It works with the '.pop' function, but not when I'm using the custom knockout.js '.remove'-function.
If I move the call to the '.remove' function outside the ajax-complete function, '.remove' does work. But I would really rather have it inside the '.complete'.
Can anyone spot what I'm doing wrong?
This doesn't work:
self.removeItem = function(data) {
$.ajax({
type: 'POST',
url:'/echo/js/?js=hello%20world!',
dataType: 'json',
contentType: 'application/json',
data: null
}).complete(function (item,data) {
self.Items.remove(data);
});
};
I made a jsfiddle to demonstrate: http://jsfiddle.net/6oe6dn7n/1/
My view-model looks like so:
var data = {
Name: "Test",
Items: ["One", "Two", "Three"]
};
function ViewModel(data) {
var self = this;
self.Items = ko.observableArray(ko.utils.arrayMap(data.Items,
function(item) {
return { value: ko.observable(item) };
}));
self.removeItem = function(data) {
$.ajax({
type: 'POST',
url:'/echo/js/?js=hello%20world!',
dataType: 'json',
contentType: 'application/json',
data: null
}).complete(function (item,data) {
// This doesn't affect the observableArray.
// 'self.Items.pop(data) does, however.
self.Items.remove(data);
});
};
}
And my HTML looks like so:
<div>
<table>
<tbody data-bind="template: { name: 'itemTemplate', foreach: Items }"></tbody>
</table>
</div>
<script type="text/html" id="itemTemplate">
<tr>
<td>
<input data-bind="value: value" />
Remove Item
</td>
</tr>
</script>
You have replaced "data" variable object in the context of response handler:
was:
self.removeItem = function(data) { // <- data
$.ajax({
type: 'POST',
url:'/echo/js/?js=hello%20world!',
dataType: 'json',
contentType: 'application/json',
data: null
}).complete(function (item, data) { // <- another data overrides upper data
// This doesn't affect the observableArray.
// 'self.Items.pop(data) does, however.
self.Items.remove(data); // <- what data to use???
});
};
changed:
self.removeItem = function(data) {
$.ajax({
type: 'POST',
url:'/echo/js/?js=hello%20world!',
dataType: 'json',
contentType: 'application/json',
data: null
}).complete(function (item, data1) { // another data - data1
// This doesn't affect the observableArray.
// 'self.Items.pop(data) does, however.
self.Items.remove(data);
});
};
I've updated the fiddle, it works for me - at least removes items.
You need to use the data variable that is passed into removeItem. Instead you override it, by using the textStatus variable of the complete callback. Like so:
self.removeItem = function(data) {
$.ajax({
type: 'POST',
url:'/echo/js/?js=hello%20world!',
dataType: 'json',
contentType: 'application/json',
data: null
}).complete(function (item) {
self.Items.remove(data);
});
};
The reason self.Items.pop(data) worked is because .pop doesn't actually take any parameters. So the data you passed in is never used, and the call is just popping the array. The second parameter in the complete callback method is by default a textStatus response.
From the documentation:
http://api.jquery.com/jQuery.ajax/
complete
Type: Function( jqXHR jqXHR, String textStatus )
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror").
Here I am using codeigniter with highchart. Highchart will change after dropdown select by calling ajax.
Here, function is called but ajax is not calling. So, where I go wrong with this.
This is my ajax:
$('.edit').click(function(e)
{
e.preventDefault();
$.ajax({
url: '<?php echo site_url("Chart/branchwiseactivity");?>',
type: 'POST',
data: {
series: []
},
dataType: 'json',
success: function(json)
{
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
options.series[3] = json[4];
chart = new Highcharts.Chart(options);
}
});
e.preventDefault();
});
I implemented Django ajax comment submission in my app using Nick Carroll's method here. I'd like the user that posted the comment, date of submission and comment to appear on the page using ajax after the server has received and saved it. What's a good way to do this?
Use jquery's post method to post the comment to server and on successful response,display the comment on the page from the success call back function.
Alright this is kind of a hackerish way to go about this, but I think I've figured out a decent solution:
<script type="text/javascript" charset="utf-8">
function bindPostCommentHandler() {
$('#comment_form form input.submit-preview').remove();
$('#comment_form form').submit(function() {
var comment_text = $('#id_comment').val();
$.ajax({
type: "POST",
data: $('#comment_form form').serialize(),
url: "{% comment_form_target %}",
cache: false,
dataType: "html",
success: function(html, textStatus) {
$('#comment_form form').fadeTo(500, 0, function(){
$(this).remove();
});
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var today = mm+'/'+dd+'/'+yyyy;
var comment = "<div class='comment'><h4>User " + "\"{{ user.username }}\"" + " Rating <small>" + today + "</small></h4>" + comment_text + "</div><hr />";
$(comment).hide().prependTo("#comments_loc").fadeIn(1000);
bindPostCommentHandler();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#comment_form form').replaceWith('Your comment was unable to be posted at this time. We apologize for the inconvenience.');
}
});
return false;
});
}
$(document).ready(function() {
bindPostCommentHandler();
});
</script>
I'm relatively new to javascript so I put this together with what little I know. Feel free to leave some comments if you think this could be cleaned up.
<script type="text/javascript" charset="utf-8">
function bindPostCommentHandler() {
$('#comment_form form input.submit-preview').remove();
$('#comment_form form').submit(function() {
$.ajax({
type: "POST",
data: $('#comment_form form').serialize(),
url: "{% comment_form_target %}",
cache: false,
dataType: "html",
success: function(html, textStatus) {
$('#comment_form form').replaceWith(html);
$('.comt_message').show();
bindPostCommentHandler();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#comment_form form').replaceWith('Your comment was unable to be posted at this time. We apologise for the inconvenience.');
}
});
return false;
});
}
$(document).ready(function() {
bindPostCommentHandler();
});
</script>