I have the following code that will hide the list-btn div and load the list-response div. It may however take 1-5 seconds for the list-response div to load, so I'd like to make it show a div called list-waiting while that happens and then once list-response shows, hide the list-waiting again.
They are all in the same place, basically replacing eachother, so I need to show one of them at a time only.
How would I do that?
jQuery(document).ready(function($){
$('.add-to-list').click(function (e) {
e.preventDefault();
var id = $(this).data("id");
$.ajax({
url: "https://www.domain.com/page.php?add=" + id,
type: "GET",
success: function (data) {
$("#list-btn-" + id).hide();
$("#list-response-" + id).show();
},
error: function (xhr, ajaxOptions, thrownError) {
$("#list-btn-" + id).hide();
$("#list-response-" + id).html('ERROR');
},
timeout: 15000
});
});
});
Hide list-btn and show list-waiting div just before AJAX call. Then hide list-waiting div in callbacks before showing list-response div.
jQuery(document).ready(function($){
$('.add-to-list').click(function (e) {
e.preventDefault();
var id = $(this).data("id");
$("#list-btn-" + id).hide();
$("#list-waiting-" + id).show();
$.ajax({
url: "https://www.domain.com/page.php?add=" + id,
type: "GET",
success: function (data) {
$("#list-waiting-" + id).hide();
$("#list-response-" + id).show();
},
error: function (xhr, ajaxOptions, thrownError) {
$("#list-waiting-" + id).hide();
$("#list-response-" + id).html('ERROR');
},
timeout: 15000
});
});
});
If you are using jQuery 1.8 or higher, I would suggest
jQuery(document).ready(function($){
$('.add-to-list').on("click",function (e) {
e.preventDefault();
var id = $(this).data("id");
$("#list-btn-" + id).hide();
$("#list-response-" + id).empty().hide();
$("#list-waiting-" + id).show();
$.ajax({
url: "https://www.domain.com/page.php?add=" + id,
type: "GET",
timeout: 15000
}).done(function (data) {
$("#list-response-" + id).html(data).show();
}).fail(function (xhr, ajaxOptions, thrownError) {
$("#list-response-" + id).html('ERROR').show();
}).always(function() {});
$("#list-waiting-" + id).hide();
});
});
});
Another way to accomplish this would be "beforeSend". Just like you have events like "success" and "error", there is a "beforeSend" event:
$.ajax({
url: "the.url.org",
beforeSend: function() {
$("#list-waiting-" + id).show();
//doStuff
},
success: function() {
$("#list-waiting-" + id).hide();
//doOtherStuff
}
})
Related
I got an interface that sends (FROMDATE and TODATE) to the MSSQl and retrieves the selected details and after receiving them the data is shown on the grid.
I'm using the MVC.
This is the js script that I'm using.
$('body').on('submit', '#form', function (e) {
e.preventDefault();
$('#btnSubmit').html('<i class="fa fa-refresh fa-spin" style="font-size:14px"></i> Please wait ....');
$('#btnSubmit').prop('disabled', true);
var fromdate = $('#PeriodFrom').val();
var todate = $('#PeriodTo').val();
if ($('#PeriodFrom').val() > $('#PeriodTo').val())
{
ToastMessage("To date cannot be less than From date ");
return false;
}
debugger;
$.ajax({
url: '/ReservationInquiries/ReservationInquery?fromdate=' + fromdate + '&todate=' + todate,
dataType: 'JSON',
method: 'GET',
beforeSend: function () {
$('#btnSubmit').html('<i class="fa fa-refresh fa-spin" style="font-size:14px"></i> Please wait ....');
$('#btnSubmit').prop('disabled', true);
},
complete: function () {
$('#btnSubmit').html('Save');
$('#btnSubmit').prop('disabled', false);
},
success: function () {
FillGrid();
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
url: '/ReservationInquiries/ReservationInquery?fromdate=' + fromdate + '&todate=' + todate,
When the user picks the date range.By using the following URL it sends the Fromdate and Todate toward the controller then the Service and then the Entry.
It returns backs ReservationNo and Name from MSQL.
So according to my program, everything is fetched to the model (the values which is fetched from MSQL).
As you can see when it redirects back I'm calling a function called **FillGrid();**in my js.
function FillGrid() is the function that I'm using to draw the grid in the HTML.
Even the data is fetched nothing is displayed on my grid is this wrong?
can anyone help me?
function FillGrid() {
debugger;
if ($('#grid').length == 1) {
$('#grid tr').not(':first-child').remove();
$.ajax({
//url: '/ReservationInquiries/select?search=' + $('#txtSearch').val(),
//dataType: 'JSON',
beforeSend: function () {
$('.grid').hide();
$("#loadingProjects").show();
},
complete: function () {
ShowGrid();
$("#loadingProjects").hide();
},
method: 'POST',
success: function (data) {
debugger
//var inquirieslist = JSON.stringify(data.InqueryList)
$('#grid tr:not(:first)').empty();
if (inquirieslist != null) {
$.each(inquirieslist, function (index, item) {
$('<tr>' +
'<td>' + item.ReservationNo + '</td>' +
'<td>' + item.Name + '</td>' +
'</tr>').appendTo($('#grid'));
});
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
}
}
For the past few days I have been trying to populate the Google Tag Manager datalayer on the OpenCart product page when the button "Add to Cart" is clicked.
I understand that I need to use the push method, but I can't figure out where to nest it since I have no HTML button just a JavaScript function.
The function:
<script type="text/javascript"><!--
$('#button-cart').on('click', function() {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('#product input[type=\'text\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').button('loading');
},
complete: function() {
$('#button-cart').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
var element = $('#input-option' + i.replace('_', '-'));
if (element.parent().hasClass('input-group')) {
element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
} else {
element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
}
}
}
if (json['error']['recurring']) {
$('select[name=\'recurring_id\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
}
// Highlight any found errors
$('.text-danger').parent().addClass('has-error');
}
if (json['success']) {
$('.breadcrumb').after('<div class="alert alert-success">' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
$('#cart > button').html('<i class="fa fa-shopping-cart"></i> ' + json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
I turned the internet up side down but found no solution to this. Any help is appreciated.
In the code from your question you have already initialized the click handler for the "Add to cart" button. Put your dataLayer logic inside the click handler.
$('#button-cart').on('click', function() {
window.dataLayer = window.dataLayer || [];
dataLayer.push({
'event': 'button-add-to-cart-click'
});
// other code
});
I am trying hard to fix this issue but still didn't get the solution, tried many links and code, but facing a bit problem to fix this.
ISSUE:
I have an input type 'Text' to search the employees name.
When I Start entering characters like 'WY', it shows all the names starting with WY.
Once I get the employee I need, I can move that to other control and Run PDF report (which loads in another Tab).
The issue is when I go back to the page where I should start searching the employees again, it won't search! as shown below:
Here is my ajax code :
$("#EmployeeSearchBox").bind('input propertychange', function () {
if ($('#EmployeeSearchBox').val() != '') {
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
UI Control :
<input type="text" id="EmployeeSearchBox" class="search-box" aria-multiselectable="true" />
Please let me know, what I should be doing to get it fixed.
This might be the reason for the issue
The $("#EmployeeSearchBox").bind('input propertychange', function () { ..}); might not be available in the DOM.
To ensure whether the EmployeeSearchBox and propertyChange handler are still alive, place an alert inside the propertychange function. If the alert is shown then the issue is some where else.
$("#EmployeeSearchBox").bind('input propertychange', function () {
if ($('#EmployeeSearchBox').val() != '') {
alert("Inside Property Change "); // Add this alert
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
what do you mean by bind it again
This is the function which is binding the EmployeeSearchBox with the DOM $("#EmployeeSearchBox").bind('input propertychange', function () {.... and when you are moving to the PDF tab and coming back again to SearchBox tab the binding of this element is lost, it means the DOM doesnot know what to be done when the property change is fired on the EmployeeSearchBox. Two ways to solve it
1) Ensure that the Event handler is always present in the DOM even when you navigate between tabs.
2) If option 1 is not achievable in your scenario, kindly rebind the event handlers whenever you are coming to the search tab. Explicitly invoke this $("#EmployeeSearchBox").bind when you are in the search tab.
Please check that the ajax call has raised for your second search.. if not there must be a problem in condition checking area or function calling method. I always use this function for searching data
$("input").change(function(){
ajax call.....
})
Am upvoting the suggestion provided from "Clement Amarnath", which helped me to resolve this issue.
I found the fix for this , instead of using .Bind(), I used .on() inside (document), am posting the answer which I have fixed it.
Thanks all!
$(document).on("input propertychange", "#EmployeeSearchBox", function () {
if ($('#EmployeeSearchBox').val() != '') {
$('#EmployeeList').empty();
$.ajax({
type: "GET",
url: "SomeSelectionPage.aspx/GetEmployees",
data: { 'searchText': "'" + $("#EmployeeSearchBox").val() + "'" },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//alert('success');
if (data.d.length > 0) {
$("#EmployeeList").removeClass("hideControl").addClass("showControl");
}
else {
$("#EmployeeList").removeClass("showControl").addClass("hideControl");
// $('select').multipleSelect();
alert("No data");
}
$.each(data.d, function (index, value) {
$('#EmployeeList').append($('<option>').text(value.FullName).val(value.EmployeeId));
});
},
//error: function (XMLHttpRequest, textStatus, errorThrown) {
// alert(textStatus);
//}
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
}
else {
$('#EmployeeList').empty();
$("#EmployeeList").addClass("hideControl");
}
});
NOTE :
below line too works :
.live() method
$("#EmployeeSearchBox").live('input propertychange', function () {... });
I can't appear to select the child form of a div I have for some reason.
For the matter, I am trying to find a way that I can have a function select the child form of a div since I have it changing for a toggling function at my site.
$(document).ready(function(){
$("#soundToggle, #soundOffForm").submit(function(event){
/*var r = new XMLHttpRequest();
r.open("POST", "sessionsetter.php", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
r.send("a=1&b=2&c=3");*/
alert("post");
event.preventDefault();
$.ajax({
type: "POST",
url: "sessionsetter.php",
data: {
sound : '0',
},
success: function(data) {
//alert("Sound toggled successfully: " + data);
$('#soundToggle').load(location.href + " #soundOnForm");
},
error: function(data) {
alert("Error in processing request: " + data);
}
});
});
$("#soundToggle, #soundOnForm").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "sessionsetter.php",
data: {
sound : '1',
},
success: function(data) {
//alert("Sound toggled successfully: " + data);
$('#soundToggle').load(location.href + " #soundOffForm");
},
error: function(data) {
alert("Error in processing request: " + data);
}
});
});
});
Anyone have any suggestions on how I can make this a possibility? Thanks. When I don't select the child of a form, the handler is destroyed as I replace the form in my DOM.
The jquery binding will be lost if the Dom is reconstructed after page loads, you may want to use this:
Assumption here is #soundToggle is the div that contains form
$("#soundToggle, #soundToggle form").submit(function(event){
if($("#soundToggle form").attr('id') == "soundOnForm"){
//do on functionality
} else if($("#soundToggle form").attr('id') == "soundOffForm"){
//do off functionality
}
}
Here is the code to call webservice to return json
$('#page_job_list_pages').live('pageshow',function(){
try {
$.ajax({
url: "http://domain.com/json/" + encodeURIComponent(tid),
type: 'get',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('page_job_list_pages - failed to retrieve pages');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$("#page_job_list_pages_list").html("");
$.each(data.nodes,function (node_index,node_value) {
console.log(JSON.stringify(node_value));
if(node_index != 0) {
var companyName = node_value.node.field_basic_info.match("Company:(.*)date");
$("#page_job_list_pages_list").append($("<li></li>",{"html":"<a href='#node_view' id='" + node_value.node.Nid + "' class='page_job_list_pages_list_title'>" + companyName[1] + "</a>"}));
}
});
$("#page_job_list_pages_list").listview("destroy").listview();
$("#page_job_list_pages_list").append('<a onclick="()" data-role="button" data-theme="a">TEST</a>');
}
});
}
catch (error) { alert("page_job_list_pages_list - " + error); }
});
this line is a button
$("#page_job_list_pages_list").append('<a onclick="()" data-role="button" data-theme="a">TEST</a>');
i want to call the jquery function to query the json again.
HOW to do that?
I've wrapped your query in a function. I am assuming this is what you want. I've also added the call in the click handlers of your buttons to query again.
Note:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). (Source: http://api.jquery.com/live/)
$('#page_job_list_pages').live('pageshow',function(){
queryJSON();
});
function queryJSON(){
try {
$.ajax({
url: "http://domain.com/json/" + encodeURIComponent(tid),
type: 'get',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('page_job_list_pages - failed to retrieve pages');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$("#page_job_list_pages_list").html("");
$.each(data.nodes,function (node_index,node_value) {
console.log(JSON.stringify(node_value));
if(node_index != 0) {
var companyName = node_value.node.field_basic_info.match("Company:(.*)date");
$("#page_job_list_pages_list").append($("<li></li>",{"html":"<a href='#node_view' id='" + node_value.node.Nid + "' class='page_job_list_pages_list_title'>" + companyName[1] + "</a>"}));
}
});
$("#page_job_list_pages_list").listview("destroy").listview();
$("#page_job_list_pages_list").append('<a onclick="queryJSON();" data-role="button" data-theme="a">TEST</a>');
}
});
}
catch (error) { alert("page_job_list_pages_list - " + error); }
}
this line is a button
$("#page_job_list_pages_list").append('<a onclick="queryJSON();" data-role="button" data-theme="a">TEST</a>');