Jump to content

AJAX return to JS variable - Undefined


Muddy_Funster

Recommended Posts

hi guys.  Having a spot of bother getting my head around this (mainly because I know pretty much bugger all about JS) But I'm trying to take an AJAX xmlResponseText and pass it out to a cariable in the JS.  I know tha tthe async nature of AJAX makes this not as strait forward as I would like, and I have been hacking at this bit of code for a while now.  I just want to be able to call the response text as a string variable for a bit of JS in the page body to apply some styling to.

 

here's the mess I have just now:

  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!");
      }
    }
  }
function getData(){
    xmlHttp.open("GET", "data.php", true);
    xmlHttp.send(null);
    xmlHttp.onreadystatechange = function(){
      if(xmlHttp.readyState == 4){
      dateOut = xmlHttp.responseText;
       success: function writeOut(dataOut){
        return dataOut;
       };
      }
    };
  };

 

and am trying to call it with

myVar = getData();
...
...
document.getElementByID("dispDiv").innerHTML = myVar;

All I get to display is "Undefined" so I'm clearly screwing this up somewhere along the line, and I just know it's a stupid simple little mistake but I need someone to point it out for me.

 

Link to comment
Share on other sites

what does writeOut do?

this is what I'm thinking, you can tinker with it to suit your code:

 

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!");
      }
    }
  }
xmlHttp.onreadystatechange = function(){
     if(xmlHttp.readyState == 4){
         dataOut = xmlHttp.responseText;
         var ajaxDisplay = document.getElementById("dispDiv");
         ajaxDisplay.innerHTML = dataOut;
     }
};
xmlHttp.open("GET", "data.php", true);
xmlHttp.send(null);
   

 

Of course, I always recommend you use jquery's AJAX API..  :P

Link to comment
Share on other sites

I don't think I even have jQuery (unless it's built into something else and I didn't know it).  I was using the writeOut in an atempt to force the execution of the AJAX at the right time (so that the results of the AJAX lookup would be there for the population of the innerHTML when the JS was trying to write it.

 

The problem is I want the output from the data.php to be run through a cut&paste horizonatal scrolling ticker.  the code is this:

<html>
<head>
<title>News Scroller Horizontal v2.2</title>

<!-- STEP I: Goes between <HEAD> & </HEAD> tags 
             You may keep it, change or ignore it!
             Or linking to an External Style Sheet:
         <LINK REL=StyleSheet HREF="yourstyle.css"> 
             without other style tags -->

<style type="text/css">
A { text-decoration:none;}
A:link	{color:blue;}
A:visited{color: blue;}
A:hover	{color: red;background-color:#66ffff;}
.tab {font-size:12px;font-family:Arial,Helvetica;color:navy;}
.tabb {font-size:14px; font-family:Arial,Helvetica;}
</style>

<!-- STEP II: Goes between <HEAD> & </HEAD> tags
              Or linking to an External js file:
<script language="javascript" src="yourfile.js"></script>
              without other script tags -->

<SCRIPT LANGUAGE="JavaScript">

/***********************************
*   http://javascripts.vbarsan.com/
*   This notice may not be removed 
***********************************/

//-- Begin Scroller's Parameters and message -->
//scroller width: change to your own;
var wwidth=450;

//scroller height: change to your own;
var wheight=20;

//background color: change to your own; 
var wbcolor="#ccffcc";

//scroller's speed: change to your own;
var sspeed=2;
var restart=sspeed;
var rspeed=sspeed;

//text: change to your own

wwholemessage='<nobr class=tab><b>News Scroller Horizontal v2.2 => '+
'<a class=tabb href="http://javascripts.vbarsan.com">'+
'Vertical Scroller JavaScript 7.0 + Horizontal Scroller JavaScript 7.0 + Typewriter Scroller JavaScript 5.0</a> <= Text Scroller Horizontal v2.2</b></nobr>';

//Or you may do a slide show running left any number of images too!
//Preload is recommended (no downloading check) - otherwise you may skip this:
//preload1 = new Image();
//preload1.src = "http://...";
//preload2 = new Image();
//preload2.src = "http://...";
//preload3 = new Image();
//preload3.src = "http://...";
// ...

//if no preloading, replace below '+ preload... +' with the actual Images path "..."

//wwholemessage='<nobr><img src='+preload1.src+' width=... height=... alt="...">'+
//'<img src='+preload2.src+' width=... height=... alt="...">'+
//'<img src='+preload3.src+' width=... height=... alt="...">'+
//'<img  ... ></nobr>';

//-- end Parameters and message-->

//-- begin: Scroller's Algorithm -->
var sizeupw=0;var operbr=navigator.userAgent.toLowerCase().indexOf('opera');if(operbr==-1&&navigator.product&&navigator.product=="Gecko"){var agt = navigator.userAgent.toLowerCase();var rvStart = agt.indexOf('rv:');var rvEnd = agt.indexOf(')', rvStart);var check15 = agt.substring(rvStart+3, rvEnd);if(parseFloat(check15)>=1. operbr=0;}if (navigator.appVersion.indexOf("Mac")!=-1)operbr=0;
function goup(){if(sspeed!=rspeed*{sspeed=sspeed*2;restart=sspeed;}}
function godown(){if(sspeed>rspeed){sspeed=sspeed/2;restart=sspeed;}}
function startw(){if(document.getElementById)ns6marqueew(document.getElementById('wslider'));else if(document.all) iemarqueew(wslider);else if(document.layers)ns4marqueew(document.wslider1.document.wslider2);}function iemarqueew(whichdiv){iedivw=eval(whichdiv);iedivw.style.pixelLeft=wwidth+"px";iedivw.innerHTML='<nobr>'+wwholemessage+'</nobr>';sizeupw=iedivw.offsetWidth;ieslidew();}function ieslidew(){if(iedivw.style.pixelLeft>=sizeupw*(-1)){iedivw.style.pixelLeft-=sspeed+"px";setTimeout("ieslidew()",100);}else{iedivw.style.pixelLeft=wwidth+"px";ieslidew();}}function ns4marqueew(whichlayer){ns4layerw=eval(whichlayer);ns4layerw.left=wwidth;ns4layerw.document.write('<nobr>'+wwholemessage+'</nobr>');ns4layerw.document.close();sizeupw=ns4layerw.document.width;ns4slidew();}function ns4slidew(){if(ns4layerw.left>=sizeupw*(-1)){ns4layerw.left-=sspeed;setTimeout("ns4slidew()",100);}else{ns4layerw.left=wwidth;ns4slidew();}}function ns6marqueew(whichdiv){ns6divw=eval(whichdiv);ns6divw.style.left=wwidth+"px";ns6divw.innerHTML='<nobr>'+wwholemessage+'</nobr>';sizeupw=ns6divw.offsetWidth;if(operbr!=-1){document.getElementById('operaslider').innerHTML='<nobr>'+wwholemessage+'</nobr>';sizeupw=document.getElementById('operaslider').offsetWidth;}ns6slidew();}function ns6slidew(){if(parseInt(ns6divw.style.left)>=sizeupw*(-1)){ns6divw.style.left=parseInt(ns6divw.style.left)-sspeed+"px";setTimeout("ns6slidew()",100);}else{ns6divw.style.left=wwidth+"px";ns6slidew();}}
//-- end Algorithm -->
</script>
<!-- End of Script between <head> & </head> tags-->
</head>

<!-- STEP III: Make sure startw() is loaded.
If you have in your page multiple "onload" events, place them
all using one onload event handler within BODY TAG, like this: 
onload="Funct1(); Funct2(); ...;" 
Or use this:
function alltostart() { 
  funct1();
  funct2();
          ...
} 
window.onload = alltostart;
-->
<body onload="startw();">

<!-- STEP IV: Goes between <BODY ... > & </BODY> tags
              begin: body code  -->

<!-- You may remove first cell below (<td> ... </td>) to get rid of Speed-change -->
<script language="JavaScript">document.write('<table align="center" border="2"><tr><td bgcolor="#ffffcc"><div class=tabc><b><u><a class=tabb href="#" onMouseOver="goup();">UP </a></u>-<u><a href="#" class=tabb onMouseOver="godown();"> DN</a></u></b></div></td><td width='+wwidth+'px>');if(document.getElementById || document.all){document.write('<span style="width:'+wwidth+'px;"><div style="position:relative;overflow:hidden;width:'+wwidth+'px;height:'+wheight+'px;clip:rect(0 '+wwidth+'px '+wheight+'px 0);background-color:'+wbcolor+';" onMouseover="sspeed=0;" onMouseout="sspeed=restart">');if(operbr!=-1)document.write('<div id="operaslider" style="position:absolute;visibility:hidden;"></div>');document.write('<div id="wslider" style="position:absolute;height:'+wheight+'px;"></div></div></span>')}</script>
<ilayer width=&{wwidth}; height=&{wheight}; name="wslider1" bgcolor=&{wbcolor};><layer name="wslider2" width=&{wwidth}; height=&{wheight}; onMouseover="sspeed=0;" onMouseout="sspeed=restart"></layer></ilayer></td></tr></table>
<!-- end  of code between BODY TAGS -->

</body></html>

 

as you can see the wwholemessage variable is being hard set at the moment, and I need it to come from a db table using the data.php to load it.  I'm really not having fun with this any more :(

Link to comment
Share on other sites

well, the code I posted is the "proper" way to handle an ajax request.

var dataOut is set to the ajax response string, so you can use that variable in whatever way you want, be it function calls etc.

Which really brings us full circle, you can do something like what you were in the OP, minus the success: param, which doesn't exist inside of a normal function.

 

Link to comment
Share on other sites

right, so effectivly i need to push the data out of the AJAX function rather than pulling in from the JS one?  So I need to edit the JS to accept the innerHTML push from the AJAX in the div constructor rather than passing the data to the string variable as I was trying to do?

 

Or am I as confused as I feel right now?  :confused: lol

 

Link to comment
Share on other sites

Well I wish I could help further, but Im having trouble wrapping my head around what it is exactly that you are trying to do.

The code I provided sets var dataOut to the Ajax response string. You can do whatever you want with this string.

So I'm not really sure why you are having further issues.

Link to comment
Share on other sites

I hear ya AyKay, I suck at explaining things at the best of times, when they confuse me it just gets worse and I end up not making sense most of the time.  I have that "ticker" script that I posted erlier, I want to populate it with a database result set generated as an unordered list on data.php from my db backend, rather than the hard set string variable that the "ticker" script comes with.  I tried renaming divs, and assigning variables but it's just not making enough sense, so I'm on page 149 of my nice crisp book on JS and things are slowly starting to come together...

Link to comment
Share on other sites

Muddy_Funster,

 

    Yeah, but...  Don't discount jQuery... Get it here: http://jquery.com/

 

    Then you can turn off / on async functionallity... on: don't wait, off (false) wait...

 

    Plus, jQuery takes complex tasks and makes them easy...

 

    The following is a sub-set of my own ajax processing scheme...

 

1.) ajax call:

 

   


    <script type="text/javascript">

 //                      #DMGPOWNER is the id of the select box 
 var DMGPOWNER = jQuery('#DMGPOWNER option:selected').text(); 

 DMGPOWNER = strtoupper(DMGPOWNER);

 var ClaimantDriver = AJAXTrafficCop('ClaimantDriverYN', DMGPOWNER);

 var validAJAXResult = checkAJAXResults(ClaimantDriver);  

 var debug = false;

 if (debug) {
 	 alert('ClaimantDriver Ajax Return: ' + "'" + ClaimantDriver + "'");
 }

 if (validAJAXResult) {

 	var propertyType = document.getElementById('DMGPTYPE').selectedIndex;

 	if (propertyType === 1 || propertyType == 2) { // Vehicle OR Other

 		ClaimantDriver = Boolean(ClaimantDriver);
 		            
		if (ClaimantDriver) { // As determined by ajaxTrafficCop.js / .php

	        // alert('Setting up Claimant Driver');

		    $("#VehicleInfo").show(); 	
		    $("#ClaimantVehicleType").show();
		    $("#InsuredVehicleType").hide();
		    
		} // END if (ClaimantDriver) { 

 	} // END if (propertyType === 1 || propertyType == 2) { // Vehicle OR Other

 } // END if (validAJAXResult) {


/**
 *
 *	Make sure	 PHP ('AJAXTrafficCop.php') 
 *		
 *		and 
 *
 *				JavaScript ('AJAXTrafficCop.js') played nice...
 *
 */

function checkAJAXResults(valueToCheck) {

	var returningValueToCheck = valueToCheck;

	suppliedJSParmsAreInvalid = stristr(returningValueToCheck, 'invalid'); // See around line 89 in 
												    			  	       // 'AJAXTrafficCop.js'
												    
	if (suppliedJSParmsAreInvalid) {

		errorText = returningValueToCheck;

		alert(errorText);

		return false;

	}

	suppliedPHPParmsAreMissing = stristr(returningValueToCheck, 'missing'); // See around line 104 in 
												    				        // 'AJAXTrafficCop.php'
												    
	suppliedPHPParmsAreInvalid = stristr(returningValueToCheck, 'invalid'); // See around line 109 in 
												    			            // 'AJAXTrafficCop.php'														

	if ( (suppliedPHPParmsAreMissing) || (suppliedPHPParmsAreInvalid) ) {

		pieces = explode('|', returningValueToCheck);

		line1  = pieces[0];
		line2  = pieces[1];

		errorMessage = line1 +  line2;

		alert(errorMessage);

		return false;

	}

	return true;

} // END function checkAJAXResults(valueToCheck) {


    </script>

    

 

2.) AJAXTrafficCop.js

 

 


    
function AJAXTrafficCop(jurisdiction, citation) { 

	if ( typeof(citation) != 'undefined') {
		var directive = null;	
	}

	var trafficCop = jurisdiction;

	var directive  = citation;

	var complexID = stristr(trafficCop, '_'); // Multiple ID's for the same task

	var debug = false;

	if (debug) {

		alert('trafficCop : ' + trafficCop);
		alert('directive : ' + directive);
		alert('complexID : ' + complexID);



	}			

	if (complexID) { // Detective work needed
				pieces = explode('_', trafficCop);

		trafficCop 	   = pieces[1]; // 'Complete'

		// alert('TrafficCop : ' + trafficCop);

		complexSubject = pieces[0]; // 'BasicInfo'

		// alert('ComplexSubject : ' + complexSubject);

	}

	debug = false;

	if (debug) { // One...

		// Or the other : 

	    // if ( (debug) || (complexID == 'INSVEHZIP') ) {

		alert('trafficCop : ' + trafficCop);
		alert('complexSubject : ' + complexSubject);

	}


	var asyncParmBoolean = false; // Do you want the callling JS to wait for the AJAX to complete ?
								                                                            // "asyncParmBoolean = false" means to process the request 
				 // asyncronously - ie.: wait for AJAX to complete first...

	var returnAJAXResult = false;  // Do you want to "see" (read use) any output from AJAX ?
				 // Even if you produce output, you may not want to intercept...

	switch(trafficCop) { 


		case 'ClaimantDriverYN' : // Called From  checkTrio() in 'Header' segment of	                                                                  // 'AutoDamgProp.phw' around line 668.
								  
			var asyncParmBoolean = false;
			var returnAJAXResult = true;

			// Directive: 'Property Owners Name'.

			directive = strtoupper(directive);

			var dataParm = "ClaimantDriverYN=" + directive;	

			var debug = true;

			if (debug) {
				alert(dataParm);
			}

		break;

		default :

			alert('A switch error occurred in \'AJAXTrafficCop.js\' while trying to process \'' + trafficCop + '\' for: \'' + directive + '\'.\n\n\tOne or more of the expected parm values are invalid.\n\n \n (Or : \'ajaxTrafficCop.php\' has a syntax error which prevented it from processing a valid JS request...) \n \n\tThe data generated for this page cannot be trusted !\n\nPlease report this message to the IT Helpdesk !');
			return;

		break;

	}

	$.ajax({

	    type: "GET",
	    url: "/common/include/ajaxTrafficCop.php",
	    data: dataParm,
	    async: asyncParmBoolean,
	    success: function(msg) {
	    	
	    	/**
	    	 *
	    	 *	Handle programmer error...
	    	 *
	    	 */
	    					    	
		    if (stristr(msg, 'ajaxTrafficCop.php')) {
     			alert( msg );
     			return;
	     	}
	     	else { // Maybe user wants to see the results of the AJAX Call...
	     		
	     		var render = returnAJAXResult; // If true, and you get back a null msg, check                                                                                        // trafficCop.php for $display = false or
	     					  // make sure the item of interest is echo'ing
	     					  // somthing...

	     		if (render) {
	     			
	     			debug = false;
	     			
	     			if (debug) {

	     				//   Change this bad boy to something of interest...

		     			if (trafficCop == 'DOMToCheckZipFor') {
		     				alert(msg);	
		     			}
		     			
		     		}
		     			
	     			result = msg;
	     		}

	      	}

	    } // END success: function(msg) {
	   
	}); // END $.ajax({

	if (returnAJAXResult) {

		if ( typeof(result) != 'undefined') {

			return result;  // Generally used when a JS call to AJAX needs the results of the
				      // call at a later time.  ( Also needs 'asyncParmBoolean = false;' )

		}
		else {

			// We don't return a value, because this message should only be generated
			// when we were expecting 'AJAXTrafficCop.php' to return some value(s), but didn't.

			alert('An error occurred in \'AJAXTrafficCop.js\' while trying to process \'' + trafficCop + '\' for: \'' + directive + '\'.\n\n\tThe expected return value was not genrated in \'AJAXTrafficCop.php\'\n\n(Or : there is a syntax error in \'AJAXTrafficCop.php\' which prevented valid JS parms to be processed.)\n\n\tThe generated data on this page cannot be trusted !\n\nPlease report this message to the IT Helpdesk !');

		}

	} // END if (returnAJAXResult) {

} // END function AJAXTrafficCop(id, status) {  


 

3.) ajaxTrafficCop.php

 


<?php

// Set no caching

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: no-store, no-cache, must-revalidate"); 
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

set_time_limit(0);

session_start();


$debug = false;		

if ($debug) {		

	error_reporting(E_ALL);	

	ini_set('display_errors', 'on');	

}

$incomingGetParm = $_GET;

$debug = FALSE;

if ($debug) {

	$parm = $incomingGetParm;

	echo "<pre><h3 style=\"color: red;\"> \n";
		var_dump($parm);
	echo "</pre></h3> \n";

}


foreach ($incomingGetParm as $getIDX => $gottenItem) {

	$switchCriteria = $getIDX;
	$getParmValue   = $gottenItem;

}


$debug = FALSE;

if ($debug) {

	if ($switchCriteria == 'ownedNonowned') { // Change as needed for debug processing...

  	 	echo "Debug report from ajaxTrafficCop.php with built-in exit. /* --> \$switchCriteria  --> " . $switchCriteria . "<-- :: \$getParmValue  --> " . $getParmValue . " <-- */ \n";
  	 	exit;
  		
  	}

}

//	echo " !!! \$switchCriteria : $switchCriteria !!! \n";

   	switch($switchCriteria) {

	case 'ClaimantDriverYN' : // Called from around line 668 in the "Header" segment of
							  // 'AutoDmgProp.phw'

		/**
		 *
		 *	In AutoDmgProp.php, we have to determine whether or not we are dealing
		 *	
		 *	with an 'Insured Driver' or a 'Claimant Driver' to decide whether or
		 *
		 *	not to allow "Same As Owner's" check-box.
		 *
		 */

		$nameToCheck = strtoupper($getParmValue);

		$claimantDriver = stristr($nameToCheck, 'CLAIMANT DRIVER');

		if ($claimantDriver) {
			echo true;
		}
		else {
			echo false;	
		}

	break;  

  		default :

  			if ( ($switchCriteria == null) || ($switchCriteria == '') || (!isset($switchCriteria)) ) {
  				
  				$switchCriteria = '!! MISSING !!';
  				$missingCriteria = true;
  				
  			}
  		
  		
  		if ($missingCriteria) {
  			
  			echo " AJAX \$switchCriteria parm (\"$switchCriteria\") missing in program: 'ajaxTrafficCop.php'. \n \n";
  			
  		}
  		else {
  		
  			echo " AJAX \$switchCriteria parm (\"$switchCriteria\") is invalid in program: 'ajaxTrafficCop.php'. \n \n";
  		
  		}
  			
 		echo "(Check the parms passed to AJAXTrafficCop JS and the switch setting in same.) \n\n";
  			
  			echo "  Please report this message to the IT Help Desk... ";
  			
  			echo "\n";
  			
  	 
  			
  		break;
  		
  		
  	} // switch($switchCriteria) {

?>

 

 

Scot L. Diddle, Richmond VA

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.