Getting variable from ajax function - javascript

I've this function.
function ajaxtakesource4(callback){
var ajaxRequest; // The variable that makes Ajax possible!
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange =function(){
if(ajaxRequest.readyState == 4 &&ajaxRequest.status==200){
var sourcetest = ajaxRequest.responseText;
callback(sourcetest);
}
}
ajaxRequest.open("POST", "takesource4.php", true);
ajaxRequest.send(null);
}
Also:
var somous4;
function run() {
ajaxtakesource4(function(sourcetest){
somous4=sourcetest;
});
alert(somous4);
}
and here I call the above the function:
<div id="run">
<button id="button_run" class="button" onclick="run()">Run</button>
</div>
To make it clear i need to use the variable of somous4 in the function run not only to print it. My idea is to call a number of variables , with the same procedure. I need to store,use these variable by the some way(this is what i am searching) use all of them in the function and run the algorithm. I need something like to return these variables (i think it is not possible) or to use them as global variables in the function run. Thanks for your interest!

Related

Getting response From Ajax call

When trying to get the responseText from an ajax call built in plain vanilla javascript, Firebug seems to see the request but one cannot get a reference to the responseText.
This is the code for function
function getAjaxResponse(){
var ajaxObj = getAjaxObj();
ajaxObj.open('get', 'responsePage.php', true);
ajaxObj.onReadyStateChanged = function(){
if(ajaxObj.readyState == 4
&& ajaxObj.status == 200){
//no functions are getting fired in here
//this does not get logged to console
console.log(ajaxObj.responseText);
//neither does this
console.log(2);
}
};
ajaxObj.send(null);
//this does gets logged to console
console.log(1);
}
function for the ajax object
function getAjaxObj(){
var req;
if(window.XMLHttpRequest){
try{
req = new XMLHttpRequest();
} catch(e){
req = false;
} finally {
return req;
}
} else {
if(window.ActiveXObject){
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
req = new ActiveXObject("Msxml.XMLHTTP");
} catch(e){
req = false;
} finally {
return req;
}
}
}
}
}
Also here is the view from firebug
How to get a reference to the response from the ajax call?
OnReadyStateChanged needs to be onreadystatechange. JavaScript is case-sensitive.
ajaxObj.onReadyStateChanged: onreadystatechange should all be lower case (and without the trailing 'd')

Variable out of scope [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return AJAX response Text?
How to return the response from an AJAX call from a function?
After whole day without solution to this. I read that this isn't possible or cant be done etc. I did go trough all of topics related, but cant find solution.
So i think my variable in code is out of scope and i cant return it, cant use it.
js file:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4)
{
var myvar = new Array();
myvar=JSON.parse(xmlHttp.responseText);
return myvar;
}
}
xmlHttp.open("GET", "showimage.php", true);
xmlHttp.send();
}
So here above is ok, its returning value of php script when its finished.
And i want this myvar variable in html file. Tried like this:
window.onload = function() {
var myvar = MakeRequest();
alert (myvar);
}
It fails, returning undefined value.
Tried also making MakeRequest function as callback function, and then calling it from html like
MakeRequest(function(txt){
});
Then I got response, but can just alert it. I don't want to alert it. I need it to be stored in variable myvar because its needed later in code.

Return Json Encode not set

I have a simple ajax request which gets a json encode array but it keeps telling me its not set... im thinking i have the return in the wrong place but am not sure where i put it... this is my function:
//Browser Support Code
function ajaxFunction(url,data){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var response = ajaxRequest.responseText
}
}
queryString = "?dta="+data;
ajaxRequest.open("GET", url + queryString, true);
ajaxRequest.send(null);
return(response);
}
I then call the function like this:
var result = ajaxFunction('call.php','1');
alert(result);
The response is working as in console it says:
{"stage1":"550","stage2":"1500","stage3":"2000","total":"1"}
But I'm getting: response is not defined
Any ideas?
There are 2 resons why response is undefined:
syntax: it is defined in inner function, so it is not visible in outer scope. So your return (response) actually is return (window.response)
logical: the response is set in asynchronous callback, so when you synchronous function returns it would not be set even if you define it in the ajaxFunction itself.
To fix it have callback that will eventually return result. Check how jQuery.ajax return it result by calling success(data, textStatus, jqXHR) passed as argument to the function.
You can also force synchronous requests by passing "false" for third (isAsync) parameter of open call check MSDN or MDN.

Ajax response works after two clicks?

I just wrote a basic user-login system where the html page uses javascript to send the ajax request to a servlet which accesses through database.
Here's the js code
var res;
function getXMLObject()
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
res=xmlhttp.responseText;
}
else {
return false;
alert("Error during AJAX call. Please try again");
}
}
function ajaxFunction() {
var veid=document.getElementById("eid").value;
var vpwd=document.getElementById("pwd").value;
//window.alert('here inside ajaxFunction'+vconf+' '+vseid);
if(xmlhttp) {
xmlhttp.open("GET","check_login?eid="+ veid +"&pwd="+ vpwd,true); //this is the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function def()
{
//window.alert('hi');
ajaxFunction();
//alert('res:'+res);
if(res=='y')
{
return true;
}
else
{
document.getElementById("uhidden").style.color="#CC0000";
document.getElementById("uhidden").innerHTML="Invalid E-Mail ID or Password"
return false;
}
}
But the code works only after two clicks :(
Any help guys?
Your def function calls ajaxFunction and then straight away checks the res variable. However ajaxFunction just sends the AJAX request; it does not wait for the AJAX response to arrive. Your code is checking the res variable before it is being set from the AJAX response.
This is why it works on the second click - not because the res variable is being set by the second click's AJAX response, but because it is still set from the first click's AJAX response.
The solution is to re-arrange your code a bit. Move the code to display the invalid login message to where the AJAX response is received. In other words, replace the res=xmlhttp.responseText; line with some code to check if xmlhttp.responseText is not y and display the invalid login message.
I guess you call def()
Your Request ist asynchron(because you set the 3rd argument of open() to true ), but in def() you immediately after sending the request work with the the result:
ajaxFunction();
//alert('res:'+res);
if(res=='y')
At this time the request usually is not finished, the result not available yet
Put all code that has to work with the server-response into handleServerResponse()

How do you call an ASHX from JavaScript?

I want to call an ASHX file and pass some query string variables from JavaScript and get the return string into a string in the JavaScript. How would I do this?
The ASHX file is already coded to response.write a string based on whatever the query strings are.
Something like this?:
function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
alert("XMLHttpRequest not supported");
return null;
}
var xmlHttpReq= createXMLHttpRequest();
xmlHttpReq.open("GET", "your.ashx?v1=1&v2=2&etc", false);
xmlHttpReq.send(null);
var yourJSString = xmlHttpReq.responseText;

Categories

Resources