auto search (ajax call) is not working after button click - javascript

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 () {... });

Related

select child at beginning of function jquery

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
}
}

exec function before every ajax success callback

I have a website where I rely on a lot of custom API call. My API return always an XML.
Currently, at the start of each and every $.get or $.post I call, I have this snippet :
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
However, I feel this code to be much redundant on one of my page, it's used 15 times.
I tried to use the $(document).ajaxSuccess() but the event.stopPropagation don't seem to work here
Is there a way to "intercept" each and every ajax call responses, do some stuff and possibly prevent the call to other defined success functions ?
I assume that you have something like this in many places in your code
$.ajax({
method: "GET",
url: "someurl.html",
dataType: "xml",
success : function() {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
// ...
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
});
you could create a generic custom ajax function tha you can re-use
function baseAjaxCall(option, sCb) {
var ajaxOptions = {
method: option.method || "GET",
url: option.url,
dataType: option.dataType || "xml",
success : function(data) {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
else {
sCb(root);
}
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
};
//you can check for optional settings
if(option.contentType !== undefined){
ajaxOptions.contentType = option.contentType;
}
$.ajax(ajaxOptions);
}
everywhere in your code you can re-use the baseAjaxCall function
baseAjaxCall({ url: "someurl.html" }, function(root){
// no need to chek for errors here!
});
Hope it's helps!

Have to focus input box twice so on keyup listener works IE9

I have an input box that takes SSN and when inputs value length reach 10 it is suppose to skip the if and do a ajax call. It works fine in all borwsers except IE 9.
There is nothing wrong with the ajax call and it all works fine if I start by focusing the input, blurring it and focus again before i type in it
I've been spending hours trying to figure this out and tried everything i could think of so any help would be welcome.
Thanks
Here is the input, the input binding and then the function it calls on keydown
<input class="paymentInput required" id="payerSsn" type="text" placeholder="Kennitala greiĆ°anda" maxlength="10"/>
$("#payerSsn").on('input keyup change', function () {
GetCustomerInfoFromSsn($(this).val(), 'payer');
});
function GetCustomerInfoFromSsn(ssn, type) {
if (ssn.length < 10) {
$("#" + type + "Ssn").removeClass("done");
$(".paymentInput.autoFill." + type).val("").removeClass("done");
return;
}
if (store.vefur)
$(".paymentInputLoader.nameInput").show();
else
$(".paymentInputLoader").show();
$.ajax({
type: "GET",
url: urlPreFix + config.url.customerInfoFormSsn + ssn,
cache: false,
dataType: "json",
timeout: config.constant.webServiceTimeOut,
contentType: "application/json; charset=utf-8",
success: function (custInfo) {
if (custInfo.length > 0) {
$("#notValidSsn").hide();
ProcessPaymentCustInfo(custInfo, type);
}
else if (custInfo.name == null) {
$(".paymentInputLoader").hide();
$("#payerSsn").addClass("error");
$("#notValidSsn").fadeIn();
}
else {
$("#notValidSsn").hide();
ProcessPaymentCustInfo(custInfo, type);
}
},
error: function (xhr, ajaxOptions, thrownError) {
$(".paymentInputLoader").hide();
$("#" + type + "Name").prop("disabled", "");
$("#" + type + "Name").focus();
}
});
}

calling a jquery function from a button which inside the function itself

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>');

broken javascript - formatting tools wont fix it. causes previous block of code to break

In as much as I would like someone to say "change this line of code to read....", I really would like to know the solution to the problem of Firefox not reporting broken code. This code block is broken and it causes a previous block of code to break. It's somewhere in the notdupe.live.click function. I can comment out the entire function and the rest of the code works. I've tried commenting out pieces but can't isolate the problem.
<script type="text/javascript">
var SaveDupeGroup = 0;
var DupeCount = 0;
var ReInitAnswer = '';
var RemoveAnswer = '';
$(document).ready(function () {
$('.StartOver').live('click', function () {
ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit(); //return true;
} else {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error
alert(errorThrown);
},
success: function (response1, textStatus, jqXHR)(
if ($(e.target).is(":checked")) {
$firstTD = $(this).parent().siblings().first();
SaveDupeGroup = $firstTD.text();
$.ajax({
type: 'GET',
url: 'cfc/basic.cfc?method=CheckDupeGroup&returnformat=json',
dataType: 'json',
data: 'DupeGroupNumber=' + $firstTD.text(),
error: function (xhr, textStatus, errorThrown) {
// show error
alert(errorThrown);
},
success: function (response, textStatus, jqXHR) {
DupeCount = response.DATA[0];
alert('Dupe Group-' + SaveDupeGroup + ' count=' + response.DATA[0]);
if (DupeCount) {
alert('huh?');
} else {
RemoveAnswer = confirm('All of the names in this group have been checked.\nDo you want to remove them from the lists?');
if (RemoveAnswer) {
alert('continued');
} else {
alert('canceled');
return false;
}
}
}
});
})
});
});
});
</script>
Line 26, you have function()( should be function(){ and because of that you're probably going to have to investigate your closing }'s
have you tried checking the code with jshint or jslint?
You have a SyntaxError.
This...
success: function (response1, textStatus, jqXHR)(
should be this...
success: function (response1, textStatus, jqXHR) {
also the colosing ) should be }.
Not sure why Firefox (Firebug?) doesn't report it.

Categories