Ajax / Jquery - 使用ajax从服务器/并行SQL查询执行返回数据时调用javascript函数

问题描述:

I have a PHP array of values. I loop through it, make ajax calls to the server by iterating through a for loop (I totally understand that making ajax cals in a for loop is not a great idea. Any suggestions/pointers to doing this a bette way would be awesome no doubt. I'd like to seek an answer to this question however please.). The data from the server takes different times based on what is to be processed & returned.

The problem I have is the showCustomerUsageChart function call doesn't get invoked at all at any stage. I tried debugging this by setting a breakpoint on this function's entry & see that there is no call made to it at all. However, I can see that the JSON data is being returned by the server at different points in time upon the respective data being available. I understand I've implemented this incorrectly, no doubt.

AJAX world is not all too familiar to me. I have looked up quite a few questions in this forum, but, kind of struggling to put the pieces together.

Could I request help to achieve what I'm after please. I'd be highly grateful to any help.

<script>
    var ajaxurl = 'myDbHandler.php';
    <?php for ($k = 0; $k < count($propertyCustomer); $k++) { ?>
        data = {
            'param1': paramFromUser1, 
            'param2': paramFromUser2, 
            'param3': paramFromUser3,
            'lookUpParamId': "<?php echo $k ?>"
        };

        $.post(ajaxurl, data,function (response) {
            var resp = $.parseJSON(response);
            showCustomerUsageChart(
                "<?php echo $propertyCustomer[$k][0] ?>",
                "<?php echo $propertyCustomer[$k][1] ?>",
                "<?php echo $propertyCustomer[$k][2] ?>",
                "<?php echo $propertyCustomer[$k][3] ?>",
                resp,       
            );
        });
    <?php } ?>
</script>

So here's one way to go about it instead, I avoided using php in javascript so the code and markup are cleaner.

To simulate the lag coming from your queries I did this:

myDbHandler.php:

$number = rand(2, 11);
sleep($number);

echo 'success after ' . $number . ' seconds';

The original .php file now looks like this (test.php):

<?php
// Array filled with testdata:
$propertyCustomer = array(
    array('value1', 'value2', 'value3', 'value4'),
    array('value1', 'value2', 'value3', 'value4'),
    array('value1', 'value2', 'value3', 'value4')
);

// Make a string that html can handle and also encode the array above to a jsonString:
$json = htmlentities(json_encode($propertyCustomer));

?>

<!-- Echo the string as data-attribute -->
<div id="holdingElement" data-array="<?php echo $json ?>"></div>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="test.js"></script>

I seperated js from markup, because I can't stand ugly code (test.js):

$(document).ready(function () {
    // Get the array from the element:
    var phpArray = $('#holdingElement').data('array');

    // Console.log for testing:
    console.log(phpArray);

    // Loop through the array with the jQuery each function:
    $.each(phpArray, function(k, phpArrayValue){
        // The makeCall function returns a ajaxObject so the object gets put in var promise
        var promise = makeCall(k);

        // Now fill the success function in this ajaxObject (could also use .error() or .done() )
        promise.success(function(response){
            // When success, call the function and use the values out of the array above
            showCustomerUsageChart(
                phpArrayValue[0],
                phpArrayValue[1],
                phpArrayValue[2],
                phpArrayValue[3],
                response
            );
        });
    });
});



function makeCall(paramId) {
    // Just testdata:
    var paramFromUser1 = 'val1';
    var paramFromUser2 = 'val2';
    var paramFromUser3 = 'val3';

    // Use ajax instead of $.post to use the success function, and return this ajaxObject
    return $.ajax({
        url: 'myDbHandler.php',
        type: 'post',
        data: {
            'param1': paramFromUser1,
            'param2': paramFromUser2,
            'param3': paramFromUser3,
            'lookUpParamId': paramId
        }
    });
}

// Function to log the results from the ajax call:
function showCustomerUsageChart(val1, val2, val3, val4, response) {
    console.log(val1, val2, val3, val4, response);
}

I hope this makes any sence, and that it works for you!

Your code is faulty there:

showCustomerUsageChart(
                    <?php echo $propertyCustomer[$k][0] ?>

You have to put a "," after the PHP closing tag.