JavaScript callback function is not working in my case [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I have a function that will return an AJAX response and use it on another function. Here is my code:
function updateLoanApproval(answer){
var password = document.getElementById("password").value;
var usid;
getExistingId(function(success){
if (success === 0){
var usid = "No ID Available";
} else {
var usid = success; //To get the returning value
}
});
alert(usid);
And here is the code for getExistingId()
function getExistingId(){
var url = "../../library/functions.php?action=getId";
var uid;
http.onreadystatechange = function(){
if (http.status == 200 && (http.readyState === 4)){
uid = http.responseText;
if (uid == "No ID"){
callback(0);
} else {
callback(id);
}
}
}
http.open("GET",url,true);
http.send();
}
As I test the code, I don't have a problem with a query or PHP code so I will not include it here, but why is usid always return undefined?

See carefully, You are missing callback parameter in getEdiistingId() function. Do like following:
function getExistingId(callback){
var url = "../../library/functions.php?action=getId";
var uid;
http.onreadystatechange = function(){
if (http.status == 200 && (http.readyState === 4)){
uid = http.responseText;
if (uid == "No ID"){
callback(0);
} else {
callback(id);
}
}
}
http.open("GET",url,true);
http.send();
}
And put alert inside callback method.
function updateLoanApproval(answer){
var password = document.getElementById("password").value;
var usid;
getExistingId(function(success){
if (success === 0){
var usid = "No ID Available";
} else {
var usid = success; //To get the returning value
}
alert(usid);
});
A method that need usid:
function doMyTaskThatNeedUsid(usid)
{
// do something.
}
And call method like following:
function updateLoanApproval(answer){
var password = document.getElementById("password").value;
var usid;
getExistingId(function(success){
if (success === 0){
var usid = "No ID Available";
} else {
var usid = success; //To get the returning value
}
// Calling method that need usid.
doMyTaskTaskThatNeedUsid(usid);
});

Related

Javascript runtime Object doesn't support this property error

I have a javascript function which get's me the emailID of the respective text added.
But what happens if the EmailID doesn't exist's it gives me error as
Microsoft JScript runtime error: Object doesn't support this property or method
Here is the function.
function getEmailIdByType() {
StrPriFnName = "FunGetEmailIdByType(" + document.getElementById('TxtPartyName').value + ")";
var ObjPriXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP")
ObjPriXMLHTTP.open("GET", "FrmInwardXMLHTTP.aspx?para=" + StrPriFnName, false);
ObjPriXMLHTTP.send("");
if (Trim(ObjPriXMLHTTP.responseText) != "") {
var StrPriData = ObjPriXMLHTTP.responseText.Split('~');
document.getElementById('TxtEmail').value = StrPriData[1];
}
else {
return false;
}
}
It gives me error at line:-
var StrPriData = ObjPriXMLHTTP.responseText.Split('~');
if (Trim(ObjPriXMLHTTP.responseText) != "") {
var StrPriData = ObjPriXMLHTTP.responseText.Split('~');
document.getElementById('TxtEmail').value = typeof StrPriData[1] != "undefined" ? StrPriData[1] : "";
}
else {
return false;
}
You should try to access the responseText only when the ObjPriXMLHTTP changes it's readyState
ObjPriXMLHTTP.onreadystatechange = function() {
if (ObjPriXMLHTTP.readyState == 4 && ObjPriXMLHTTP.status == 200) {
var StrPriData = ObjPriXMLHTTP.responseText.split('~');
}
Probably the responseText property is only available after it got a response. The response hasn't really arrived where you try to see it.
Here is a full example.

Ajax call inside a while loop

I want Ajax to get information while the information is valid. So if I do
$(document).ready(function () {
var url = '/my/url/';
var ses = true;
var i = 0;
while (ses) {
i++;
var temp;
$.get(url + "?get=" + i, function (data) {
if (data != '') {
temp = data;
sortArticles(data);
}
});
if(temp == '') ses = false;
}
});
If I do this without while (putting 0 instead of get var), I get the information I need, but if I put it like this, I enter an infinite loop and the page breaks. By the way, I tested and the if(data != '') statement works as intended.
I don't know why temp doesn't change the state of the ses variable. I tried putting an else statement inside $.get(..)
else ses = false;
but it doesn't do the trick neither.
Thanks for reading!
jQuery ajax (as most ajax implementations), which $.get() is a shorthand for, is asynchronouos be default. The callback function is only executed once the request is complete. The while continues indefinitely since without yielding control out to the JS engine the callback doesn't get a chance to do it's work - even if the request(s) are done.
In order to continuously send requests, try like this:
function requestMore(i) {
$.get('/my/url/?get=' + i, function (data) {
if (data != '') {
sortArticles(data);
requestMore(i + 1);
}
});
}
(document).ready(function () {
requestMore(1);
});
The way you wrote your code temp will never be ''.
The problem is temp is not a string. It's undefined.
Instead of:
if(temp == '') ses = false;
write:
if(typeof(temp) == 'undefined') ses = false;
$(document).ready(function () {
var url = '/my/url/';
var ses = true;
var i = 0;
while (ses) {
i++;
var temp='';
$.get(url + "?get=" + i, function (data) {
if (data != '') {
temp = data;
sortArticles(data);
}
});
if(temp == '') ses = false;
}
});
This will work.Initialize temp as a blank string as shown :)

how to pass json parameters btween 2 files using module

i am trying to call function in other js file using require.all these the parameters
> Login = require("LoginRequest");
Create = require("CreateView");
var params = { username : username.value , password : password.value};
var type ="POST";
var URL = "https://localhost/post_auth.php";
var Result; </li>
and here the call funcion from LoginScreen.js
b2.addEventListener('click',function(e)
{
alert(params.username);
if (username.value != '' && password.value != '')
{
Result=Login.Request(params,type,URL);
}
else
{
// warning alert
alert("Username/Password are required");
}
if (Result.logged == true)
{
alert("Welcome " + Result.name + ", Please answer the following question");
Create();
}
else
{
alert(Result.message);
}
});
when i try to pass the parameters to LoginRequest.
function Request(params,type,url){
var Result;
var loginReq = Titanium.Network.createHTTPClient();
loginReq.open(type,url);
loginReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
//send parameters
loginReq.send(JSON.stringify(params));
loginReq.onload = function()
{
var json = this.responseText;
Result = JSON.parse(json);
alert (Result.logged);
alert (Result.name);
};
return Result;
};
exports.Request = Request;
the calling return undifiend object , where is my wrong here ?
That's because you are making an async call.
when you call loginReq.send() the call will be made and it will continue executing the rest of the code without waiting for the async call to be finished, that's why the function returns undefined.
To fix this you can make a sync call instead of an async call (this is a bad bad bad idea) or you could restructure your code, maybe LoginRequest could return the loginReq instance instead of the result

How to return value from ajax

How to get the return value true and false.
I always get undefined and after read some article i still didn't understand.
My reference:How to return value from an asynchronous callback function?
function validateScreenName(value){
var screenname = document.getElementById("screenname-box").value;
if((screenname.length < 3) || (screenname.length > 20)){
value(false); // if I change to return false still can't get the value. Always undefined.
}else{
if(screenname != "something"){
var http = new XMLHttpRequest();
var param = "screen_name="+screenname;
var url = "screen-name-validation.php";
http.open("POST",url,true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function(){
//The response from server is either 1 or 0
if (http.readyState==4 && http.status==200){
if(http.responseText == 0){
value(true); // I can't get this value
}else{
value(false);
}
}
}
http.send(param);
}else{
value(false);
}
}
}
I need this value to this script
function disableSubmit(){
validateScreenName(function(val2){
var val1 = validateFullName();
var val3 = validateTargetName();
//I need val2 from validateScreenName
if(val1 && val2 && val3){
//if all true do something
}else{
//if one of the value false do somthing
}
});
}
Can someone explain how to get the value with only javascript without jquery? thanks.
Instead of returning typeof bool(false,true), use returning string..eg.,"true" or "false"

Why HttpRequest callbacks not working without alert

I have a issue in getting response in Kony application. this is the code
function getServerResponceOption(url){
alert(url);
var httpclient2 = new kony.net.HttpRequest();
var requestMethod = constants.HTTP_METHOD_GET;
var async = true;
httpclient2.open(requestMethod, url,async);
if(getAccessToken() != null && getAccessToken() != ""){
httpclient2.setRequestHeader("AuthToken",getAccessToken());
}
httpclient2.send();
httpclient2.onReadyStateChange = HandleResponce(httpclient2);
}
function HandleResponce(obj)
{
alert("Getting data "+obj.readyState+" Status "+obj.status+" Response "+obj.response );
if(obj.readyState == 4 )
{
if (obj.response != null && obj.response != "")
{
var jsonObj = obj.response;
handleResponseOption(0,jsonObj);
return;
}
else
{
}
}else{
var state = obj.status;
alert("Readystate "+obj.readyState+" Status = "+state);
}
if (obj.response != null && obj.response != "")
{
var jsonObj = obj.response;
handleResponseOption(1,jsonObj);
}
}
Here i got server response if i put the alert message in HandleResponce(obj) without the alert i didn't get any response. the ready state is 1 and status is 0. What is the problem occurred if i remove the alert message?
Note: URL and getAccessToken() is getting values.
You are calling function in line, When you use HandleResponce(httpclient2) function is immediately executed.
httpclient2.onReadyStateChange = HandleResponce(httpclient2);
Change your code as
httpclient2.onReadyStateChange = function(){ HandleResponce(httpclient2) };

Categories

Resources