Ajax call onchange of date - javascript

I am using daterangepicker.js, onchange of date i have to call the getchart method
when i change the date i need to call a getchart(), can anyone help me out in this
here is my code:
$(document).ready(function() {
$('#dateRangeSelector').daterangepicker(); //textbox id
var start = Date.today().setTimeToNow();
var end = Date.today().setTimeToNow();
var displayValue = start.toString("yyyy/MM/dd") + " - " + end.toString("yyyy/MM/dd");
$('#dateRangeSelector').val(displayValue);
var host = '<?=$host ?>'
var dateRangeSelector = $("#dateRangeSelector").val();
var dates = dateRangeSelector.split(" - ");
var value = "'"+dates.join("' , '")+"'";
var array = value.split(',');
var startTime = array[0];
var endTime = array[1];
$.get(SITE_URL + 'admin/SystemMonitor/charts/getChartsData', {'host' : host,'startTime' : startTime,'endTime' : endTime}, function(response){
console.log("viewCharts", response);
obj = response;
//bootbox.alert(obj.status, obj.label);
if (obj.status == 'OK') {
$('.one_half').show();
showMonitoringServer(host, obj);
} else {
show_message('Show Chart Error -' +host, 'Unexpected error occured! Please try again later!', 'error' );
}
}, "json");
});

Have you tried the onChange event?
$('#dateRangeSelector').daterangepicker({
onChange: function(){
//do ajax stuff
}
);
There seems to be a known issue with onChange getting called twice. If it hasn't been fixed in your version, you can always use:
$('#dateRangeSelector').on('blur', function(){
//do ajax stuff
});
I added a callback function for onChange now that you might be able use. Keep in mind that it may not fit your needs exactly because it will fire on EVERY change that occurs in the input. One-click range shortcuts will actually fire 2 change callbacks because this plugin simply triggers date changes on each datepicker, one at a time. Once this plugin is adopted by jQuery UI, I’m sure we’ll work that part out and have the rangepicker firing events as one widget. For now, you’ll need to set up your page with this issue in mind.

Try this.
$(document).ready(function() {
$('#dateRangeSelector').change(function(){
$.get(SITE_URL + 'admin/SystemMonitor/charts/getChartsData', {'host' : host,'startTime' : startTime,'endTime' : endTime}, function(response){
console.log("viewCharts", response);
obj = response;
//bootbox.alert(obj.status, obj.label);
if (obj.status == 'OK') {
$('.one_half').show();
showMonitoringServer(host, obj);
} else {
show_message('Show Chart Error -' +host, 'Unexpected error occured! Please try again later!', 'error' );
}
}, "json");
});
});

You can use
$( "#dateRangeSelector" ).change(function() {
alert( "Handler for .change() called." );
});
You can also have a look at the Jquery API: http://api.jquery.com/change/

From the documentation itself shows:
Follow this link of documentation
$('#dp5').datepicker().on('changeDate', function(ev){
if (ev.date.valueOf() < startDate.valueOf()){
....
}
});
so you need to do this way:
$('#dateRangeSelector').datepicker().on('changeDate', function(ev){
$.get(SITE_URL + 'admin/SystemMonitor/charts/getChartsData', {'host' : host,'startTime' : startTime,'endTime' : endTime}, function(response){
console.log("viewCharts", response);
obj = response;
//bootbox.alert(obj.status, obj.label);
if (obj.status == 'OK') {
$('.one_half').show();
showMonitoringServer(host, obj);
} else {
show_message('Show Chart Error -' +host, 'Unexpected error occured! Please try again later!', 'error' );
}
}, "json");
});

Related

Wordpress Back-end Javascript Error

I've created a Custom Admin page on wordpress back-end, and have this basic html structure,
<ul data-status="available">
<li class="available">AVAILABLE</li>
<li class="onleave">ONLEAVE</li>
</ul>
When I use js code below, it works fine
$('ul').each( function() {
var status = 'available';
$(this).find('li.' + status ).addClass('active');
});
While this code below also works (it adds class on element), However it, produces an error
$('ul').each( function() {
var status = $(this).data('status');
$(this).find('li.' + status ).addClass('active');
});
Error on Console
Syntax error, unrecognized expression: li. load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=4.4.1:2
(9 Errors) Cannot read property 'hasClass' of undefined load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,svg-painter,heartbeat,wp-auth-check,thickb…:246
Any clear explanation would be highly appreciated
FULL JS CODE
( function($) {
'use strict';
$(document).ready( function() {
$('ul').each( function() {
var status = $(this).attr('name');
//$(this).find('li.' + status ).addClass('active');
});
$('form').on('click', 'li', function() {
var currentStatus = $(this).parent().attr('name');
var id = $(this).parent().attr('id');
var status = $(this).attr('name');
var input = '<input id="model-'+id+'" type="hidden" name="'+id+'" value="'+status+'" />'
if( currentStatus !== status || !currentStatus ) {
$('form').prepend( input );
} else {
$('form').find('#model-'+id).remove();
}
$(this).parent().find('li').removeClass('active');
$(this).addClass('active');
});
$('form').submit( function(e) {
e.preventDefault();
console.log( $( this ).serialize() );
});
});
})(jQuery);
A quick (although not very nice solution) would be to check the value/type of status and jump out of the .each() loop if it is not defined:
$('ul').each( function() {
var status = $(this).attr('name');
if (typeof status === "undefined" || !status) {
return false;
};
$(this).find('li.' + status ).addClass('active');
});
As I mentioned it is generally a bad idea to loop through ALL elements of a type on a page. It would be better to loop through a set of elements with a given class.
Try with this:
$('ul').each( function() {
var status = $(this).attr('data-status'); //note: data-status, not status
$(this).find('li.' + status ).addClass('active');
});
.data() method is for setting/getting object level data not represented visually in the Dom. You, however, are using attributes, which has a different accessor in jQuery (.attr()).
See here:
https://api.jquery.com/data/
and here
http://api.jquery.com/attr/

Execute completeAjax only once

I need to fire a function on completion of an already running ajax on the page. The function I want to update will update wishlist item counter and the function which is previously running saves item in wishlist.
The problem is (what I've figured out) - after making (initializing) ajax request, while waiting for success msg, the function again executes itself.
Bottom line, I want ajaxComplete function part to run only once ever. Please point me in right direction
jQuery(document).ready( function() {
var token = false;
jQuery( '.add_to_wishlist' ).on( 'click', function() {
if( token == false ) {
jQuery(document).ajaxComplete(function() {
console.log('Entered Click!');
token = true;
jQuery.ajax({
url: wishajax.ajax_url,
data: {
action: 'vg_inject_wish',
},
success: function( response ) {
console.log('Entered Success!');
jQuery( '.wishlist-container' ).html( response );
console.log('After Success!');
token = true;
}
});
});
}
});
});
jQuery(document).ajaxComplete is an independent event. Why are you combining it inside click event and writing again jQuery.ajax inside it? Separate the concerns as below:
jQuery(document).ajaxComplete(function() {
token = true;//If you need this only in success then no need to put it here as this
//will get executed irrespective of ajax result
});
jQuery( '.add_to_wishlist' ).on( 'click', function() {
if( token == false ) {
jQuery.ajax({
url: wishajax.ajax_url,
data: {
action: 'vg_inject_wish',
},
success: function( response ) {
console.log('Entered Success!');
jQuery( '.wishlist-container' ).html( response );
console.log('After Success!');
token = true;
}
});
}
});
maybe this can help you to
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
// Usage
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada
taken from the blog of David Walsh.

jQuery - Detect value change which use .val() function

We all know that use the val() will not trigger the change event, so we also use .trigger('change') behind the val().
But the problem is that someone write the val() did't with trigger() and it's a external file that I can't edit it.
So, how can I detect value change through some code same like below:
$('.elem').on('change', function(){
// do something
});
My suggestion is to override jquery's val()
var originalValFn = jQuery.fn.val;
jQuery.fn.val = function() {
this.trigger('change');
originalValFn.apply( this, arguments );
}
jsfiddle: http://jsfiddle.net/2L7hohjz/js
var originalValFn = jQuery.fn.val;
function getErrorObject(){
try { throw Error('') } catch(err) { return err; }
}
jQuery.fn.val = function() {
if ($(this).hasClass( "element" )) {
var err = getErrorObject();
var caller_line = err.stack.split("\n")[4];
var index = caller_line.indexOf("at ");
var clean = caller_line.slice(index+2, caller_line.length);
console.log(clean);
console.log(arguments);
}
originalValFn.apply( this, arguments );
};
Try:
setTimeout(function() {
if (currentValue != previousValue)
{
// do something
}
}, 500);
Thank you,
I commonly use the solution from this post to get around problems like this one:
hidden input change event
watchField('.elem', function(){
//do some stuff here
});
function watchField(selector, callback) {
var input = $(selector);
var oldvalue = input.val();
setInterval(function(){
if (input.val()!=oldvalue){
oldvalue = input.val();
callback();
}
}, 100);
}
Try:
$('.elem').on('keyUp', function(){
// do something
});
or
$('.elem').on('lostFocus', function(){
// do something
});
Thank you,

how to fix error "Expected identifier, string or number"

I have been fighting this issue for couple of days now and i am not able to resolve this issue because the line where it says the error is is BLANK. my JS code is below:
$(document)
.ready(
function() {
// THE DEBUGGER SAYS THE ERROR IS IN THIS LINE"(script1028
// expected identifier string or number)".
$(document).ajaxStart(function() {
$('#overlay').show();
});
$(document).ajaxStop(function() {
$('#overlay').hide();
});
var html = "";
$('#zipcode,#telephone').autotab_magic().autotab_filter(
'numeric');
$("#backtoTopholder").click(function() {
window.scrollTo(0, 0);
})
preload([ '../img/AjaxLoader.gif' ]);
$("#startover").click(function() {
})
$("#backtoTopholder").hide();
$(function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('#backtoTopholder').fadeIn();
} else {
$('#backtoTopholder').fadeOut();
}
});
$('#backtoTopholder a').click(function() {
$('body,html').animate({
scrollTop : 0
}, 800);
return false;
});
});
$(".addressMatch").click(function() {
alert("index");
});
preload([ '../img/step1.png', '../img/step2.png',
'../img/step3.png', '../img/step4.png',
'../img/step5.png', '../img/step6.png',
'../img/add_to_cart_button_off.png',
'../img/add_to_cart_button_on.png' ]);
$.ajaxSetup({
cache : false,
global : true
});
$("#existingCustomer").change(function() {
switch (this.value) {
case "No":
$("#WTNRow").hide();
break;
case "Yes":
$("#WTNRow").show();
break;
default:
break;
}
})
$("#plus4")
.click(
function() {
if (!$("#address").val()
|| !$("#city").val()
|| !$("#state").val()) {
alert("In order to do verify the zip code you need to fill out the address,city and state");
return false;
}
var data = $("#searchPackages")
.serialize();
var requestZipCode = $
.ajax({
url : "classes/Dispatcher.php?Ziplookup=1",
type : "POST",
dataType : "text",
cache : 'false',
data : data
});
requestZipCode
.success(function(data) {
var result = data;
if ($.trim(result) == "not found") {
$("#zipCodeReturnmsg")
.html("");
$("#zipCodeReturnmsg")
.html(
"<font color=\"red\">could retrieve a valid zipcode, please review your address and try again.Please select a unit Suffix.</font>");
} else {
$("#zipCodeReturnmsg")
.html("");
$("#zipcode")
.val(
$(
"#zipcode")
.val()
+ $
.trim(result));
$("#zipCodeReturnmsg")
.html(
"<font color=\"green\">zip code retrieved successfully.</font>");
}
});
requestZipCode
.fail(function(jqXHR, error,
errorThrown) {
$("#test").html(
jqXHR.responseText);
});
})
});
I overlooked for extra commas and reserved words and i believe i didn't miss any. Any help to fix this will be very thankful.
I am suing jquery version 1.10.2.
thank you very much
The indentation makes it very hard to read what's going, I believe you're missing a few semicolons. For example:
$("#backtoTopholder").click(function(){
window.scrollTo(0,0);
})
preload(['../img/AjaxLoader.gif']);
should this be:
$("#backtoTopholder").click(function(){
window.scrollTo(0,0);
});
preload(['../img/AjaxLoader.gif']);
?
There is nothing wrong with what you posted here. Your error is elsewhere. Fiddly proof here.
// some code because Stack Overflow complains to JSFiddle links
// without accompanying code...
// even though I just posted the exact same code that OP did
// only with filler functions to stub for code he did not post
// >.<

javascript not displaying login form again

when I click on the log in button the pop up open correctly. But when I close it and again click on the log in button without refreshing the page, it doesn't appear.
my code is:
<script type="text/javascript">
load_login_page = function() {
$.get(HOST_NAME + "e_commerce/ECommerces/ecommerce_login", {}, function(data) {
$("#temp_login_box").html(data);
$.blockUI({
message:$('#temp_login_box'),
css:{
top:($(window).height() - 300) / 2 + 'px',
left:($(window).width() - 800) / 2 + 'px',
width:'620px',
border:'none',
background:'none',
cursor:'default'
},
overlayCSS:{ backgroundColor:'#333' }
});
load_login_ajax_form();
});
};
load_login_ajax_form = function () {
var options = {
beforeSubmit:show_login_request, // pre-submit callback
success:show_login_response // post-submit callback
};
$('#product_info_form').ajaxForm(options);
};
show_login_request = function (formData, jqForm, options) {
return true;
};
show_login_response = function (responseText, statusText, xhr, $form) {
if (responseText == 'ok') {
// $("#temp_login_box").html(responseText);
window.location.href = HOST_NAME + "e_commerce/ECommerces/user_desboard";
//load_login_ajax_form();
} else {
$("#temp_login_box").html(responseText);
load_login_ajax_form();
}
};
hide_login_info = function() {
$.unblockUI();
};
hide_login_info is form closing function. temp_login_box is id to targeted div. please help me out with this code.
Please trace your function load_login_page to check whether $.get called every time.
because you are creating $.blockUI in success of $.get
To check more i need $.unblockUI Code.
But what i suggest is, in unblockUI function either you do empty the div or hide it.
If you hide it then to show on click you have to write $().show(); in $.blockUI function
if it is not the reason
provide $.unblockUI code then might be i can help you.
Note is jquery selector for the div you hide

Categories