0

Im a little new to Ajax, and Ive been trying figure out what part im doing wrong. I have results being pulled from a database and thrown into xml. While im looping through the xml I'm trying execute a php file while sending it the ID number from the xml results and then return the 'echo' from the php file. Im not sure if im totally off or just missing one part, but the results come back 'undefined'.

Here is the php file that Im trying to get echoed out and show up.

echo rating_bar($id);

function rating_bar($id) {

    //other code, but $static_rater is what gets echoed

    $static_rater = "";
    $static_rater .= '<div id="ratingblock" class="ratingblock">';
    $static_rater .= '<div id="unit_long'.$id.'">';
    $static_rater .= '<ul id="unit_ul'.$id.'" class="unit-rating" style="width:'.$rating_unitwidth*$units.'px;">';
    $static_rater .= '<li class="current-rating" style="width:'.$rating_width.'px;"></li>';
    $static_rater .= '</ul>';
    $static_rater .= '<p class="static">Rating: <strong> '.$rating1.'</strong>/'.$units.' ('.$count.' '.$tense.' cast)</p>';
    $static_rater .= '</div>';
    $static_rater .= '</div>';

    //return join("\n", $static_rater);
    echo $static_rater;exit;
}

And this is the .js code that im trying to get to return the results.

downloadUrl("phpsqlajax_genxml.php", function(data) {
    var xml = data.responseXML; 
    var bounds = new google.maps.LatLngBounds();
    var markers = xml.documentElement.getElementsByTagName("marker"); 
    // alert("downloadUrl callback, length="+markers.length);

    for (var i = 0; i < markers.length; i++)  { 
        var id = markers[i].getAttribute("id");
        if (!id) id = "id "+i;
        var name = markers[i].getAttribute("name");
        if (!name) name = "name "+i;
        var address = markers[i].getAttribute("address"); 
        if (!address) address = "address";
        var citystate = markers[i].getAttribute("citystate");
        if (!citystate) citystate = "city, ST";
        var phone = markers[i].getAttribute("phone");
        if (!phone) phone = "phone number";
        var type = markers[i].getAttribute("type");
        var point = new google.maps.LatLng( 
          parseFloat(markers[i].getAttribute("lat")), 
          parseFloat(markers[i].getAttribute("lng"))); 
        bounds.extend(point);
        var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + citystate + "<br/>" + phone;  //html inside InfoWindow 
        var url = "starrating/_drawrating.php?id=" + id + "";
        //var contentString = ajaxLoad(url, parseResults, true);
        //var contentString =   downloadUrl(url, "POST", "text=" + text, completed);
        var contentString = AJAX('starrating/_drawrating.php','id='+id,
            function(data) {
                var htm = $("#ratingblock").html(data);
                alert(htm);
           }
      );

        var description = "<br><br>description" + id + " <br><b>" + name + "</b> <br/>" + address + "<br/>" + citystate + "<br/>" + phone;  //html inside InfoWindow
        var icon = customIcons[type] || {}; 
        var marker = new google.maps.Marker({ 
            map: map, 
            position: point, 
            icon: icon.icon, 
            shadow: icon.shadow,
            animation: google.maps.Animation.DROP
        }); 
        bindInfoWindow(marker, map, infoBubble, html, description, contentString); 
    } 
}); 


function AJAX(url, data, callback)
{
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.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        callback(xmlhttp.responseText);
    }
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);

}

EDIT: Ok so ive been playing around with this and updated my code above. Now when I run this using firebug I can see the post and the response is this:

<div id="ratingblock" class="ratingblock"><div id="unit_long10"><ul id="unit_ul10" class="unit-rating" style="width:150px;"><li class="current-rating" style="width:0px;"></li></ul><p class="static">Rating: <strong> 0.0</strong>/5 (0 votes cast)</p></div></div>

But the alert just says [object Object] and the infowindow says [object Object]. So i know its calling and returning the data, and ive searched and tried just about everything I can think of to get the above section to appear correctly inside the infowindow. Any thoughts?

EDIT #2

Im trying a new approach below.

var contentString = $.ajax({
                            type:"POST",
                            url: "starrating/_drawrating.php",
                            dataType: "html",
                            data:"id="+id,
                            success: function(data){
                                    var $response=$(data);
                                    $response.find('ratingblock').html();
                                    console.log($response);
                                }
                        });

The console comes back with "Object[div#ratingblock.ratingblock]" but the results still say [object Object]. Any ideas what im missing?

1
  • Why build the string in the PHP into an array, rather than just build it as a string? Commented Apr 9, 2013 at 20:44

3 Answers 3

1

The A in AJAX stands for asynchronous, meaning that the JS will not wait for the PHP data to come back. So you cannot simply assign the result of your AJAX call to a variable, you have to register a function that will be called once some data comes back. This is what your currently empty function(result) {} callback is for.

It's sort of like asking someone to fetch something, and carrying on in the meantime rather than standing frozen to the spot until they get back. The callback function, in this slightly dodgy analogy, is a note of what you intend to do when they get back.

Sign up to request clarification or add additional context in comments.

Comments

0

You're sending part of your data in the url and part in the post body, put both parts in the post body. i.e.

AJAX('starrating/_drawrating.php','id='+id,

2 Comments

I tried this and its still coming back as undefined. Perhaps im missing something in the function(result) { ?
@user1221768 just do callback(xmlhttp.responseText); without the call, and fetch the id via $_POST['id']
0

$static_rater is an array you can't use the concatenation operator with it.

$static_rater[] = "\n".'<div class="ratingblock">';
$static_rater[] = '<div id="unit_long'.$id.'">';
$static_rater[] = '<ul id="unit_ul'.$id.'" class="unit-rating" style="width:'.$rating_unitwidth*$units.'px;">';
$static_rater[] = '<li class="current-rating" style="width:'.$rating_width.'px;">Currently '.$rating2.'/'.$units.'</li>';
$static_rater[] = '</ul>';
$static_rater[] = '<p class="static">'.$id.'. Rating: <strong> '.$rating1.'</strong>/'.$units.' ('.$count.' '.$tense.' cast)</p>';
$static_rater[] = '</div>';
$static_rater[] = '</div>'."\n\n";

1 Comment

Sorry, im not sure I understand. When I run the php file on its own it displays exactly as it should. So when i run _drawrating.php?id=9 it comes back ok.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.