Question

Why doesn't this javascript ajax function return a value?

Asked by: CoastalData

Hello Experts,

I have this relatively simple function which sort of works, but won't return a value for me to then assign to the innerHTML of a div:

/***********************************************
* Basic Ajax Routine- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
function processGetPost(){
      var myajax=ajaxpack.ajaxobj
      var myfiletype=ajaxpack.filetype
      var myresponse
      if (myajax.readyState == 4){ //if request of file completed
            if (myajax.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful or running script locally
                  if (myfiletype=="txt")
                        // works:
                        alert(myajax.responseText);
                        // returns undefined:
                        return(myajax.responseText);
                  else
                        return(myajax.responseXML);
            }
      }
}

I can see that the function works because I can use the alert to see the response, but for some unknown reason, I can't return that value to another function which then assigns the responseText to the innerHTML of a div on the page.

Could somebody please take a look and see if you can spot my error?

Thanks in advance!

--Jon

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-02-19 at 14:38:10ID22399738
Tags

ajax

Topics

JavaScript

,

Dynamic HTML (DHTML)

Participating Experts
4
Points
125
Comments
17

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. DHTML Editor - Insert Table Into div innerHTML
    I am tring to write a wysiwyg editor... The following code represents the functionality to insert a table. My problem is, I can't figure out how to insert it into the existing innerHTML. I've only been able to append it to the end: <html> <head> <title>T...
  2. ajax and innerHTML ?
    Hi, How do you write out a select menu using innerHTML and populate it dynamically? I have this snippet tdObjs[2].innerHTML = ' <select name="contact_type_id" </select> '; Without hardcoding the option tags, how can I populate the above select menu? I...
  3. HTML DHTML best practices div and innerHTML
    A couple of questions about best-practices when it comes to HTML and DHTML. 1. Is there any reason why I souldn't use innerHTML? I thought I read somewhere that it's depricated but I'm not sure. I haven't run into a browser problem with innerHTML yet, but is there a better...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: b0lsc0ttPosted on 2007-02-19 at 15:48:10ID: 18567354

Let's try to narrow down the problem.  In the alert did you have it show the responseText and see it or was it some other response?

If it is responseText then try sending it to the div from this function.  Does that work?  Instead of using responseText in the other function that is writing to innerHTML try writing a string.  For example ...

divname.innerHTML = 'This is a test string';

Does that appear?  If not, then this function is the problem and there is no problem with the AJAX script.  These steps will help us narrow down the problem.  Please show the html and script that is relevant.

As you do this remember that Javascript is case sensitive and look for Javascript errors.  Also what browser are you using?  These last tips may help you identify the problem as you work on my comment.

Let me know if you have a question or need more information.

bol

 

by: CoastalDataPosted on 2007-02-19 at 16:21:22ID: 18567516

Well I did hack it to make it work, but I'd still like to fix it... basically all I did was to replace the "return" statement with this, doing a direct assignment of the value rather than returning it to the calling function:

var subobj=document.getElementById("subcontent2");
subobj.innerHTML = (myajax.responseText);

I did that because, yes, I had done exactly as you suggested by hard-coding a string in there, so I KNEW that I was close!

Maybe that function's not returning a string, but maybe an object instead?

 

by: b0lsc0ttPosted on 2007-02-19 at 16:42:29ID: 18567590

I don't think so.  Since it works by replacing the return line with the line to write the innerHTML the responseText is just a string.  What calls the processGetPost() function?  The problem appears to be in that part of the script.  If you want to get it to work then you can provide more of the script and page.

If you want to find out the type of variable you can use ...

typeof variablename

Let me know if you have a question or need some more information.

bol

 

by: CoastalDataPosted on 2007-02-19 at 17:14:04ID: 18567687

The calling function, activated by an onClick event, uses this code:

var myContent = ajaxpack.getAjaxRequest("getHelpContent.asp", "NavID=" + nav_id, processGetPost, "txt");
alert(myContent);

The alert returns the word "undefined", but if I think if I override the return value to be a hard coded value, it does return correctly. I'll try typeof in a bit.

 

by: b0lsc0ttPosted on 2007-02-19 at 17:37:24ID: 18567733

Then were you inserting the response with something like the line below?

subobj.innerHTML = myContent;

If so then myContent may be an object.  It would depend on what ajaxpack.getAjaxRequest() function/method does and returns.  You could see with ...

alert(typeof myContent);

What information do you have about ajaxpack and the getAjaxRequest method/property?  You might have to adapt or not use this if it is meant for something else and returning something that isn't a string, etc.

Let me know the results and how I can continue to help you with this.  I'm starting to think that ajaxpack is a lot more work than it needs to be if you want to use AJAX. :)

bol

 

by: stanscott2Posted on 2007-02-19 at 19:36:44ID: 18568166

myajax.responseText only "lives" as long as the function is running.  Javascript doesn't "collapse" this to a string until the function is finished, so it disappears.

You solved the issue by setting the innerHTML inside the function, you can also do this:

var answer = myajax.responseText;  // this sets the value of the answer variable to the resulting string
return answer;  // which can then be used by another function

Stan

 

by: mplungjanPosted on 2007-02-20 at 02:13:18ID: 18569308

The a in Ajax is for ASYNCRONOUS
You cannot call an ajax function and expect the return to do anything
You EITHER call a new function with the string inside that if statement that does exactly what you did or do exactly what you did and fill the innerHTML  of something when you get a 4

 

by: mark-bPosted on 2007-02-20 at 05:10:28ID: 18569963

"The a in Ajax is for ASYNCRONOUS.  You cannot call an ajax function and expect the return to do anything"

Not true.

You CAN make an XHR request to be synchronous.  It's a parameter right on the XMLHttpRequest.open() function.

Unfortunately, the AjaxPack from dynamic drive doesn't allow you to change this parameter when the request is made.  It is hardcoded to be an async call (the one I am looking at)

Two suggestions:

1) Build and use your own XMLHttpRequest object, then use the async flag on the open method:  xhr.open( 'POST', 'http://call.to.server', false )

2) Use a more complete Ajax library that already handles this.  Although there are many, some suggestions are prototype (http://www.prototypejs.org/), or the Dojo toolkit I/O functions (http://www.dojotoolkit.org).   If your looking for simplicity, I would suggest prototype.

-Mark

 

by: mplungjanPosted on 2007-02-20 at 06:31:40ID: 18570618

I have not seen this return anything

function processGetPost(){
  if (myajax.readyState == 4){ //if request of file completed
    if (myajax.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful or running script locally
       return(myajax.responseText);
    }
  }
}

alert(processGetPost())

since the script returns immediately it is called and does not wait for the result. It is not single threaded.

Michel

 

by: CoastalDataPosted on 2007-02-20 at 07:08:38ID: 18570989

Ok, yeah, looks like this is a shortcoming of the DynamicDrive library. I think the solution to this thread lies with a split between stanscott2 and mark-b. Any objections?

 

by: mark-bPosted on 2007-02-20 at 07:13:14ID: 18571035

If you want change the ajax pack javascript (ajaxroutine.js) to support synchronous calls, just change the two methods getAjaxRequest and postAjaxRequest to:

ajaxpack.getAjaxRequest=function(url, parameters, callbackfunc, filetype, sync){
 ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
 if (ajaxpack.addrandomnumber==1) //Further defeat caching problem in IE?
  var parameters=parameters+"&ajaxcachebust="+new Date().getTime()
  if (this.ajaxobj){
   this.filetype=filetype
   this.ajaxobj.onreadystatechange=callbackfunc
   this.ajaxobj.open('GET', url+"?"+parameters, !sync)
   this.ajaxobj.send(null)
  }
}

ajaxpack.postAjaxRequest=function(url, parameters, callbackfunc, filetype, sync){
 ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
 if (this.ajaxobj){
  this.filetype=filetype
  this.ajaxobj.onreadystatechange = callbackfunc;
  this.ajaxobj.open('POST', url, !sync);
  this.ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  this.ajaxobj.setRequestHeader("Content-length", parameters.length);
  this.ajaxobj.setRequestHeader("Connection", "close");
  this.ajaxobj.send(parameters);
 }
}

Then change your ajax call to:

ajaxpack.getAjaxRequest("example.htm", "", processGetPost, "txt", true )

(I haven't tested this, but it should work)

-Mark

 

by: b0lsc0ttPosted on 2007-02-20 at 08:32:28ID: 18571752

>>I think the solution to this thread lies with a split between stanscott2 and mark-b. Any objections?
I'm a little surprised that I was left out.  I was getting information but headed to the same conclusion as the comments you plan to accept.  It would be nice to have an explanation.  It is your question and you know who helped but I was just a little surprised.

bol

 

by: mark-bPosted on 2007-02-20 at 10:15:28ID: 18572521

It doesn't matter to me who gets the points.  Split them as you see fit.

 

by: CoastalDataPosted on 2007-02-20 at 10:36:24ID: 18572685

Hey Bol, well, maybe you're right, but now I'm looking at Mark-b's post, and it looks like we might have an actual code solution, so I guess it'd be between you and him for the points. (Which was why I posted a comment, rather than actually accepting a solution).

My question still, then, is how to get the content that was returned by the ajax call... Like this?

var myResponse = ajaxpack.getAjaxRequest("example.htm", "", processGetPost, "txt", true );

 

by: mark-bPosted on 2007-02-20 at 11:27:06ID: 18573126

This should work:

  <script type="text/javascript">
  function processGetPost(){
            var myajax=ajaxpack.ajaxobj
            var myfiletype=ajaxpack.filetype
            if (myajax.readyState == 4){ //if request of file completed
               if (myajax.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful or running script locally
              if (myfiletype=="txt")
                  ajaxpack.lastResponse = myajax.responseText;
              else
                  ajaxpack.lastResponse = myajax.responseXML;
            }
      }
}

  ajaxpack.getAjaxRequest("example.htm", "", processGetPost, "txt", true);
  alert( ajaxpack.lastResponse );
 </script>

 

by: mplungjanPosted on 2007-02-20 at 13:06:00ID: 18574014

I believe you will not succeed as I already pointed out.
Treat ajax like a setTimeout

 

by: CoastalDataPosted on 2007-02-25 at 07:54:41ID: 18605266

Hello, I finally accepted two posts as an answer to my question -- mark-b posted code which comes very close to working, but ultimately, I've decided to spend some more time getting to know DoJo.

Thanks for the help and input!!!!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...