Javascript retrieving username from db [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm trying to write a JavaScript function that retrieves surname that corresponds to a supplied email address with no success so far. Here's my code:
function getUsername(){
var username;
$(function(){
var dataString = 'email=' + EMAIL_ADDRESS;
$.ajax({
url: 'user_crud_operations.php',
data: dataString,
dataType: 'json',
success: function(data){
U = data[1];
username = data;
}
});
});
return username;
}
I need to use the retrieved username in another function elsewhere. Where am I going wrong?

Asynchronous functions (as used in AJAX) usually do not return values but instead trigger callback functions.
You must restructure your design so that "getUserName()" passes to a callback instead of returning a value. For example:
function getUsername(handler) {
// ...
$.ajax({
// ...
}).done(function(username) {
if (handler && (typeof(handler)==='function')) {
handler(username);
}
});
}
// Sample usage...
getUsername(function(username) {
alert("OK: username=" + username);
});

Related

Capture POST request to local variable in script [duplicate]

This question already has answers here:
AJAX not updating variable
(5 answers)
Closed 5 years ago.
I have the javascript code below that POSTs a request, I then want to save the response to a local variable named sku, but it is not binding.
the variable sku remains an empty string.
var sku = ""; //to be passed to server when filled
var cookie_info = {
number_nights: number_nights_cookie,
number_travelers: number_travelers_cookie,
type_traveler: type_traveler_cookie,
departure_date: departure_date_cookie,
country: country_cookie
};
$.ajax({
type: 'POST',
url: 'https://azooree.com/wp-admin/php/sku-calculation.php',
data: cookie_info,
success: function(response) {
console.log('success', response);
sku = response;
},
error: function() {
console.log('error!');
alert("[ERROR] Information lost, please try again. Thank you!");
}
});
var basic = {
info: sku + "LP"
};
The value of variable sku is being returned from your POST request which is asynchronous. That's why at the time of assigning the value of sku to basic - it will be empty.
You can easily update the value of basic either by using a callback function like below-
$.ajax({
type: 'POST',
url: 'https://azooree.com/wp-admin/php/sku-calculation.php',
data: cookie_info,
success: function(response) {
console.log('success', response);
sku = response;
updateBasicValue(sku);
},
error: function() {
console.log('error!');
alert("[ERROR] Information lost, please try again. Thank you!");
}
});
function updateBasicValue(sku) {
basic = {
info: sku+"LP"
};
}
Or else, you can do whatever you need to do with the sku variable inside the success function of your AJAX request.
UPDATE
You also need to check for CORS issues if your request is being sent from any other domain or subdomain different than the one causing it. - (Thanks LordNeo)

How do I get value from Ajax function for jquery onclick function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a button that when I click on it , it will get data from my database , and display it on my text area based on the id.
JQuery
$('#verifyBtn').on("click", function() {
var exeOutput = checkOutput();
$("outputArea").html(exeOutput);
});
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}
function getOutput(dataStr, flag) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
return data;
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}
Through my servlet for getting from my database.
Servlet
exercisesModel outputModel = null;
try {
DBConnection db = new DBConnection();
outputModel = db.getExerciseById(request.getParameter("exNo"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.getWriter().append(outputModel.getExpOutput());
EDIT: Upon clicking, i think there is data but my text area is not displaying it.
Since you're making an Asynchronous call you can't return an immediate response using return data;, but instead you could pass the selector then assign the result to your output element when the success callback is called:
<script>
$('#verifyBtn').on("click", function() {
checkOutput("outputArea");
});
function checkOutput(output_selector){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true, output_selector);
}
function getOutput(dataStr, flag, output_selector) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
$(output_selector).html( data );
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}
</script>
NOTE : The passed flag parameter isn't used.
Hope this helps.
This block here:
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}
try adding a return to the getOutput line
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
return getOutput(dataString, true);
}
By value i guess you mean the result of the call. You can find that in the parameter of the success handler.
success: function (data) {
//This is your result from server.
console.log(data);
return data;
}
Take a look at your JS console to see the results.

jquery : constructed data is undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I spent lot of time to figure this out but did not find anything,
function constructAgenciesData() {
$.ajax({
url: "getAgenciesAndGlobalJson.do",
dataType: "json",
success: function(data){
$.each(data, function (index, row) {
// console.log("data : "+ JSON.stringify(data));
$("#"+row.id).data("assignedAgencies", row.assignedAgencies).data("restOfAgencies", row.restOfAgencies).data("global", row.global).data("globalID", row.globalID);
});
}
});
}
constructAgenciesData();
$(function($){
$(".globalswitch").each(function () {
var idRow = $(this).parents('tr')[0].id;
alert(idRow);
console.log($('#'+idRow).data("global"));// <-- UNDEFINED
$(this).switchButton({
checked: row.data("global")
});
});
$(document).on('click','button.btn', function () {
var idRow = $(this).parents('tr')[0].id;
var title = $(this).parents('td:first').siblings(':eq(1)').text();
title = "Rule Name : " + title;
$("#divPopUp").data('param_1', idRow);
$("#divPopUp").data('opener', this).dialog("option", "title", title).dialog("open");
console.log($('#'+idRow).data("global"));// <-- WORKING
var old_array = $('#'+idRow).data("restOfAgencies");
var new_array = $('#'+idRow).data("assignedAgencies");
addCheckbox(diff(old_array,new_array));
});
});
I don't know why the same line :
console.log($('#'+idRow).data("global"));
is undefined in the .each function.
BUT it is working in the click function .
Your $.ajax call is asynchronous. This means that it is firing request while the rest of the Javascript is being run.
The success function within constructAgenciesData() might not have been completed prior to the IIFE $(function($){.
Therefore, there is no guarantee that the .data('global') will be set by the time you're trying to access it within the $(".globalswitch").each loop.
A solution to this issue would be to wrap the $(".globalswitch").each loop within a function globalSwitchLoop() and fire that on the success of the $.ajax call.
Also, take a look at jQuery's promises.

Why return not working after Ajax call jquery? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am not able get the returned value after ajax call. I can see that values are being returned but when I do console.log() it shows undefined. Is there something wrong in my approach.
var base_path = "http://localhost/lab/theapp/api/"
$(function () {
var url = base_path + "tasks"
var type = "post"
var data = ""
var get = submit_me(type, data, url)
console.log(get)
})
function submit_me(type, data, url) {
try {
$.ajax({
url: url,
type: type,
data: data,
dataType: "json",
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", $.cookie("token"))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('page_login_submit - failed to login');
console.log(JSON.stringify(XMLHttpRequest))
console.log(JSON.stringify(textStatus))
console.log(JSON.stringify(errorThrown))
},
success: function (r) {
if (r.sessid) {
var sessid = r.sessid
var session_name = r.session_name
var token = r.token
jQuery.cookie("token", token)
return r
}
},
})
} catch (error) {
console.log(error)
}
}
Your ajax call will take some time to retrieve that values. You cannot pass the value directly to the variable. Write the code in ajax success function. ie console.log() in ajax request function. That would follow the delay caused by the ajax call. Try this link https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings Check the async attribute here and experiment.

jquery ajax gets HTML but will not return it [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return the response from an AJAX call from a function?
I'm trying to get some HTML content via ajax. But for some reason, though the HTML makes it to the ajax function, when I try to use it as a returned value, I get undefined.
Like this:
function get_additional_options(name) {
var post = $.ajax({
type: 'post',
url: 'order_queries_templates/html/' + name + '_additional_options.php?<?=time()?>',
//data:'product_id=' + product_id,
dataType: 'html'
});
post.done(function (p) {
console.log(p); //prints out all the HTML just as I would expect
return p;
});
}
but when I try to get the HTML to append it to my page like this
if (has_additional_options == "t"){
var html_to_append = get_additional_options(name);
console.log(html_to_append); // undefined
}
It is the same result if I use the done() method, or just return the value as a success callback. What is my error?
You can't return values from asynchronously called functions.
You should return post (i.e. the result of $.ajax) and then register a .done handler outside of your function:
function get_additional_options(name) {
return $.ajax({
...
});
};
if (has_additional_options == "t") {
get_additional_options(name).done(function(p) {
console.log(p);
});
// NB: code execution continues here immediately - don't do anything
// else here - all further stuff must be done in the above callback
}
You are returning the HTML value inside the anonymous function.
You're basically passing it to the post.done method.
Maybe it's better to use events in this case since you're running asynchronous code here.
function get_additional_options(name) {
var post = $.ajax({
type: 'post',
url: 'order_queries_templates/html/' + name + '_additional_options.php?<?=time()?>',
//data:'product_id=' + product_id,
dataType: 'html'
});
post.done(function (p) {
$("body").trigger("html_loaded",[p]);
);
}
$("body").on("html_loaded", function (htmlData) {
// Do something with your HTML data here.
$(this).append(htmlData);
});

Categories