Paul Paul - 7 months ago 8
Javascript Question

Ajax load from php with json parse

I use a webservice to get availability of hotels, but cannot get ajax to show results of more than one. My method is definitely flawed & slow - how better to do?

1) Code (simplified) called for EACH hotel in a page listing 6-12 hotels:-

<script>
$(document).ready(function(){
$("#div<%=i%>").load("hotel-avail.php?id=xxyy");
});
</script>


2) hotel-avail.php?id=xxyy uses a webservice to get a PHP array, $result, defining availability of the hotel with id xxyy. Content of the html section:-

<script>
var result = JSON.parse( '<?php echo json_encode($result) ?>' );
if (result.hotels.estado == 'OK') {
document.getElementById("demo").innerHTML = "Yes";
} else {
document.getElementById("demo").innerHTML = "No";
}
</script>

Availability: <span id="demo"></span>


So this method injects data twice into 2 divs, one in each file. Apart from looking bad, and NOT working, it must be the slowest way to iterate through 6-12 hotels. Help please!

Answer

Use this code as reference, If I am missing the point, let me know

 $.ajax({
    url: 'hotel-avail.php?id=xxyy',
    method: 'post',
    dataType: 'json',
    success: function (result) {

        if (result.hotels.estado == 'OK') {
            document.getElementById("demo").innerHTML = "Yes";
        } else {
            document.getElementById("demo").innerHTML = "No";
        }
    }
});

This ajax only works with jQuery. forgot to point that out. also you can change this code:

document.getElementById("demo").innerHTML = "Yes";

for

$("#demo").html("Yes");
Comments