Nita
Nita

Reputation: 561

PHP MySQL JS AJAX - Loop issue

I have PHP loop. I take the id, lat, lon data from record, passed it to script to do some calculations, then I passed this data to AJAX which will save the results of that calculation in MySQL DB, if it's successful then it will add the line of confirmation text to a results div.

My Code (I did trim it to keep focus on the issue)

<div id="distance_results"></div>

<?php
        $result = $mysqli->query("SELECT * FROM test")
        while($row = $result->fetch_array()) {
        $id = $row['id'];   
        $city = $row['city'];   
        $lat = $row['lat'];
        $lon = $row['lon'];
        $driving_from = "51.528308,-0.3817765";
        $driving_to = "$lat,$lon";
?>
<script>
    var id = '<?php echo $id ?>';
    var city = '<?php echo $city ?>';
    var start = '<?php echo $driving_from ?>';
    var end = '<?php echo $driving_to ?>';

   // code
    directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
    // code
    var mi = response.routes[0].legs[0].distance.value;

            console.log(id);
            console.log(city);
            console.log(mi);

//Ajax Begin
            $.ajax({
            type: 'post',
            url: 'test-dc-upd.php',
            data: {'updateid': id, 'distance': mi},
            success: function() { 

            html="Distance between London and " + city  + " is " + mi;
            $("#distance_results").append("<p>"+html+"</p>");

                }
            });
 //Ajax End

} else {}

});  


</script>


<?php } ?>

AND CODE FOR "test-dc-upd.php"

$id = $_POST['updateid'];
$distance = $_POST['distance'];
$result = $mysqli->query("UPDATE test SET distance='$distance' WHERE id='$id' LIMIT 1");

So PHP is looping thru MySQL DB, when but when I look at console:

'mi' values are calculated well according to lat / lon;

PROBLEMS:

1) 'id' and 'city' values stay the same (values of last record in the loop);

2) AJAX is updating value of last record in the loop only

So it obvious there is a some issue with the loop.

Any suggestion to what i do wrong?

Upvotes: 0

Views: 146

Answers (4)

Nita
Nita

Reputation: 561

I manage to do it a little different way i was hoping for ( But distance and travel time has been calculate for more then 3000 locations).

So what i did is to make sure mysql (test-dc.php) finds record where distance and travel time has not been calculated, makes calculation, update record with Ajax. Ajax on succesion opens the (test-dc.php) again, And is looping thru all results till there is nothing else to calculate. Had to refesh few times but thats fine, job done.

Adjustment to Mysql query:

$result = $mysqli->query("SELECT * FROM test WHERE distance='' LIMIT 1")

and to AJAX:

success: function() { 
   html="Distance between London and " + city  + " is " + mi;
   $("#distance_results").append("<p>"+html+"</p>");
   location.href = "test-dc.php"
}

So that did the trick, but i still belive there is a better way of achiving the same result, i will be happy if someone could help me to figure it out.

Upvotes: 0

anuraj
anuraj

Reputation: 157

In a loop calling ajax request is not a good practice we can easily pass array of values to javascript using the function implode like this

this implode function is for single dimensional array,

 var ar = <?php echo '["' . implode('", "', $ar) . '"]' ?>;

For your question you need to create a multi dimensional array for the result like this ..

<?php
    $result = $mysqli->query("SELECT * FROM test");
    $arr= array();
    while($row = $result->fetch_array()) {
   $arr[]=array('id'=>$row['id'],'city'=>$row['city],'lat'=>$row['lat']...etc);
}
  ?>

afetr that you can pass each item in the array to javascript like this

var idArray= <?php echo '["' . implode(', ', array_column($arr, 'id')); . '"]' ?>;
   var cityArray= <?php echo '["' . implode(', ', array_column($arr, 'city')); . '"]' ?>;

you can get each tag as array in javascript after that using a sing ajax request pass all javascript array to php script. and manipulate in the server side .

Your ajax request is like this

 $.ajax({
        type: 'post',
        url: 'test-dc-upd.php',
        data: {
          'idArray':idArray,
          'cityArray':cityArray, //etc you need pass all array like this 
        },
        success: function(data) { 

            // your success code goes here

            }
        });

Note that array_column() function only supported by php 5.3 or above

Upvotes: 0

user2047029
user2047029

Reputation:

Change this $("<p>"+ html +"</p>").append("#distance_results"); To

$("#distance_results").append("<p>"+ html +"</p>");

Your jquery code is wrong. First you have to put selector and in append function the html code.

Upvotes: 1

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

Nita, change the success function from:

success: function() { 

    html="Distance between CITYX and " + city  + " is " + mi;
    $("<p>"+ html +"</p>").append("#distance_results");  

    }
});

To

success: function() {
        html="Distance between CITYX and " + city  + " is " + mi;
        $("#distance_results").append(<p>"+ html +"</p>);
        // this will append the dynamic content to #distance_results
    }
});

Explanation:

To put a dynamic content is some html object you have to first prepare the content than select the html object and put the content into it.

Upvotes: 0

Related Questions