new to ajax.

not that good at javascript.

I have the following code which uses ajax to get data from a mysql database with php

once I call the ajax function to get the data....I want to use the data in the main script but I have not been able to show the data with the document.write statement.

you will see where I have been testing that the data is being returned from the php script and yes it is...

I thought that the lines variable would contain the data I want.

when I document.write(allText) It says it is undefined...variable lines would be a split of that.

Eventually I want to be able to get the data every 5 seconds from the data base and display on a google map.

Thanks for your help.....an example would be most welcome.

<html>
<head>
<script type="text/javascript">
 
function getflights(str)
{
test = "test inside the function";
 
document.write("im in the function<br>");
 
//if (str=="")
//  {
//  document.getElementById("txtHint").innerHTML="";
//  return;
//  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
 
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    //document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
 
allText = xmlhttp.responseText; 
lines = xmlhttp.responseText.split("<br>"); // Will separate each line into an array 
 
 
//document.write(xmlhttp.responseText);
//document.write(allText);
//document.write(lines[0]);
//document.write(lines[1]);
//document.write(lines[2]);
//return allText;
    }
 
  }
xmlhttp.open("GET","getadsbplanes.php?q="+str,true);
xmlhttp.send();
 
 
 
}
 
</script>
 
//==============================================================
<body>
<script type="text/javascript">
var string1;
var test;
//var allText;
//allText = "mmmm";
 
string1 = "ADSB Planes updated every 5 seconds"; 
test = "test outside function";
document.write(string1+"<br>");
 
lines = new Array(20);
 
 
//function start()
//{
//setInterval ( "showuser()", 5000 );
//}
 
 
document.write("call function <br>");
getflights();
 
document.write("show data = ");
  
document.write(test);
 
document.write(allText);
 
</script>
</body>
</head>
</html>

Do you know JQuery? It's much more easier to work with AJAX, or manipulate DOM elements as you wish.

This is a simple test page using JQuery post mehtod, but there are many more with much more flexibility, if you need.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">  

$(function() // OnLoad
{
	$.post( // Jquery post method
		"myurl.php" // url
		{
			parameter1: "myParameter",
			parameter2: "myParameter"
		},
		function(data) // On Success
		{
			$("#myDIV") // get myDiv object
				.html(data); // set its html content
		},
		function(error) // On Error
		{
			alert("AJAX Error: " + error);
		}
	);
});
		
		
    </script>        
</head>

<body>
    <div id="myDIV"></div>
</body>
</html>

Learn more at http://jquery.com/

If you can't use JQuery, say it and I'll go trough your code.

thanks for the reply.

I do not know jQuery.

Looking at your code I believe it passing the html code to the div.

I have done the exact same thing with AJAX. It shows on a web page nicely.

However I need to manipulate the data that is returned from the AJAX so I can do more with it. My problem is that I can not seem to find the correct way to pass the php script response via Ajax into a variable so I can work on it.

Now maybe jQuery can do this easier.

What kind of data are you returning from the php page? Post a example.

What kind of data are you returning from the php page? Post a example.

The data returned from the php script is coming from a mysql database so it can be of my choosing...could be a file, could be an html table...I have full control of what the php gives me.

Save as test.html

<html>
<head>
<script src="javascript/jquery-1.7.min.js" type="text/javascript"></script>
<style>
.restart, .stop, .clear
	{
	font-size: 20px;
	margin-right: 20px;
	}
.container
	{
	position: relative; border: 1px black solid; width: 500px; height: 300px;
	}
.code
	{
	margin-top: 30px; position: relative; border: 1px black solid; width: 800px; height: 200px;
	}
</style>



<script>
window.onload = function()
	{
	t = setInterval("ajax('/test2.php', 'xhr=blahblah', 'GET', 'script', 10000, true)", $('.intsec').val() * 1000);
	};
function timeout()
	{
	alert("Operations has timed out.  \n\nPlease try again.");
	}
function success(data, textStatus, XMLHttpRequest)
	{
	console.log(data + textStatus + "   " + XMLHttpRequest);
//	console.log(JSON.stringify(data));
	$('.code').html(data);
	return false;
	}
function catch_error(jqXHR, textStatus, errorThrown)
	{
	if(textStatus == 'timeout') timeout();
	console.log(jqXHR);
	console.log(errorThrown);
	console.log(textStatus);
//	console.log(JSON.stringify(jqXHR));
	return false;
	}
function ajax(url, data, type, dataType, timeout, async)
	{
	$.ajax({
		  dataType: dataType,
		  type: type,
		  url: url,
		  data: data,
		  async: async,
		  timeout: timeout,
		  success: success,
		  error: catch_error
		});
	return false;
	}
$('.restart').live('click', function()
	{
	t = setInterval("ajax('/test2.php', 'xhr=blahblah', 'GET', 'script', 10000, true)", $('.intsec').val() * 1000);
	$(this).removeClass('restart').addClass('stop').text('Stop');
	});
$('.stop').live('click', function()
	{
	clearInterval(t);
	$(this).removeClass('stop').addClass('restart').text('Re-Start');
	});
$('.clear').live('click', function()
	{
	$('.container').empty();
	});
$('.intsec').live('change', function()
	{
	if($('.stop').length)
		{
		clearInterval(t);
		t = setInterval("ajax('/test2.php', 'xhr=blahblah', 'GET', 'script', 10000, true)", $('.intsec').val() * 1000);
		}
	});
</script>
</head>
<body>
<a class='stop' href='#'>Stop</a>
<a class='clear' href='#'>Clear Box</a>
Interval in seconds: <input class='intsec' value='5' />
<div class='container'></div>
<textarea class='code'></div>

</body>
</html>

Save as test2.php

<?php
$top = mt_rand(0,290);
$left = mt_rand(0,490);
$hue = mt_rand(0,100);
$sat = mt_rand(0,100).'%';
$light = mt_rand(0,100).'%';
$class = $top . $left;
$background = "hsl($hue, $sat, $light)";
$code  = "$('.$class').remove();";
$code .= "\n$('.container').append(\"<div class='$class' style='position: absolute; top:$top; left:$left; width: 10px; height: 10px; background-color: $background;'></div>\");";
echo $code;
$code = str_replace('$', '\$', $code);

?>

This may help you with getting started with jquery.

It will allow you to send jQuery/Javascript code back to the browser for processing. This will allow you to control more of the functionality on the server side.

There is an interval timer that starts on window.onload. It will receive the default value of 5 seconds from the initial page.

If you decide to return data in a different format ie., json, xml, html, etc. Google jquery ajax and visit the jquery site for additional information on ajax.

As you can see, jquery ajax is very concise. However, there are different options that you may want to play around with.

You will also need to download the jquery framework.

The console.log statements will display the results of the call in your browser's console log. Comment out some or all of these statements when you do not need them.

test.html: Browser side (requesting)
test2.php: Server side (sending)

trying your jquery code I do not get the expected results.

can you show me where you manipulate the data returned from the php script?

Hi,

In my script, I'm not manipulating data in the browser. I'm only manipulating the DOM.

I'm using PHP to create a "result" and sending "jQuery" commmands back to the browser via Ajax. jQuery then runs the commands in "$code" to place the the colored boxes in the box.

As i stated, there are other options on the jQuery site if you would rather manipulate the data server side. If this is the case, you may want to explore the "JSON" dataType. My example uses the "script" dataType so I can do the majority of the work on the server and then just manipulate the DOM afterwards

in any event your code does not appear to work. perhaps you could post a description of what is suppose to happen.


I am NOT that versed on what DOM is. Looking back at my original post I still have not seen an example of manipulating what is sent back from the PHP script.

Can you show me an example of manipulating the "data" returned by the php script in AJAX...or using jquery? That is what I need. I need the javascript on the client side to manipulate what it gets back from the AJAX.

ok :)

declare allText outside the function.

declare allText outside the function.

Declaring allText outside the function does not let the "value" to come back to the main javascript.

If I assign a string to allText....it is passed to the main javascript.

There is soemthing unique about the "data" passed back by the php script and assigned to allText.....BUT what?

If I do a document.write of the allText variable inside the function it gives me the data....but the whole script dies.

Throwing out these test results so someone may be able to pick up on what is going on.

Further thought!!

The reason the allText value is undefined is because the onreadystate function has not had time to assign a value before the stream goes back to the main script.

does that make sense?

If that is the case then a delay required while the data is assigned. How could I do that?

further testing ------ I finally got the data back to the main script by putting a 15 second delay in the "getflights" function.

Now this shows that it can be done.....this is gonna be far too slow....

Any suggestions?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.