H Emad
H Emad

Reputation: 327

mixing Ajax with Javascript

I foundout that I cant mix php with javascript so I ttried AJAX. in the code below I want the ajax function to get a value from getcount.php page and return it to the caller function. the code below doesnt work. where is the mistake?

<script type="text/javascript">
function getcount(day)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.open("GET","getcount.php?"+day,true);
xmlhttp.send();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    return xmlhttp.responseText;   
    }
}
 </script>

<script type="text/javascript">
$(function () {
var previousPoint;

var d1 = [];
 for (var i = 0; i <= 10; i += 1)
         d1.push([i, getcount(i)]);
  .
  .
  .

Upvotes: -1

Views: 612

Answers (4)

kmfk
kmfk

Reputation: 3961

Mixing any type of Ajax query with a loop of this nature is not a great idea. It will create some interesting race conditions as the Ajax request is asynchronous - as already mentioned.

It would be better to do a single ajax request and handle the loop in php - then return a single array. However, again, its important you need to understand by default, the rest of your procedural javascript code will not wait for the Ajax method to return.

See the docs for help

Upvotes: 1

Tuhin Subhra Dey
Tuhin Subhra Dey

Reputation: 980

Try using Jquery ajax which is very easier for maintenance and debugging. Here is a sample 
ajax code

$.ajax({
 type: 'POST',  // can be get also
 url: 'yourpage.php',  // change name
 data: id,  // some data if u need to pass
 success: function(data) {  // returns date
       $('.result').html(data); // result 
 }
}); 

For details  http://api.jquery.com/jQuery.ajax/

Thanks.

Upvotes: 0

shyam
shyam

Reputation: 9368

The ajax callback will be asynchronous so, getcount() will return undefined and when the callback returns it is not assigned to anything

function getcount(day, arr) {
var xmlhttp;
...
xmlhttp.send();

xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    arr.push([day, xmlhttp.responseText]);   
    }
}
$(function () {
var previousPoint;

var d1 = [];
 for (var i = 0; i <= 10; i += 1)
     getcount(i, d1);
...

Upvotes: 3

Tronix117
Tronix117

Reputation: 1985

Use jQuery, it will be far easier:

<script type="text/javascript">
  $(function () {
  var previousPoint, d1 = [];

  var getCount = function(day){
    $.get("getcount.php?"+day, function(data){
      d1.push([day, data]);
    });
  }

  for (var i = 0; i <= 10; i += 1)
    getcount(i)
});
</script>

Upvotes: 1

Related Questions