user1199649
user1199649

Reputation: 39

How to output only a json_encoded array from an Ajax call?

I want my ajax call to only return the values from my array in test.php

At the moment the ajax call is returning all the code present in the php file.

How can I return only the json_encoded array?

jQuery Code:

var params = {'action': 'save' , 'id':5};
$.ajax({
    type: "POST",
    url: "test.php",
    data: params,
    success: function( data ) {
        $.each(data, function (index, value) {
            $('#menu_container a').eq( index).text( value);
        });
    }
});

test.php:

<?php
    $array = array();
    $i = 0;
    while ($i < $num) {
        $f1 = mysql_result($result, $i, "Page");
        $array[] = $f1; ?>

        <?php echo $f1; ?>

        <?php $i++;
    }
?>

</br>
</br>

<?php
    echo json_encode($array);
?>

</body>
</html>

Upvotes: 0

Views: 274

Answers (1)

Michael Robinson
Michael Robinson

Reputation: 29498

Simply remove all other portions of your PHP code that generated output:

<?php
$array = array();
$i = 0;
while ($i < $num) {
    $f1 = mysql_result($result,$i,"Page");
    $array[] = $f1;
    $i++;
}
echo json_encode($array);
?>

Upvotes: 1

Related Questions