This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have the following code:
var text = "";
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: DataReview.BASE + "/Encryption/FetchLatestEditBy",
data: JSON.stringify({
"ExtendedReport_id": dataRow["ExtendedReport_id"],
"Report_id": dataRow["Report_id"]
}),
success: function (data) {
text = data.ResultData;
},
error: function (data) {
console.log(data);
}
});
setTimeout(function () {
console.log(text); //This displays the value
$(this).attr('data-toggle', 'tooltip');
$(this).attr('title', text);
}, 1000);
As you can see, I'm trying to set the tooltip-text in the setTimeout-function. But It will not show up. When I replace text-variable with some dummy-text, it works. But the variable value does not work.
When you use timeout, the this will be in window scope and not with the element. So you are actually adding attributes to the window.
Secondly there is no guarantee that ajax call will be done or you might be waiting too long after the Ajax call by using a timeout. You should be setting the attributes in the success callback of the Ajax call.
Thirdly you probably need to get trigger the tooltip manually so it gets the updated data.
var elem = $(this);
$.ajax({
/* your code here, removed to simplify answer*/
success: function (data) {
elem.attr('data-toggle', 'tooltip');
elem.attr('title', text);
elem.tooltip().tooltip("show"); // might need to change this line based on actual library
}
});
I am assuming your ajax success is taking more time and thus the setTimeout function is called first before the "text" variable value is set in the success function. Try calling a function in onsuccess ajax function.
var text = "";
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: DataReview.BASE + "/Encryption/FetchLatestEditBy",
data: JSON.stringify({
"ExtendedReport_id": dataRow["ExtendedReport_id"],
"Report_id": dataRow["Report_id"]
}),
success: function (data) {
text = data.ResultData;
settooltiptext();
},
error: function (data) {
console.log(data);
}
});
function settooltiptext()
{
console.log(text); //This displays the value
$(this).attr('data-toggle', 'tooltip');
$(this).attr('title', text);
}
Related
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']);
}
});
}
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 :(');
}
});
I'm not good at JQuery at all, in fact this is my first encounter due to Shopify. In other words I'm completely lost.
This is what I was able to do so far.
function FindPlayer()
{
var playerid = $('input[id=playerId]').val();
var clubname = $('input[id=teamname]').val();
$("#searchBar").attr('data-user-input', value);
$.ajax({
url: "http://website.com/index.php?player=" + playerid + "&club=" + clubname,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response(data);
}
});
}
The json response is going to look like this:
[{"playerFound":"true","tradeid":"123456"}]
I want to then check if playerFound is true or false before setting this element:
<input id="tradeId" type="hidden" name="attributes[tradeid]" />
This is probably pretty basic for JQuery users but not for me any help would be appericiated.
Try This:-
$.ajax({
url: "http://website.com/index.php?player=" + playerid + "&club=" + clubname,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if(data[0].playerFound == "true")
{
$('#tradeId').val(data[0].tradeid);
}
}
});
Since content type is JSON you can simply use like this
success: function (data) {
if(data.playerFound == "true"){
$('#tradeId').attr('name',data.tradeid) // if you want to change name
$('#tradeId').val(data.tradeid)// if you want to change value
}
}
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
});
}
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');
}
});
}