Datatables, change AJAX data ( not with elements ) - javascript

I have a Datatable which is getting populated by AJAX. All is good but i want to have some shortcuts to request data from the server. Problem is how can i change the data i'm sending on the fly ? I know i can create an element <input> or something and it can get the value from that, but i was hoping i could change the data once something is clicked.
var Table = $('#table').DataTable({
"ajax": {
"type" : "POST",
"url": "url",
"data": function ( d ) {
d.cmd = "offline";
}
},
});
This works fine and passes the cmd as offline back to the server.
How can i change that value on click before the ajax.reload is called.
$('#online_btn').on( 'click', function () {
Table.ajax.reload();
} );
Using this
$('#online_btn').on( 'click', function () {
var d = [];
d.cmd = "online";
Table.ajax.data(d);
Table.ajax.reload();
} );
Gives back an ajax.data is not a function error

You could modify an object and use $.extend() to merge within the data function
var myData ={};
var Table = $('#table').DataTable({
"ajax": {
"type" : "POST",
"url": "url",
"data": function ( d ) {
return $.extend(d, myData);
}
},
});
$('#online_btn').on( 'click', function () {
myData.cmd = "online";
Table.ajax.reload();
});

Use jquery ajax beforesend object.
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
//update your value here
}
})
source: jquery documentation
beforeSend
Type: Function( jqXHR jqXHR, PlainObject settings )
A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.

I do this in 2021:
function customSearch(){
let t = JSON.parse(window.filter);
t["custom-field"] = $('input[name="custom-field"]').val() || "";
window.filter = JSON.stringify(t);
return window.filter;
}
const table = $('#table').DataTable({
ajax:{
url:"my-wonderful-url.json",
type:"POST",
data: function(d) {
const t = customSearch();
return Object.assign(d, {filter:t});
},
error:function(e){console.log(e);},
});
$('input[name="custom-field"]').on('keyup', function(e){
table.ajax.reload(null, false);
});

Related

Why does my jquery plugin cannot access or utilize a data or vaiable from my script?

I have this custom made jQuery plugin, whenever I called it in my script, the option parameter row cannot access the variable or data defined on my script.
JQuery Plugin:
{
$.fn.dbGrid = function (options) {
var settings= $.extend({
read: function () { },
row:""
}, options)
settings.read.call(this)
//console.log(settings.row)
//It ouputs nothing
}
Usage on my Script:
var rows;
function onSuccess(data) {
rows = data;
}
function populateTable() {
$("#container").dbGrid({
read: function () {
$.ajax({
url: "some url",
success: onSuccess,
dataType: "json",
async: false,
type: "GET"
});
},
row:rows
//here the option `row` can not access my `rows` defined in my script, thats why it cannot yield result in my plugin whenever I do console.log
})
//console.log("Row in Base script" + rows);
//Here it outputs the result I want which is data from the function onSuccess
}
populateTable();
}

MVC5 Ajax update

I have a dropdown with selection id StaffId. What I am doing is once an item is selected I want to pass on the StaffId to controller to fetch records in a database using the staffId. This is giving an error on page load without passing the StaffId to the controller. below is the snippet
controller
[HttpPost]
public PartialViewResult GetStaffPosts(int? id)
{
var sPost = db.StaffPosts.Where(a => a.StaffId == id.Value);
return PartialView(sPost.ToList());
}
<div id="divPartialView">
#{Html.RenderPartial("GetStaffPosts");}
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
$.ajax(options);
}
});
});
</script>
Your current code is not actually making an ajax call on the change event because you are invoking the $.ajax(options); call inside the success callback of the options object. You are not calling the $.ajax method on the change event!
This should work (assuming your controller code is returning a 200 response).
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
options.type= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
You may also simplify your code using the $.post method.
$("#StaffId").change(function() {
$.post("/StaffPost/GetStaffPosts/",{ id: $(this).val() } ,function (data) {
$("#divPartialView").html(data);
});
});
Or even using the $.load method and a one liner
$("#StaffId").change(function(event) {
$("#divPartialView").load("/StaffPost/GetStaffPosts/", { id: $(this).val() });
});
Hi just put your ajax call outside of the success function and make an url like the below code and try again
Your changed code:
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "../StaffPost/GetStaffPosts,
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest)
{
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
});
</script>

How to optimize (minimize) jQuery AJAX calls

I have over 50 AJAX calls from different functions of my code. All these calls have a similar structure with different data/url/callback params:
var jqXHR = $.post('/dba/port.php', {
mode: "del_wallfunds",
pdata: cdata,
wname: wName
},
function (data) {}, "json")
.done(function (data) {
var msg = data.msg;
if (msg.indexOf("Error") == -1) {
alertify.success(msg);
delSelected(selGroup);
} else {
alertify.error(msg);
}
})
.fail(function () {
alertify.error("Error .....");
});
I am thinking how to write a function that would return that var jqXHR to minimize the total size of the code. It is not a problem to pass all static variables like URL, error strings etc. But the problem is that all callback functions on ".done" are different and I don't know how to pass these callback functions as variables.
One way would be to call a single "universal" function on .done and pass a "switch" variable to that function, but it doesn't seem to be an elegant solution.
Any suggestions how to it in some elegant way?
Thanks
Either pass the done callback function as an argument when calling your function:
function ajaxCall(url, data, doneCallback) {
return $.post(url, data, doneCallback, "json").fail(...);
// or
return $.post(url, data, function() {}, "json").done(doneCallback).fail(...);
}
var jqXhr = ajaxCall('yoururl.php', {key: 'value'}, function(data) {
// do something
});
Or return the jqXhr object from the function, and assign the done callback then:
function ajaxCall(url, data) {
return $.post(url, data, function() {}, "json").fail(...);
}
var jqXhr = ajaxCall('yoururl.php', {key: 'value'});
jqXhr.done(function(data) {
// do something
});
Alternatively switch to using jQuery.ajax() instead, and pass the entire options object in:
function ajaxCall(options) {
return $.ajax(options).fail(...);
}
var jqXhr = ajaxCall({
url: 'yoururl.php',
data: {key: 'value'},
dataType: 'json'
});
jqXhr.done(function(data) {
// do something
});
You can try to :
turn "request successfully returned a treatment error" into a "rejected request",
put the "alertify" processing in a common callback
Here is a sketch of what this could give :
function myAjaxApi(url, data){
var myAjaxCall = $.post(url, data, function (data) {}, "json")
.then(function (data) {
// using .then : change "request succesful with error state"
// to "rejected state"
var msg = data.msg;
if (msg !== undefined && msg.indexOf("Error") >= 0) {
var dfd = $.Deferred();
// try to match the same signature as the "error" option
dfd.reject(this, msg);
return dfd;
} else {
return data
}
});
myAjaxCall.done(function(data){
if (data.msg) {
alertify.success(data.msg);
}
}).fail(function (jqxhr, msg) {
if (!msg) { msg = "Error ....."; }
alertify.error(msg);
});
return myAjaxCall;
}
//usage
myAjaxApi('/dba/port.php', {mode: "del_wallfunds", pdata: cdata, wname: wName})
.done(function (data) {
// the ".done()" queue will not be executed if msg contains "Error" ...
delSelected(selGroup);
});
Some parts should be written with more care ; the above example is meant to illustrate how you can wrap your repeated ajax calls inside a common api.

Extending jQuery ajax success globally

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0
Sample response
{"code": "0", "message": "your code is broken"}
or
{"code": "1", "data": "return some data"}
I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.
You can build your own AJAX handler instead of using the default ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaults
success: function(data){ //hijack the success handler
if(check(data)){ //checks
callback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaults
return $.ajax(options); //send request
}
so your call, instead of $.ajax, you now use;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
This solution transparently adds a custom success handler to every $.ajax() call using the duck punching technique
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return _oldAjax(options);
};
})();
Here's a couple suggestions:
var MADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
function ajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
function ajaxSuccess(data) {
console.log(data);
}
function ajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
//
// setup with ajaxSuccess() and call ajax as usual
//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------
// or
// ----------------------------------------------------
//
// declare the handler right in your ajax call
//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});​
Working: http://jsfiddle.net/pF5cb/3/
Here is the most basic example:
$.ajaxSetup({
success: function(data){
//default code here
}
});
Feel free to look up the documentation on $.ajaxSetup()
this is your call to ajax method
function getData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
and after that callback success or method success
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});

JavaScript functions not defined?

For some reason, Firefox is throwing "function not defined" errors at this piece of JS:
$(function() { // on document ready
function updateAlerts() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'checkAlerts'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
// Update the DOM to show the new alerts!
if (response.friendRequests > 0) {
// update the number in the DOM and make sure it is visible...
$('#notifications').show().text(response.friendRequests);
}
else {
// Hide the number, since there are no pending friend requests or messages
var ablanknum = '0';
$('#notifications').show().text(ablanknum);
}
}
});
}
function friendRequestAlert() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'sendFriendAlert'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
if (response.theFRAlert !== '0') {
// Display our fancy Javascript notification.
$.jgrowl('' + response.theFRAlert + '');
}
}
});
}
function messageAlert() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'sendMessageAlert'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
if (response.theAlert !== '0') {
// Display our fancy Javascript notification.
$.jgrowl('' + response.theAlert + '');
$('#therearemessages').show().text(response.theAlert);
}
}
});
}
});
I checked through my code and nothing seems to be wrong.
There is no reason to wrap your 3 functions in the document ready wrapper--nothing inside those functions (which may rely on the doc being ready) is executed until they are called. Further, by wrapping them in doc ready, you're forcing them into the scope of that anon function and they cannot be used from outside of it.
Unrelated, you should set your dataType to 'json' on the $.ajax calls and stop making manual calls to $.parseJSON.
New code:
function updateAlerts()
{
$.ajax( {
url: '/check.php',
type: 'POST',
data: {
method: 'checkAlerts'
},
dataType: 'json',
success: function( response )
{
// Update the DOM to show the new alerts!
if( response.friendRequests > 0 )
{
// update the number in the DOM and make sure it is visible...
$( '#notifications' ).show().text( response.friendRequests );
}
else
{
// Hide the number, since there are no pending friend requests or messages
var ablanknum = '0';
$( '#notifications' ).show().text( ablanknum );
}
}
} );
}
function friendRequestAlert()
{
$.ajax( {
url: '/check.php',
type: 'POST',
data: {
method: 'sendFriendAlert'
},
dataType: 'json',
success: function( response )
{
if( response.theFRAlert !== '0' )
{
// Display our fancy Javascript notification.
$.jgrowl('' + response.theFRAlert + '');
}
}
} );
}
function messageAlert()
{
$.ajax( {
url: '/check.php',
type : 'POST',
data: {
method : 'sendMessageAlert'
},
dataType: 'json',
success: function( response )
{
if( response.theAlert !== '0' )
{
// Display our fancy Javascript notification.
$.jgrowl('' + response.theAlert + '');
$('#therearemessages').show().text(response.theAlert);
}
}
} );
}
Scope in javascript is function based.
Since you define the 3 functions inside a function that is run on DOMready and then goes out of scope, so does the funcitons.
In other words: the 3 functions only exist inside the DOmready function, and you cannot use them from anywhere else outside that function.

Categories

Resources