AJAX Request returns 'undefined' - php

For some reason I always receive undefined if I return the value but if I'm trying to display it in alert I receive the php values.
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) {
//Browser does not support AJAX
return false;
}
}
}
return xmlHttp;
}
function isUsernameExists() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
handleResponse(xmlHttp.responseText);
}
}
var str = document.getElementById('username').value.toString();
xmlHttp.open("GET", "ajax.php?username="+str, true);
xmlHttp.send(null);
}
Edit:
function handleResponse(response) {
return response.toString();
}
Thanks,
Guy Dor

It looks like you are trying to read the return value from this function:
function isUsernameExists() {
It doesn't have a return statement, so it will always be undefined.
I'm guessing you expect this return statement to pass the value you want:
return xmlHttp.responseText.toString();
But that is part of this function:
xmlHttp.onreadystatechange = function() {
Which is called automatically when the readystatechange event fires, and not by any function call you make.
Asynchronous JavaScript and XML rarely uses XML but is asynchronous. Anything you want to do with the data fetched needs to be done by the callback function you assign to onreadystatechange. It can call other functions, but it cannot return anything (at least not that will be received anywhere useful).

We can't see enough of your code to fully understand the situation, but you are dealing with an asynchronous operation and the only way to communicate the result of that asynch operation is to call a function with the value you got from that operation. You cannot just return from the function.
This is a common misunderstanding (the sixth time I've answered this issue today). The function on have for the ready state change is not called by any of your code. It's called by the browser internally when the ajax call completes. That means that returning your value from that function will do nothing and certainly won't communicate that result to any of your code. If you want to communicate that result to some of your code, then you need to call some of your code from inside that function and pass it the desired result so that code can act on it. This breaks the normal flow of programming, but is required when dealing with asynchronous operations.

you have a return statement in the function your create here,
xmlHttp.onreadystatechange = function() {
but there is no return statement in the function,
function isUsernameExists() {
just because you created the function within another function does not mean the code in that function gets run.
the code within the function you created will not run until a response is received from the server, by which point the original function that created the second function will have already finished execution.
the code does not halt to wait for a response from the server, it instead continues to run and finishes execution. the function that you created to handle the response from the server then gets run at a later time when a response is received.

Related

xmlhttp Request with callback function

I want to return the responsetext of an ajax call. I'm not succeeding and I get the whole time undefined:
function ajaxFunction(callback,tekstvar){
xmlhttp= new GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="php/functions_translate.php";
url=url+"?tekst="+tekstvar;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
return callback(xmlhttp.responseText)
};
};
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function translate(tekstvar) {
var text = ajaxFunction(function(tekst){return tekst;},tekstvar);
return text;
}
I'm calling the translate function to give me a certain translation of word. Does anyone know, what i'm doing wrong?
I've voted to close this due to duplicate. This answer is merely to make the answer found in the duplicate question more relevant to this specific question.
Please read this for more info: Undefined return value from the function call Javascritpt
You need to add a callback to the translate() function:
function translate(tekstvar,callback) {
ajaxFunction(callback,tekstvar);
}
If you expect to call translate like this:
var newtext = translate(text);
displayText(newtext);
doSomethingElseWith(newtext);
then I'm sorry but that's not possible with asynchronous code. You need to put all the code that you would have written after calling the translate function to be inside the callback you pass into the translate function.
In other words, modify it like this:
var newtext = translate(text);
//
//--------------------------------------- move everything below this line
// into the callback
displayText(newtext);
doSomethingElseWith(newtext);
so that it looks like this:
translate(text,function(newtext){
displayText(newtext);
doSomethingElseWith(newtext);
});

PHP, run code without opening windows on the webbrowser

If I have a list of elements, and via javascript the user moves the elements in another order, can I, after each move, launch a php code (like a php page) but without having to call it in the browser?
Create an XmlHttpObject for the URL, send() it, check results to see if the call was successful, and discard the responseText. As an example, suppose you have the new order in a variable testUrl, e.g., "http://domain.com/script.php?order=1,4,3,2"
var xmlHttpObject = new XMLHttpRequest();
xmlHttpObject.open("GET", testUrl, false);
xmlHttpObject.send();
var xmlText = xmlHttpObject.responseText;
if (xmlText == 'Success')
// do nothing
else
alert (xmlText);
An addition to the above answer - for the sake of posterity, in case someone has to debug your code some day :) I use the following function call to get that object: (I believe it makes the JS more readable and portable). You can check the return value and if null, alert the user that AJAX is not supported by the browser.
function getXmlHttpObject () {
var xmlHttpObject = null;
try {
xmlHttpObject = new XMLHttpRequest();
} catch (ex) {
try {
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
} catch (ex) {
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
return xmlHttpObject;
}

How to call multiple AJAX functions (to PHP) without repeating code

I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.
But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?
<script type="text/javascript">
function mom()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('mom').innerHTML = response;
}
</script>
My Trigger is this
<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>
You could modify your function so it takes a parameter :
// The function receives the value it should pass to the server
function my_func(param)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
// Pass the received value to the handler
HandleResponse(param, xmlHttp.responseText);
}
}
// Send to the server the value that was passed as a parameter
xmlHttp.open("GET", "index.php?i=" + param, true);
xmlHttp.send(null);
}
And, of course, use that parameter in the second function :
function HandleResponse(param, response)
{
// The handler gets the param too -- and, so, knows where to inject the response
document.getElementById(param).innerHTML = response;
}
And modify your HTML so the function is called with the right parameter :
<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>
<!-- for this secondcall, you'll want the function to work on 'blah' -->
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>
This should work (if I understand correctly)
<script type="text/javascript">
function func(imgName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById(imgName).innerHTML =
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
</script>
MARTIN's solution will work perfectly.
By the way you should use some javascript framework for Ajax handling like jQuery.
It will make your life easy.
If you are having light weight images you preload the images on your page.
I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.
Added example code:
To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget
var req_fifo=Array();
var eleID=Array();
var i=0;
function GetAsyncData(myid,url) {
eleID[i]=myid;
if (window.XMLHttpRequest)
{
req_fifo[i] = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
}
req_fifo[i].abort();
req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
req_fifo[i].open("GET", url, true);
req_fifo[i].send(null);
i++;
}
function GotAsyncData(id) {
if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
return;
}
document.getElementById(eleID[id]).innerHTML=
req_fifo[id].responseText;
req_fifo[id]=null;
eleID[id]=null;
return;
}
function reget(id) {
myid=eleID[id];
url=urlID[id];
req_fifo[id].abort();
req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
req_fifo[id].open("GET", url, true);
req_fifo[id].send(null);
}
The suggestions to parameterize your function are correct and would allow you to avoid repeating code.
the jQuery library is also worth considering. http://jquery.com
If you use jQuery, each ajax call would literally be this easy.
$('#mom').load('/index.php?i=mom');
And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)
function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');
It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.
At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.

Check for username while typing in field?

I am fluent with HTML, and mostly PHP.
I can do the scanning part with PHP.. I'm just not sure how to call a function in PHP with JavaScript, because I don't know JavaScript.
My PHP code will connect to my MySQL database and see if the text currently in the textbox (Not clicked enter yet, still typing) is in the database..
Do you know how to do this, or at least know a link that tells you how to do it?
This sounds like a problem for jQuery. I'd give you a long-winded example, but there are many people that would give you a much better one: like this guy.
Consider using jQuery in conjunction with jQuery UI, specifically something called autocomplete. I'm fairly certain it does what you're wanting, and it's completely themable for your site.
I see everybody likes jQuery so much, wow!
I'd tell you just need some very basic Ajax script to call your PHP script and receive the response.
Here's the simple Javascript function (actually two):
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
//use this method for asynchronous communication
function doRequest(scriptAddressWithParams, callback) {
if (xmlhttp) {
xmlhttp.open("POST", scriptAddressWithParams, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
else {
alert("Error retrieving information (status = " + xmlhttp.status + ")\n" + response);
}
}
};
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
and here's an example of usage:
<input type="text" onchange="doRequest('myphpscript.php?checkvalue='+this.value, function (returnedText) { alert(returnedText);});"/>

changing values of array elements in javascript functions

These are my three functions that I am using in javascript :
function postRequest()
{
var xmlHttp;
if(window.XMLHttpRequest)
{ // For Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{ // For Internet Explorer
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('GET', 'effort.php', true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
get_string(xmlHttp.responseText);
dij();
}
}
xmlHttp.send(null);
}
function get_string(str)
{
get_integer = str.split(" ");
for(var i=0;i<214;i++)
{
vertex_i[j] = get_integer[i]*1;
j++;
}
j=0;
for(var i=214;i<427;i++)
{
vertex_f[j] = get_integer[i]*1;
j++;
}
j=0;;
for(var i=427;i<517;i++)
{
x[j] = get_integer[i]*1;
j++;
}
j=0;
for(var i=517;i<607;i++)
{
y[j] = get_integer[i]*1;
j++;
}
for(var m=0;m<90;m++)
{
for(var n=0;n<90;n++)
{
L[m][n] = -1;
}
}
for(var m=0;m<212;m++)
{
x1 = x[vertex_i[m]];
x2 = x[vertex_f[m]];
y1 = y[vertex_i[m]];
y2 = y[vertex_f[m]];
L[vertex_i[m]][vertex_f[m]] = parseInt(find_dist(x1,x2,y1,y2));
}
}
function point_it(event)
{
postRequest();
}
namely :
point_it(event),then postRequest(); and finally dij();
In these functions I use the data in three globally defined arrays,the elements of whose are derived from the data sent by the server(get_string function).
if I call dij() function from within the postRequest() function(after the get_string function I am able to access the correct data within the arrays.
However if I call it immediately after the postRequest() function the value of elements in the array become equal to null.
I am unable to understand the proper reason for this and have tried several ways to get through but with no progress.
CAn sm1 please help me out !
postRequest fires an asynchronous request to the server. Calling a function directly after it doesnt mean that the request has finished and youve doen anything with the response data. It works inside postRequest because that where you actually handle processing the request and response.
if you want to do this all from within point it i would recommend doing the following:
function postRequest(callback)
{
var callbackFunc = callback||null;
var xmlHttp;
if(window.XMLHttpRequest)
{ // For Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{ // For Internet Explorer
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('GET', 'effort.php', true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
get_string(xmlHttp.responseText);
if(callbackFunc){
callbackFunc();
}
}
}
xmlHttp.send(null);
}
function point_it(event)
{
postRequest(dij);
}
this allows you to vary the callback that uses the array thats been populated by the post request and in a away that it always fires after that request cycle is complete.
XMLHttpRequest is asynchronous.
That means, it will return as soon as the request was send. If you now call dij() the request will still be pending and get_string wasn't called yet.
As soon as the requests completes, the callback will be called, and then execute get_string.
You need to leave dij() inside the callback too.
Visually:
postRequest is made, sets the callback, but does not execute it, postRequest then returns
the code after the call to postRequest executes
some time passes...
the XMLHttpRequest finally completes and the callback executes, which now calls get_string
Global variables are not a good practice. It is better to combine your get_string and dij functions into one with your arrays as local variables inside the single function.

Categories