how to execute a specific code after a ajax - javascript

I have a function in which uses ajax which populate a select element of options from my database, here is the code of the function.
function Filtering_GetRole(roleElement) {
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Filtering_GetRole",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var roletooldetails = response.d;
var appendItem = "";
$(roleElement).empty();
$.each(roletooldetails, function (index, Filtering_GetRoleInfo) {
var activeappend = "";
var id = Filtering_GetRoleInfo.id;
var role = Filtering_GetRoleInfo.Role;
activeappend = "<option value=" + id + ">" + role + "</option>";
appendItem += activeappend;
});
$(roleElement).prepend('<option disabled="disabled" selected="selected" value="">Select Tool</option>')
$(roleElement).append(appendItem);
},
error: function (XMLHttpRequest) {
console.log(XMLHttpRequest);
alert("error in Filtering_GetTool");
}
});
}
which I call like this
var slcRole = $(this).closest(".td-span-buttons").closest(".tr-span-buttons").find(".slc-role"); var holdRoleId = slcRole.val();
Filtering_GetRole(slcRole);
slcRole.val(holdRoleId);
but the problem is since I use ajax the code slcRole.val(holdRoleId); will execute first resulting to the value not selected on the option element. How can I do that when the ajax code finished this code will execute. Sorry for the bad english

The another way to make sure your ajax request has been processed is to use jQuery.when(), but the best way is to put slcRole.val(holdRoleId) into success callback.

Just put slcRole.val(holdRoleId); into success.
Else, js will execute without waiting ajax done.

I think you need to execute this after success or error so instead putting in any callback or after your Filtering_GetRole put it in the complete callback of ajax have a look here. It will execute code within complete block when ajax is complete. Hope this will help.

You can use complete function. complete executes only after the "success" of ajax. Following code will be helpful to you.
success: function (response) {
// Your code
},
complete: function (response) {
slcRole.val(holdRoleId);
},
error: function (XMLHttpRequest) {
// Your code
}

Related

Javascript loop with ajax call

I've been struggling all afternoon to understand how to make this work, hopefully someone can help. I have a simple requirement to run through a list of checked check boxes, retrieve some data from the server, fill an element with the data expand it. So far I have the following code;
function opentickedrows() {
$('input[type=checkbox]').each(function () {
if (this.checked) {
tid = $(this).attr('name').replace("t_", "");
$.ajax({
url: '/transfer_list_details_pull.php?id=' + tid,
type: 'GET',
success: function (data) {
$('#r' + tid).html(data);
$("#r" + tid).show();
$("#box" + tid).addClass("row-details-open");
}
});
}
});
}
The problem that I am having is that the ajax calls all seem to happen so fast that 'tid' isn't being updated in the ajax call. From what I have read I believe I need to wrap this up into a couple of functions with a callback but I just can not get my head around how. I'd be really grateful if someone can set me on the right path.
Ajax calls are asynchronous, so when the success callback is invoked, tid has the value of the last item of the $('input[type=checkbox]').
You could use a closure:
function opentickedrows() {
$('input[type=checkbox]').each(function () {
if (this.checked) {
tid = $(this).attr('name').replace("t_", "");
(function(tid) {
$.ajax({
url: '/transfer_list_details_pull.php?id=' + tid,
type: 'GET',
success: function (data) {
$('#r' + tid).html(data);
$("#r" + tid).show();
$("#box" + tid).addClass("row-details-open");
}
});
})(tid)
}
});
}

DOM timing or wrong code?

I've got two multi select list boxes, the first one allows someone to select a team.
The second one shows the members related to the team. When the first list box (the team) is selected I make an ajax call to fill the members of that team. I'm also using the chosen library. This is all working fine however, I needed a way to remove the x from the listbox selected value so that users don't think they can remove a member from the team.
$("#MainContent_lbMembers_chosen a").removeClass("search-choice-close");
The above code works when I throw that in a console window, but if I have it in my if condition it doesnt seem to work:
$("#MainContent_lbTeams").on('change', function() {
//was a value selected?
var latest_value = $("option:selected:last", this).val();
var latest_text = $("option:selected:last", this).text();
if ($("#MainContent_lbTeams :selected").length > 0) {
$("#dTeamNotice").show();
$("#MainContent_lblTeamMembers").text("Members of '" + latest_text + "':");
PopulateMembers(latest_value);
$("#MainContent_lbMembers_chosen a").removeClass("search-choice-close");
$("#trMembers").fadeIn();
} else {
//hide it...
$("#dTeamNotice").css("display", "none");
$("#trMembers").hide();
}
});
Basically the change event grabs the most recently selected text and value. If the length of what is selected > 0 I load the members of my team with PopulateMembers:
function PopulateMembers(buCompanyTeamID) {
$('#<%=lbMembers.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
$("#<%=lbMembers.ClientID %>").trigger("chosen:updated");
$.ajax({
type: "POST",
url: "/Code/WebServices/Utilities.asmx/GetTeamMembers",
data: '{buCompanyTeamID: ' + buCompanyTeamID + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnMembersPopulated,
failure: function (response) {
alert(response.d);
}
});
}
function OnMembersPopulated(response) {
PopulateControl(response.d, $("#<%=lbMembers.ClientID %>"), true);
}
function PopulateControl(list, control, selected) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0"></option>');
$.each(list, function () {
if(selected)
control.append($("<option selected></option>").val(this['Value']).html(this['Text']));
else
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
control.empty().append('<option selected="selected" value="0"><option>');
}
control.trigger("chosen:updated");
}
But I cannot understand why in a console window I can do this:
$("#MainContent_lbMembers_chosen a").removeClass("search-choice-close");
And it removes the x from the chosen selected value so that a user cannot remove an item, but within the if condition this doesnt have any effect.
I even tried disabling like so:
$("#MainContent_lbMembers").attr('disabled', true).trigger("chosen:updated");
This only works in a console as well, is it some timing issue or something else?
PopulateMembers() contains an asynchronous Ajax call. So, if you are expecting:
PopulateMembers(latest_value);
$("#MainContent_lbMembers_chosen a").removeClass("search-choice-close");
to operate on the results of the ajax call in PopulateMembers(), then you do indeed have a timing problem. The Ajax call will complete some time in the future, long after PopulateMembers() has finished and long after you've executed the .removeClass() statement.
To operate on the results of PopulateMembers(), you have to either put your code in the success handler of that ajax call or restructure your code so that PopulateMembers() will call a callback when it's done and you can do the .removeClass() in that callback.
I would suggest using promises like this:
// return the ajax promise from PopulateMembers
function PopulateMembers(buCompanyTeamID) {
$('#<%=lbMembers.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
$("#<%=lbMembers.ClientID %>").trigger("chosen:updated");
return $.ajax({
type: "POST",
url: "/Code/WebServices/Utilities.asmx/GetTeamMembers",
data: '{buCompanyTeamID: ' + buCompanyTeamID + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).then(onMembersPopulated, function (response) {
alert(response.d);
});
}
$("#MainContent_lbTeams").on('change', function() {
//was a value selected?
var latest_value = $("option:selected:last", this).val();
var latest_text = $("option:selected:last", this).text();
if ($("#MainContent_lbTeams :selected").length > 0) {
$("#dTeamNotice").show();
$("#MainContent_lblTeamMembers").text("Members of '" + latest_text + "':");
// act only when the returned promise is resolved
PopulateMembers(latest_value).then(function() {
$("#MainContent_lbMembers_chosen a").removeClass("search-choice-close");
$("#trMembers").fadeIn();
});
} else {
//hide it...
$("#dTeamNotice").css("display", "none");
$("#trMembers").hide();
}
});

Calling a function from if block in success

Hello fellow programmers. I am newbie to jquery ajax.
How do i call function checkreturn() from if block or is it possible to access msg outside the success if yes then please let me know how. I need it because only if condition proves true i have to enable the subsequent textbox. Here is my code.Thanks in advance for your time and reply.Rajesh.
<script type="text/javascript" >
function checkreturn() {
document.getElementById("txtAns").removeAtrribute("disabled");
}
function cQtn(e){
var uname= $("#<%=Username.ClientID%>").val();
var sq=$("#<%=SecQuest.ClientID%>");
var sqtn = $("#<%=SecQuest.ClientID%> option:selected").text();
var sans=$("#txtAns");
var msgbox = $("#Dstatus");
$.ajax({
type: "POST",
url: "forgotpassword.aspx/CheckValidSQtn",
data: "{'uname':'"+uname+"','args':'"+sqtn+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
sq.removeClass("notavailablecss");
sq.addClass("availablecss");
msgbox.html('<img src="proj_mages/a.png"> <font color="Green"> Valid </font>');
//how do i call from here??
}
else {
sq.removeClass("availablecss");
sq.addClass("notavailablecss");
msgbox.html(msg.d);
}
}
});
}
</script>
You have a typo in your checkreturn function. You want to use removeAttribute, instead of removeAtrribute (double t,not double r).
Also, you can use jQuery functions:
function checkreturn(){
$('#txtAns').prop('disabled',false);
}
, instead of native DOM functions (document.getElementById, setAttribute):
not sure what why the normal way is not working but you could try forcing what the browser is supposed to do,
function checkreturn(){
document.getElementById("txtAns").removeAtrribute("disabled");
}
Becomes
window.checkreturn = function(){
document.getElementById("txtAns").removeAtrribute("disabled");
}
Then try calling via window.checkreturn(); or checkreturn(); you can also so try this the other way arround so you can leave your function and try calling window.checkreturn();
If none of these are working it would say your function is not entering the window(Global) scope for your page use Firebug or Inspector and try to all checkreturn(); see what exception you get back,
if you get a not found your not showing us some thing in your code maybe a closure or some thing
I'll look into it further but try setting async for the ajax call to false:
function checkreturn() {
document.getElementById("txtAns").removeAtrribute("disabled");
}
function cQtn(e) {
var uname= $("#<%=Username.ClientID%>").val(),
sq=$("#<%=SecQuest.ClientID%>"),
sqtn = $("#<%=SecQuest.ClientID%> option:selected").text(),
sans=$("#txtAns"),
msgbox = $("#Dstatus");
$.ajax( {
async: false,
type: "POST",
url: "forgotpassword.aspx/CheckValidSQtn",
data: "{'uname':'"+uname+"','args':'"+sqtn+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
sq.removeClass("notavailablecss");
sq.addClass("availablecss");
msgbox.html('<img src="proj_mages/a.png"> <font color="Green"> Valid </font>');
//how do i call from here??
} else {
sq.removeClass("availablecss");
sq.addClass("notavailablecss");
msgbox.html(msg.d);
}
}
} );
}
Now, when the ajax call is made, the rest of the script will wait til it completes instead of how everything continues when async is true.

How to bring ajax search onkeyup with jquery

My Script to call ajax
<script language="javascript">
function search_func(value)
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
</script>
HTML
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.
For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.
When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.
Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.
I believe I had explained up to reader knowledge.
You should check if the value has changed over time:
var searchRequest = null;
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "sample.php",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
EDIT:
The searchRequest variable was added to prevent multiple unnecessary requests to the server.
Keep hold of the XMLHttpRequest object that $.ajax() returns and then on the next keyup, call .abort(). That should kill the previous ajax request and let you do the new one.
var req = null;
function search_func(value)
{
if (req != null) req.abort();
req = $.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
Try using the jQuery UI autocomplete. Saves you from many low-level coding.
First i will suggest that making a ajax call on every keyup is not good (and this why u run in this problem) .
Second if you want to use keyup then show a loading image after input box to show user its still loading (use loading image like you get on adding comment)
Couple of pointers. Firstly, language is a deprecated attribute of javascript. In HTML(5) you can leave the attribute off, or use type="text/javascript". Secondly, you are using jQuery so why do you have an inline function call when you can do that with jQuery too?
$(function(){
// Document is ready
$("#sample_search").keyup(function()
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg)
{
//Receiving the result of search here
}
});
});
});
I would suggest leaving a little delay between the keyup event and calling an ajax function. What you could do is use setTimeout to check that the user has finished typing before then calling your ajax function.

jQuery script supposed to run async but works only sync? why?

I have this small jquery script that does not work if I remove the 'async:false' part... And I don't understand why (the alert() part is there just to check if it works or not). My guess was it would work asynchronously but it just doesn't. Can somebody explain to me why? And what should I change to make it async?
$(document).ready(function(){
var artistName = new Array();
var artistPlaycount = new Array();
$('#inputForm').submit(function(){
var userName = $('#username').attr('value');
var amount = $('#amount').attr('value');
userName = "someUsername";
$.ajax({
type: "POST",
url: "prepXML.php",
data: "method=getartists&user="+userName+"&amount="+amount,
dataType: "xml",
async:false,
success: function(xml){
var i = 0;
$("artist",xml).each(function(){
artistName[i] = $(this).find("name").text();
artistPlaycount[i] = $(this).find("playcount").text();
i++;
});
}
});
});
alert(artistName[2]); //or any other iteration number
});
thank you
To do this asynchronously you need to move the alert into the callback and remove the async option, like this:
$.ajax({
type: "POST",
url: "prepXML.php",
data: "method=getartists&user="+userName+"&amount="+amount,
dataType: "xml",
success: function(xml){
$("artist",xml).each(function(i){
artistName[i] = $(this).find("name").text();
artistPlaycount[i] = $(this).find("playcount").text();
});
alert(artistName[2]);
}
});
Otherwise that success function populating the array happens after the alert does...so what you want isn't quite there yet. Not until the request comes back from the server does the success handler execute.
Also, the first parameter to the .each() callback is the index, you can use it, no need to keep your own incrementing variable :)
It doesn't work because the callback is fired after the alert. Put the alert in the callback.
you need to move the alert into your success handler.
alert(artistName[2]); //or any other iteration number
should go right after you loop through the xml.
so you should have:
success: function(xml){
var i = 0;
$("artist",xml).each(function(){
artistName[i] = $(this).find("name").text();
artistPlaycount[i] = $(this).find("playcount").text();
i++;
});
alert(artistName[2]); //or any other iteration number
}

Categories