Check for ajax call completion - javascript

I'm having a problem filling and accessing a global variable with ajax. I have the following code (stripped down a bit):
var answers;
$(document).ready(function() {
showResults();
console.log(answers);
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
return answers;
});
}
My question is the following: When I log answers in the done function it gives me a nice array. That would mean the array variable is filled. But when I log it from $(document).ready, It returns an empty variable. This is probably because the AJAX call is asynchronous, and the log gets executed before the variable is filled.
However, I need to use that variable on another page, so I need to access it from the $(document).ready ... Any idea about how to check if the variable is filled? Or when the showResults() is completed? Thanks in advance for your help!
Edit -
Thanks for your replies! But I'm still struggling with the following: As I understand, I can call another function from the ajax callback, and pass it the data. The thing is, I have to do a lot of different stuff with it after the call, and the only way I can get it to work now is by calling a function in the ajax callback, then calling another one from that one, etc...
So I end up wit showResults(); in the doc.ready, which then executes a lot of functions that are all "linked" together. Is there anyway I can return the data to the variable, for use in other places? I hope I have made this clear, English is not my native language, sorry.

Execute the functionality that is dependent on the answers array after the AJAX call. Call your function from within done(..)
A very rough idea:
var answers;
function functionalityDependentOnAnswers() {
//the code dependent on answers array.
}
$(document).ready(function() {
showResults();
//Move code here to functionalityDependentOnAnswers()
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
functionalityDependentOnAnswer();
});
}

You can use the when method provided by jQuery (look at this SO link).
Or look at this SO link where a similar situation is explained.

Check the documentation for success: this will only be executed when successful callback is done.
var answers;
$(document).ready(function() {
showResults();
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).when(function (data) {
console.log(answers);
answers = data.questionary;
return answers;
});
}

Idea: Have a hidden input field and add change listener to it.
<input type="hidden" id="answers_input" />
Now have a listener to this.
var answers;
$(document).ready(function() {
$('#answers_input').on('change', function() {
// trigger your custom code
console.log(answers);
})
showResults();
console.log(answers);
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
$('#answers_input').val(answers);
});
}
Solution is kinda like a hack, let me know if this works for you

You're in the right way.
Do stuff with answers inside the DOM callback.
var answers;
$(document).ready(function() {
showResults();
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
console.log(answers);
// Manage answers here
});
}

Related

How to put ajax request inside function and call it when necessary?

I have an ajax request:
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
I want to be able to put this inside a function that waits for me to trigger it with a return call. I am not exactly sure how to word it, I am new to javascript and jquery. But basically, I want to trigger this ajax call with various different button clicks and instead of having to put the ajax call inside every button click event, I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
Heres an example of a click event Id like to call the ajax request function with. Thanks!
$(function() {
$(".task-listing").click(function() {
//Call Ajax function here.
});
});
Callbacks are well-suited for this scenario. You can encapsulate your ajax call in a callback function.
function apiCall() {
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
}
You can now hook apiCall()method as a callback to button click.
$(function() {
$(".task-listing").click(apiCall);
});
By doing this you will able to achieve this.
I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
EDIT:
Note:
This is lead to start, you can alter this according to your requirement.
Is this not working for you? ↓↓
$(function() {
$(".task-listing").click(function() {
let pid = $(this).attr("id"); //get any other value which you want to pass in function, say url
someFunction(pid); // pass any other parameters, eg- someFunction(pid, url)
});
});
function someFunction(pid){ // someFunction(pid, url)
$.ajax({
type: 'POST',
url: '/get-result.php', // url: url
dataType: 'json',
data: 'pid=' + pid,
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
}
});
}

How do I pass value from a javascript function to C# Code behind?

I have a dynamic button which have unique id's, I'm getting the id of the clicked button like so:
$("button").click(function() {
//I want to pass this.id to my btnDetails_Click event in C# or to a variable Property(for efficiency)
});
How do I do this? Sorry noob in javascript.
I won't code precisely for you, but maybe what I will include could help and point you to right direction in your own conclusion.
Okay, let us say that the page you are using is called Page.aspx, and the method is called Done
var values = {"0,","1","2"};
var theids = JSON.stringify(values);
// Make an ajax call
$.ajax({
type: "POST",
url: "Page.aspx/Done",
contentType: "application/json; charset=utf-8",
data: {ids: theids },
dataType: "json",
success: function (result) {
alert('Alright, man!');
},
error: function (result) {
alert('Whoops :(');
}
});

Trying to use a callback with .ajax call to assign value to a variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm trying to use a .ajax call, to assign the value from an xml document, to a variable in javascript. I can't quite figure out how to use a callback, I know this topic is well discussed on forums, but I haven't been able to find an example out there that does what I am trying to do. The example below makes a call to Google Maps, and gets a string "Central Standard Time" back. I can use .ajax calls to move the text to a div. But I can't figure out how to assign this to a variable, my_zone, and move that value to a div.
Anyone able to help me out? Please? If someone can do a rewrite of the code here, thanks....
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='//code.jquery.com/jquery-2.0.2.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
//this works great, we get the value and it goes to the 'zzz' div, asynchronously
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/timezone/xml",
data: {
location: '35.129186,-89.970787',
timestamp: '1389006000',
sensor: 'false'
},
dataType: "xml",
success: function(xml) {
var val = $(xml).find('time_zone_name').text();
$( "#zzz" ).empty().append( val ); //want to return val
}
});
//this is what I am trying to do, get the return'd value, and put it into a variable
var my_zone = getZone(); //just want to get the value into a variable
$("#xxx").empty().append(my_zone); //do something with it, maybe display it
function getZone() {
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/timezone/xml",
data: {
location: '35.129186,-89.970787',
timestamp: '1389006000',
sensor: 'false'
},
dataType: "xml",
success: function(xml) {
var val = $(xml).find('time_zone_name').text();
console.log(val);
return val; //needs to be part of a Callback
}
});
}
///////////
});
</script>
</head>
<body>
<div id="xxx">some output here....</div>
<div id="zzz">some output here....</div>
</body>
</html>
You can't do that, instead you can pass a callback function to getZone() which will get called once the request is completed with the desired parameter
//pass a callback function which will get called when the ajax request is completed
getZone(function (my_zone) {
$("#xxx").empty().append(my_zone); //do something with it, maybe display it
});
function getZone(callback) {
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/timezone/xml",
data: {
location: '35.129186,-89.970787',
timestamp: '1389006000',
sensor: 'false'
},
dataType: "xml",
success: function (xml) {
var val = $(xml).find('time_zone_name').text();
console.log(val);
callback(val); //call the callback with the value
}
});
}

Not to remove object without confirmation

I try to remove elements from my table in my django project, but I would like to have such a removal to be confirmed. Using this article
http://www.developmentwall.com/delete-row-from-html-table-jquery/
I wrote such function:
<script>
function deleteAjax(row_id){
$.ajax({
url: "delete_item/"+ row_id +"/",
type: "POST",
data: {'id':row_id},
success: function (){
if(!confirm('Are you sure you want to delete?')){
ev.preventDefault();
return false;
}else{
$('#my_row_'+row_id).remove();
}
}
});
}
</script>
Unfortunately, despite of the fact that I click that I won't to delete object, the object is removed.
Have you any hints? I suppose that it can be something wrong with ev, but I am fairly new to javascript and ajax and I do not know how to cope with this.
try this:
<script>
function deleteAjax(row_id){
if (!confirm('Are you sure you want to delete?')) { return; }
$.ajax({
url: "delete_item/"+ row_id +"/",
type: "POST",
data: {'id':row_id},
success: function (){
$('#my_row_'+row_id).remove();
}
});
}
</script>

Setting data-content and displaying popover

I'm trying to get data from a resource with jquery's ajax and then I try to use this data to populate a bootstrap popover, like this:
$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);
and the function for retrieving data is:
get_data_for_popover_and_display = function() {
var _data = $(this).attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}
What is happening is that the popover is NOT showing when I click, but if I hover the element later it will display the popover, but without the content (the data-content attribute). If I put an alert() inside the success callback it will display returned data.
Any idea why is happening this? Thanks!
In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display().
Don't worry! The this keyword is hairy; misinterpreting its value is a common mistake in JavaScript.
You can solve this by keeping a reference to this by assigning it to a variable:
get_data_for_popover_and_display = function() {
var el = $(this);
var _data = el.attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
el.attr('data-content', data);
el.popover('show');
}
});
}
Alternatively you could write var that = this; and use $(that) everywhere. More solutions and background here.
In addition to the answer above, don't forget that according to $.ajax() documentation you can use the context parameter to achieve the same result without the extra variable declaration as such:
get_data_for_popover_and_display = function() {
$.ajax({
type: 'GET',
url: '/myresource',
data: $(this).attr('alt'),
dataType: 'html',
context: this,
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}

Categories

Resources