How to return value from ajax - javascript

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"

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.

Two ajax calls and only one is running

I have the following http variable which returns an object:
var http = (function(){
var success = null;
var error = null;
var requestInfo = {content: '', status: 0};
var core = {
request: function(options){
var $http = Object.create(http);
sendRequest(options).then(function(){
if(typeof(success) == 'function'){
success(requestInfo.content);
}
}, function(){
if(typeof(error) == 'function'){
error(requestInfo.content);
}
});
return $http;
},
success: function(callback){
success = callback;
return this;
},
error: function(callback){
error = callback;
return this;
}
};
function sendRequest(options){
return new Promise(function(resolve, reject){
var xhttp = new XMLHttpRequest();
var method = options.method.toUpperCase();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4){
requestInfo.content = JSON.parse(xhttp.responseText) || xhttp.responseText;
requestInfo.status = xhttp.status;
}
if (xhttp.readyState == 4 && xhttp.status == 200) {
resolve(requestInfo);
}else if(xhttp.readyState == 4 && xhttp.status != 200){
reject(requestInfo);
}else if(xhttp.status >= 400){
reject(requestInfo);
}
};
xhttp.open((method || 'GET'), options.url, true);
var data = options.data || '';
xhttp.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').getAttribute('content'));
if((typeof(data) == 'object' && (Object.keys(data).length > 0) || data.length > 0)){
xhttp.send(JSON.stringify(data));
}else{
xhttp.send();
}
});
}
return core;
})();
If I call it more than once simultaneously, like so:
http.request({url: '/path1'}).success(function(){
alert('success');
});
http.request({url: '/path2'}).success(function(){
alert('success');
});
only one of the items gets passed via ajax the other one does not. What is causing this? I thought that doing Object.create(this) would make each one unique from each other but it doesn't seem to be doing that...
The Object.create() method creates a new object with the specified prototype object and properties.
So you're creating 2 objects with the same prototype, and the data is in the prototype itself. Since the prototype is an object, and it is the same, both resulting objects have the same references for their data objects and functions.
You need to specify the data not in the prototype object, but for each instance instead.
So after you create var $this = Object.create(this);, you must add the data to $this, such as successFunc, otherwise the next call will override this data.
The sucessand error variable used to store your callback functions must be created within your request function to be truly unique per request. However, if you're going to use Promises, I'd suggest simplifying the whole deal using load and error event listeners available to the XMLHttpRequest object (a nice example can be found on MDN's XMLHttpRequest article) and simply passing in your success and failure functions the then method of your Promise instance.
Here's a simplified JSFiddle example using a timeout to simulate a 500 millisecond HTTP request.
The issue was with this line:
var method = options.method.toUpperCase();
I was not setting the method property in the options and it wasn't erroring saying that it couldn't send, it basically just exited the method without warning...
I changed it to this:
var method = (options.method || 'GET').toUpperCase();
and it started to work.

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

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);
});

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) };

JavaScript Comparision fails, when retrieving the values from the Servlet through ajax

Using the function storeSessionId() , I retrieved the value of storedSession and assigned to sessionId from the servlet using AJAX.
var storedSession;
var sessionId;
function storeSessionId(){
try
{
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
storedSession = xmlhttp.responseText.toString();
sessionIdValue(storedSession);
}
};
xmlhttp.open("POST","JoinAction?subject="+subject+"&userId="+userId+"&secureKey="+secureKey,true);
xmlhttp.send();
}
catch(err)
{
alert(err.description);
}
}
When I compared the sessionId!=null only my div will be displayed else it cannot be displayed.
But even if I got sessionId==null also, my div was displayed. My div was displayed in both the condition.
function sessionIdValue(storedSession){
sessionId = storedSession;
if(sessionId != null && sessionId != "null"){
document.getElementById("div").style.display="inline";
}
}
Most likely sessionId is an empty string "". Try changing the condition to
if(sessionId && sessionId != "null")
This will just check for a truthy value which the empty string is not.
You are comparing sessionId != null which is incorrect.
Put alert(sessionId) to know the response value.
Try:
if(sessionId && sessionId != "null"){
document.getElementById("div").style.display="inline";
}
First condition checks whether sessionId is not undefined and then for null string.
The solution is ,
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g, "");
}
I passed the sessionId value in to trim()...
Thanks for all who helped me..

Categories

Resources