I'm making some functions after opening the modal. RefreshBirths() function needs motherId and fatherId which are from getDictionaryMother() and getDictionaryFather() functions (these render my mothers and father on page then I can get values in refreshBirths() function).
I checked that refreshBirths() takes my ids too early so a have undefined ids in the end.
I checked calling my refreshBirths() function in .done part in mother/father methods and it fixes my problem but I prefer do it explicitly in the indicated part of the code.
This doesn't fix but I want to make this there:
$('#create-modal').on('shown.bs.modal', function() {
refreshBreeds();
getDictionaryMother();
getDictionaryFather();
$.when(getDictionaryFather()).done(function() {
refreshBirths();
});
});
Here it fixes but I prefer have that method called in another place
function getDictionaryMother() {
$.ajax({
url: "/admin/api/dictionary/" + "ANIMAL_MOTHER",
type: "GET",
dataType: "json"
})
.done(function(response) {
$('#mother-create').empty();
$('#mother').empty();
response.forEach(function(mother){
$('#mother-create').append('<option value='+ mother.id +'> '+ mother.value +' </option>');
$('#mother').append('<option value='+ mother.id +'> '+ mother.value +' </option>');
});
refreshBirths();
})
.fail(function(jqxhr, textStatus, errorThrown) {
displayErrorInformation("Cannot get dict: " + name + " due to: " + jqxhr.responseText);
});
}
You can use .then() method on the Ajax request or .when().
Related
I am attempting use a variable that I create through data being sent from php in one ajax function in a another ajax function. I'm not sure what I am doing wrong. I tried creating making this a global variable by doing var nameOutput and also tried var nameOutput = 0. You will see alert code in the second ajax function. This is outputting nothing. If I remove the .val(), I receive object Object.
The code in question is in the second Ajax function: data: {
'nameOutput': nameOutput.val()
}
Does anyone have any idea what I have to do?
var nameOutput;
$('#shuffle').on('click', function() {
$.ajax({
url: 'php/name-selection.php',
type: 'POST',
success: function(data) {
nameOutput = $('#name-output').html(data);
$(nameOutput).html();
},
complete:function(){
$('#send-info').slideDown(1500);
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
});
//var datastring1 = $('#name-output').serialize();
$('.check').click(function() {
alert(nameOutput.val());
$.ajax({
url: 'php/name-selection-send.php',
type: 'POST',
data: {
'nameOutput': nameOutput.val()
}
,
success: function(data) {
if (data == 'Error!') {
alert('Unable to submit inquiry!');
alert(data);
} else {
$('#success-sent').html(data);
}
},
complete:function(){
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
if you can set inner html of nameOutput using .html('blah') , so you can extract the html again using nameOutput.html() not nameOutput.val();
however I think you have to define the element like this to be a HTML element:
var nameOutput=$('<div></div>');
also in first ajax function,set the html using this:
nameOutput.html(data);
and if there is a real element with ID name-output , and you want the result to be visible, do both of these:
nameOutput.html(data);
$('#name-output').html(data);
Not sure how to even ask the question, if any suggestions for the title please let me know...
I have the following function that retrieves via AJAX information of a JSON file. This function as you can see below:
setOptionsSettings("[data-machine-brand-options]", apiUrlMachineBrands, 'name');
function setOptionsSettings(htmlElement, url, apiParameter) {
$.ajax({
dataType: "json",
url: url,
// CREATE GENERIC SOLUTION for the spinner
beforeSend: function(xhr) {
$('main').html('<div class="spinner"><div class="hori-verti-centering"><div class="bounce bounce1"></div><div class="bounce bounce2"></div><div class="bounce bounce3"></div></div></div>');
setHeader(xhr);
},
success: function (data) {
$.each(data, function(i) {
$(htmlElement).append("<option id=" + data[i].id + " value=" + data[i].apiParameter + ">" + data[i].apiParameter + "</option>");
});
}
});
return {};
}
I'm trying to set apiParamter so when you call the function setOptionSettings you can place the name of the parameter you need to call. So in this case the parameter is name. How can I insert this into the function so it works?
I tried the following and other solutions but nothing would work, any suggestions?
$(htmlElement).append("<option id=" + data[i].id + " value=" + data[i]. + apiParameter + ">" + data[i]. + apiParameter + "</option>");
To access object property using string key use Bracket notation i.e data[i][apiParameter]
As you are using jQuery create element using it.
$(htmlElement).append($('<option></option>', {
"id": data[i].id,
"value": data[i][apiParameter]
}));
I'm having problems with the return value of a jQuery ajax call. I can debug the whole thing server side and I know everything is working correctly and the return value is properly being calculated. I can look under the NET tab in FireBug and see that the response is:
{"d":false}
But when I test the value in the Success function of the ajax call, msg is NULL. Why?
Here's the ajax call:
function GetStateCertifiable(areaID) {
$.ajax({
url: "../WebServices/AoP.asmx/GetStateCertifiable",
data: '{"AreaID":"' + areaID + '"}',
dataType: 'json',
success: function (msg) {
alert(msg); // for debugging
if (msg)
$("#isCertified").slideDown("fast");
else
$("#isCertified").slideUp("fast");
},
error: function (msg) {
alert("An error occured. \nStatus: " + result.status
+ "\nStatus Text: " + result.statusText
+ "\nError Result: " + result);
},
complete: function () {
}
});
};
Other, similarly structured client-side calls work fine. This is a same-domain request.
try changing the name of the variable to something other than msg. I think that might be a message box or something similar. Try
function GetStateCertifiable(areaID) {
$.ajax({
url: "../WebServices/AoP.asmx/GetStateCertifiable",
data: '{"AreaID":"' + areaID + '"}',
dataType: 'json',
success: function (result) {
alert(result); // for debugging
if (result)
$("#isCertified").slideDown("fast");
else
$("#isCertified").slideUp("fast");
},
error: function (result) {
alert("An error occured. \nStatus: " + result.status
+ "\nStatus Text: " + result.statusText
+ "\nError Result: " + result);
},
complete: function () {
}
});
};
It turns out the problem was that my web service (../WebServices/AoP.asmx/GetStateCertifiable) returned a bool and from the post response, I know that was properly sent back to the client. Ajax, however, didn't like that. Once I changed the web service to return the strings "true" or "false", everything worked.
Does jQuery ajax only work for strings or is there something I should have done to prepare the msg object to receive a bool?
I'm trying to create an if/else statement within my jQuery code that changes the ajax URL and success function that gets fired off:
if($($this.context).find('img').hasClass('scheduler-img')) {
url = window.location.origin + "/recipes/" + planned_recipe_id +'/update_recipe'
} else {
url = window.location.origin + "/recipes/" + recipe_id +'/make_recipe'
success = successfulRecipeAdd(closest_date, image_url, recipe_id);
}
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
data: {
planned_for: planned_for,
meal_type: meal_type
},
success: (function() {
success
}),
error: (function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
})
});
I'm using this for a jQuery draggable and sortable table, so when I'm dragging and dropping the first item, it doesn't work because it tries creating the 'success' variable with an empty dataset. However, it does work for every subsequent drag/drop after.
function successfulRecipeAdd(closest_date, image_url, recipe_id) {
$.get( window.location.origin + "/recipes/get_recipes", function(data) {
console.log(data);
var planned_recipe_id = $(data).last()[0][0].id;
$(closest_date).append("<img src='"+image_url+"'class='scheduler-img col-md-12' id='"+ recipe_id +"' data-planned-id='"+planned_recipe_id+"'>");
});
}
I'm having a lot of trouble figuring out a way to write this that would allow me to create variables within the if/else statement, then fire off the ajax call using variables, rather than having two ajax calls within the if/else statement.
I have an AJAX request that utilizes beforeSend, success, and failure, yet when the beforeSend gets hit it treats it as an object instead of a method call.
Here's the AJAX:
$.ajax({
url: "#Url.Action("DeleteUser", "DataFeeds")/" + id,
method: 'post',
beforeSend: "deleting('" + id + "')",
success: "deleted('" + full + "','" + id + "')",
failure: "failed('" + id + "')"
});
Just for kicks, here's the deleting() method:
function deleting(id) {
$('#btnDelete-' + id + ' span').html('Deleting...');
$('#btnDelete-' + id + ' span').prop('disabled', 'disabled');
}
It's pretty simple stuff, but I can't figure out why it's treating my function as an object.
Halp!
You need to pass an extra anonymous function there, otherwise you're just assigning a string:
beforeSend: function(){ deleting(id) },
// same with the other methods...
I could be mistaken, but I don't think you're allowed to give JQuery a string there. You can give it a function instead by currying deleting:
function deleting(id) {
return function() {
$('#btnDelete-' + id + ' span').html('Deleting...');
$('#btnDelete-' + id + ' span').prop('disabled', 'disabled');
}
}
And:
beforeSend: deleting(id),