dataTable refresh on ajax success - jquery-ui

I have the data table from the jquery plugin dataTables (http://datatables.net/) that I want to refresh upon ajax success. I tried the following code but its not working. Any help will be appreciated
$(document).ready(function() {
oTable = $('#mytable').dataTable();
var fa = 0;
$('#submit tbody td ').click(function() {
var gCard = $('#mytable tbody').delegate("tr", "click", rowClick);
});
function rowClick() {
fa = this;
var id = $("td:eq(1)", this).text();
cardNumber = $.trim(id);
$.ajax({
url : 'myurltopostto',
type : 'POST',
data : {
id : id
},
success : function(data) {
oTable.fnDraw(); //wanted to update here
},
error : function() {
console.log('error');
}
});
}
});

You can use : fnDeleteRow which will take care of refreshing the table html and data internally, look up API details here:
http://datatables.net/ref
oTable.fnDeleteRow( fa );

hello my dears programers... sorry... my inglish is very bad but I help you... my following is this:
<script type="text/javascript">
function Ajax()
{
var
$http,
$self = arguments.callee;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function()
{
if (/4|^complete$/.test($http.readyState)) {
document.getElementById('ReloadThis').innerHTML = $http.responseText;
setTimeout(function(){$self();}, 10000);
$( this ).hide( "slow" );
}
};
$http.open('GET', 'cls_Noticias/last_noticias.php', true);
$http.send(null);
}
}
</script>
</head>
<body>
<script type="text/javascript">
setTimeout(function() {Ajax();}, 10000);
</script>
<div id="ReloadThis">Espere a que la pagina se actualice!</div>
</body>
good life!

Related

Redirect before selecting an item Select2

I'm using Select2 v4.0.3 and I populate the element using ajax.
$("#el").select2({
multiple: true
maximumSelectionSize: 1,
ajax: {
url: url,
data: function (params) {
return {
name: params.term
};
},
processResults: function (data) {
return {
results: $.map(data.results, function(obj) {
return {id: obj.id, text: obj.name, key: obj.key};
}
})
};
}
}
});
I want to redirect the client before a result is selected. The problem is I need the key attribute from the clicked result. To understand better what I want to do, I paste here a snippet that works after the selection is made.
$("#el").on("select2:select", function(e) {
var selected = $(this).select2('data')[0];
location.href = base_url + '?key=' + selected.key;
});
You can use event.params.args.data.id to get the key attribute from the clicked result. So, your code would probably work like:
$("#el").on("select2:select", function(e) {
var selected = event.params.args.data.id;
location.href = base_url + '?key=' + selected;
});
I slightly modified the official Github repositories example to show my point.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<select class="js-data-example-ajax" style="width: 100%">
<option value="3620194" selected="selected">select2/select2</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data.items, function(ghrepo) {
return {
text: ghrepo.archive_url,
id: ghrepo.archive_url
}
})
}
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
},
minimumInputLength: 1
}).on('select2:selecting', function(event, params) {
event.preventDefault();
repoId = event.params.args.data.id;
console.log(repoId);
});
</script>
</body>
</html>

Scoping issue with jQuery UI Widget Factory

I have a scoping problem that i cannot find a solution for in Google here is a simplified version of my code
jQuery.widget( "myNamespace.myPlugin", {
options: {},
_create: function() {
$main = this.element;
},
_init: function() {
$main.text('ajax running');
$.ajax({url:'some/url/path'})
.done(function(data) {
this._callback(data);
});
},
_callback: function() {
$main.text('ajax complete');
}
});
$('.widget_element').myPlugin();
<html>
<head>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
</head>
<div class="widget_element"></div>
</html>
The error i am getting is:
TypeError: this._callback is not a function
Is there a better way of performing this task in within the widget environment?
Thanks
As with most problems, a solution only rears its head AFTER you post a question on SO
Aparently self = this is perfectly valid
jQuery.widget( "myNamespace.myPlugin", {
options: {},
_create: function() {
self = this;
$main = this.element;
},
_init: function() {
$main.text('ajax running');
$.ajax({url:'some/url/path'})
.done(function(data) {
self._callback(data);
});
},
_callback: function() {
$main.text('ajax complete');
}
});
I hope this helps someone in the future

why the function in side of function wont get called?

i have the following reactjs code to generate two dropdown list where the ddlproducts gets loaded by ddlCategories selection. but when i called the function getDataById() and tried to print the ajax populated array data2 to alert(), there was no alert() there were two alerts none of the alerts were prompted. it shown this error message on the IE console,
execution did not reached the function getDataById() 'cus the alert() in that function even didn't execute
SCRIPT438: Object doesn't support property or method 'getDataById'
correction: once the calling of this.props.getDataById() was changed to this.getDataById() it worked
but how do populate the ddlProducts dropdown. how do i access tag of the ddlProducts and then add the options to it?
here is the code:
var gdata=[];
var trStyle = {
'color': 'black',
'border-style' :'solid',
'margin-left':'20%'
};
var HCOMP = React.createClass({
getInitialState:function(){
return{data1:[], data2:[], isMounted:false, selectedValue:0}
},
componentDidMount:function(){
this.getData();
this.setState({isMounted:true})
},
ddlProdCatsChanegeEvent: function(e) {
if (this.state.isMounted)
{
var newV = ReactDOM.findDOMNode(this.refs.refProdCats).value;
var seleValue = newV;
this.setState({selectedValue:newV}, function(){
this.getDataById(this.state.selectedValue);
alert(this.state.data2);
});
}
},
render: function() {
var prodCats = this.state.data1.map(function(ele, index){// <PRODCATSOPTION optValue={ele.ProductCategoryID} optText={ele.Name} />
return <option value={ele.ProductCategoryID} data-key={index}>{ele.Name}</option>
});
prodCats.unshift(<option value={''}>{'---- select category ------'}</option>)
return (<div>Prodcut Category:<br /><select id="ddlCategories" ref="refProdCats" onChange={this.ddlProdCatsChanegeEvent}>{prodCats}</select><br />
Products:<br /><select id="ddlPorducts" ref="refProds"></select><br /></div>
)
},
getDataById:function(catId){
var x = catId;
alert('rec id:'+x);
$.ajax({
url:'http://localhost:53721//Home/GetProductCats?id='+ x,
method:'GET',
success:function(d1){
this.setState({data2:d1});
}.bind(this),
error:function(){
alert('ERROR');
}.bind(this)
})
},
getData:function(){
//ajax here
$.ajax({
url:'http://localhost:53721//Home/GetProductCats',
method:'GET',
success:function(d1){
this.setState({data1:d1});
}.bind(this),
error:function(){
alert('ERROR');
}.bind(this)
})
}
});
var PRODOPTIONS = React.createClass({
render:function(){
return(<option value={this.props.optValue}>{this.props.optText}</option> )
}
});
var PRODCATSOPTION = React.createClass({
render:function(){
return(<option value={this.props.optValue}>{this.props.optText}</option> )
}
});
ReactDOM.render( <HCOMP/>, document.getElementById('d1') );
Try updating ddlProdCatsChanegeEvent to ddlPropCatsChangeEvent.

Multiple ViewModels Knockout with JQuery

I Have this Fiddle
It is working perfectly in the fiddle, but as soon as i put everything in a ASP.NET MVC4 Application the second ViewModel is not loaded!
This normally is only when i add the following Script Tag to my Project
<script src="../../Scripts/jquery.mobile-1.2.0.js" type="text/javascript"></script>
Do i need some JQuery Functions to load the second ViewModel or what did i wrong? ;)
Here is my code:
<form action="" data-bind=" template:{ 'if': loginVM, data: loginVM }">
//SomeCode
</form>
<form action="" data-bind=" template:{ 'if': startVM, data: startVM}">
//Some Code
</form>
<script type="text/javascript">
var masterViewModel = {
loginVM: ko.observable(),
startVM: ko.observable(),
projektUnterbrechen: ko.observable(),
logout : ko.observable(),
projectStartVM: ko.observable()
};
var LoginVM = function () {
var self = this;
self.mandant = ko.observable();
self.user = ko.observable();
self.password = ko.observable();
self.showDetails = function () {
if ((self.user() == "Gregor") && (self.password() == "gregrech")) {
masterViewModel.loginVM(null);
masterViewModel.startVM(new StartVM());
**//alert(masterViewModel.startVM()!=null) //==True**
}
else {
alert("Username oder Passwort falsch");
}
};
};
var StartVM = function () {
self = this;
**//alert(masterViewModel.startVM()!=null) //==False**
//Um weiterzumachen muss man eingeloggt sein
self.favoriten = ko.observableArray([
{
projectName: "Favorit1"
},
{
projectName: "Favorit2"
},
{
projectName: "Favorit3"
}
]);
//Die zuletzt verwendeten Projekte
self.zuletzt = ko.observableArray([
{
lastProjName: "Zuletzt1"
},
{
lastProjName: "Zuletzt2"
},
{
lastProjName: "Zuletzt3"
}
]);
self.showStart = function (projectName, data, event) {
masterViewModel.projectStartVM(new ProjectStartVM(projectName));
masterViewModel.startVM(null);
};
};
masterViewModel.loginVM(new LoginVM());
$(document).on('pageinit', function () {
ko.applyBindings(masterViewModel);
});
</script>
Thank you for your answers
EDIT:
I found out, that i get different Values if i compare my masterViewModel.startVM()!= null even if it has to be the same!
Maybe this helps you!
Please look at the comments with "**" in my Code to understand what i mean
Try to load viewmodel in ready event not pageinit event.
$(document).ready(function () {
ko.applyBindings(masterViewModel);
});

jquery close datepicker when input lose focus

I'm using datepicker inside my input , my last field is the datepicker input , after validating it i want to set focus on another input inside my form , but the problem is the datepicker is not closed even taht it does not have the focus..
how can I close the datepicker when i set the focus on another input field?
(I tried .datepicker("hide"); but it did not worked for me).
UPDATE:
this is my code:
$(function()
{ $( "#test_date" ).datepicker({
dateFormat: "dd/mm/yy"
});
});
//when i call my function:
$( "#test_date" ).datepicker("hide"); //---> this does not work!
Thank's In Advance.
Question Edited to work with the latest version of jqueryUI
JqueryUi auto-closes the datepicker when an element loses focus by user interaction, but not when changing focus with JS.
Where you are calling your function which removes focus from the input assigned a datepicker you also need to call:
$("#test_date ~ .ui-datepicker").hide();
This code is hiding the datepicker which is a sibling (~) of #test_date.
To be dynamic, and using the class assigned by jQueryui you can do:
$(".hasDatepicker").on("blur", function(e) { $(this).off("focus").datepicker("hide"); });
;(function() {
function eventOnFocusDP(e, par) {
if (par.ver == $.fn.jquery) {
if (this.tmr) clearTimeout(this.tmr);
par.lbl1.text(par.msgs[1]);
this.tmr = setTimeout(function() { par.inpNP.focus(); }, par.secs*1e3);
}
}
function eventOnFocusNP(e, par) {
if (par.ver == $.fn.jquery) {
par.lbl1.text(par.msgs[0]);
par.lbl2.text(par.msgs[2]);
}
}
function eventOnBlurNP(e, par) {
if (par.ver == $.fn.jquery) par.lbl2.text("");
}
function eventOnBlurHDP(e, par) {
if (par.ver == $.fn.jquery) {
$(this).off("focus").datepicker("hide");
}
}
function test(secs) {
this.ver = $.fn.jquery;
this.secs = (typeof secs)=='number'?secs:2;
this.msgs = [
'This will lose focus to box below '+this.secs+' seconds after it gains focus.',
'Losing focus in '+this.secs+' seconds!',
'Focus now on bottom box.'
];
this.inpDP = $('[name=datePicker]');
this.inpNP = $('[name=nextPicker]');
this.lbl1 = $('#dPMsg').text(this.msgs[0]);
this.lbl2 = $('#dPMsg2');
var par = this;
this.inpDP.datepicker({ dateFormat: "dd/mm/yy" })
.on('focus', function(e) { eventOnFocusDP.apply(this, [e, par]) });
this.inpNP.on('focus', function(e) { eventOnFocusNP.apply(this, [e, par]) });
this.inpNP.on('blur', function(e) { eventOnBlurNP.apply(this, [e, par]) });
$(document).on('blur', '.hasDatepicker', function(e) { eventOnBlurHDP.apply(this, [e, par]) });
return this;
}
function init() {
window.Test = test;
setTimeout(function() {
$(document).on('change', '.switcher, .switcher-ui', function(e) { if (window.Test) new Test(); });
$(jQueryUISwitcher).trigger('change');
}, 1e3);
}
if (document.readyState == "complete") init();
else jQuery(window).on('load', init);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/cfc32292cbbfa548fb9584db05b2b2fc/raw/4f16f7ee441dfb98aa166a2e84193b14574a46d1/jquery.switcher.js"></script>
<form action="javascript: void 0">
<input type="text" name="datePicker" id="dP" placeholder="mm/dd/yyyy" />
<label for="dP" id="dPMsg"></label>
<hr />
<input type="text" name="nextPicker" placeholder="tab to here" />
<label for="dP" id="dPMsg2"></label>
</form>
<hr />
<hr />
<hr />
Here's a modified solution that worked for me:
$(".hasDatepicker").each(function (index, element) {
var context = $(this);
context.on("blur", function (e) {
// The setTimeout is the key here.
setTimeout(function () {
if (!context.is(':focus')) {
$(context).datepicker("hide");
}
}, 250);
});
});
My version of js:
<script type="text/javascript"> $(function () {
$("#dtp1").on("dp.change", function (e) {
$('#dtp1').data("DateTimePicker").hide();
});
});
I hope it's help you
This worked for me:
$("#datepickerTo").datepicker({
onSelect: function () {
$(this).off( "focus" );
}
});

Resources