0

I'm using the ajax technique in combination with php and I want to know how to get the return variable from the function that is called by onreadstatechange.

A java function is called onsubmit to then call a php script to verify some things in my database and return true or false depending on the results.

Here is where I run into problems, I want the onsubmit="return snappyajaxfunction()" to return false or true based on the results from the php.

My question is, how do I get the result of false or true from the stateChanged function to become the return for snappyajaxfunction.

I tried doing this for kicks: result = request.onreadystatechange=StateChanged with no luck.

I've also tried saving the responsetxt to a global variable then returning the global variable in snappyajaxfunction with no luck.

snappyajaxfunction()
{

   request.onreadystatechange=stateChanged;         
   request.open("GET",url,true); 
   request.send(null);

   return result;
} 

function stateChanged() 
{ 
    if (request.readyState==4)
    {   
       return request.responseText; 
    }       
}

The purpose of this is to script is to verify the username / password entered by the user with the username / password stored in my database. If it they don't match it returns false and the form will not submit, if it does the form submits and the user is brought to the welcome page...

payling
  • 2,466
  • 5
  • 33
  • 44
  • 3
    Any particular reason you're not using a framework like jQuery for this? – brettkelly Dec 23 '09 at 20:53
  • http://stackoverflow.com/questions/290214/in-ajax-how-to-retrive-variable-from-inside-of-onreadystatechange-function - Same question. Maybe that can help you. – Jeff Rupert Dec 23 '09 at 20:58
  • 3
    I'm new to coding and I enjoy learning the tough way first so I know the mechanics of things I suppose? – payling Dec 23 '09 at 20:59
  • 2
    Maybe it is an assignment or to learn the basics.. personally I wouldn't tell someone to use jQuery when a problem like this is not trivial... it's just burying the problem deeper (I he wants to do serious JavaScript in the long term) – Mike Gleason jr Couturier Dec 23 '09 at 20:59
  • probably a good approach. I would suggest writing at least one fully-functional ajax script w/o any frameworks for that very reason. – Derek Adair Dec 23 '09 at 21:01
  • @payling You're absolutely right, take a look at "closures" also. The "Definitive JavaScript" book is a good start before getting used to any library or framework. Have a good time learning during the holidays! – Mike Gleason jr Couturier Dec 23 '09 at 21:03

5 Answers5

1

You could do:

function stateChanged() 
{ 
    if (request.readyState==4)
    {   
       OnStateChanged(request.responseText);
    }           
}

Where OnStateChanged is a function that act as an event handler...

EDIT: in OnStateChanged you can then submit or not your form based on response

EDIT2: On the server when you check the u/p, if they're right log the user right on and return the status to JavaScript.. then in the JavaScript instead of resubmitting a form, just reload/redirect the page if it is successful or display an alert otherwise...

It is just not possible to return something from a function by an asynchronous operation in it... the original thread of execution is long gone. The asynchronous operation is executed by another thread (If I remember correctly, don't flame).

Thanks

  • I ended up making it a synchronous function instead and that worked by setting the state changed result to a global variable and then returning it at the end of snappyajax. request.open("GET",url,false); – payling Dec 28 '09 at 13:57
  • @payling : Keep in mind synchronous queries got deprecated and using them should raise an error. – user2284570 Oct 08 '14 at 22:10
1

jQuery won't automagically fix the fact that he's trying to base his submission on the results of an asynchronous request.

What you can do is the following:

1) Set the form onsubmit to simply call snappyajaxfunction();

2) In stateChanged, if the readystate is 4, obtain a reference to the form and do the following:

form.onsubmit = function() { return true; };
form.submit();

Basically - Set the onsubmit to always return true and then force it to submit again. For added usability you may want to disable the button causing the submission while waiting for statechanged to happen. And then re-enable it.

zincorp
  • 3,284
  • 1
  • 15
  • 18
  • Seems a bit like a hack job but it'll work.. – payling Dec 23 '09 at 21:05
  • If you want it to seem less hacky, change the submit button to be a regular button and have that call snappyajaxfunction(). Instead of having to then overwrite the form's onsubmit you just call form.submit(); if the readystate is 4. – zincorp Dec 23 '09 at 21:08
0

feel free to check out this tutorial on ajax.

It will show you how to properly use ajax step-by-step

as inkedmn has suggested, I would recommend using jquery or any of the other js frameworks

Derek Adair
  • 21,846
  • 31
  • 97
  • 134
0

The problem is that ajax calls are asynchronous. That means the response is separate from the request. You have to modify your code to handle that. You cannot (should not) make http calls synchronous.

Look at this code. It works, and you'll be able to read the response:

var req = new XMLHttpRequest();
req.open('GET', url, true);
req.onreadystatechange = function (ev) {
    if (req.readyState == 4) {
        alert(req.responseText);
    }
};
req.send(null);
Gabriel McAdams
  • 56,921
  • 12
  • 61
  • 77
  • Read the response... But not handle it by the caller without using a global variable *(ex: knowing if the script is run as [user script](http://stackoverflow.com/q/26247041/2284570?noredirect=1#comment41183426_26247041))*. – user2284570 Oct 08 '14 at 22:14
0

To make your code work you can use closures and pass functions as parameters.
2 properties javascript is very good at.

snappyajaxfunction(url, fn)
{
   var request...

   request.onreadystatechange=function() 
    { 
        if (request.readyState==4)
        {   
           fn(request.responseText);     
        }           
    };             
   request.open("GET",url,true); 
   request.send(null);
}

to use it you can build a function like

var doSomething = function(response){
  alert(response);
};
snappyajaxfunction('/country/code/32', doSomething);

The closure allows 'request' to be available within the function that handles the onreadystatechange. The function 'fn' is passed as a parameter of snappyajaxfunction.

Mic
  • 24,812
  • 9
  • 57
  • 70
  • Hum, I'm not sure if I understand how this helps me. You pass the response into function fn then you alert the result, how does snappyajaxfunction return the alert..? – payling Dec 23 '09 at 21:24
  • snappyajaxfunction does not return anything. This is asynchronous, the time you call is not immediately followed by the time you get a response. A callback function such as 'fn', is the typical way to handle this kind of asynchronism. when the readyState is 4, the function fn will be called with the responseText. And inside the function doSomething you have your response and usually you show something to the user (ie: an alert in this example) – Mic Dec 23 '09 at 21:33
  • @Mic : There are some case a callback function can't work because the caller definitely need to work with the result of the request. – user2284570 Oct 08 '14 at 22:19