简体   繁体   中英

How to send php array using json to jquery using ajax?

I'm building a calculator and getting the results by using ajax in jquery to send values to the php file and returning the results back to jquery. I can get one result to return, but want to get two results that can be separated. I tried doing this with json from a previous answer , but can't get it to work. It appears that answer came from JQuery. What am I leaving out?

JQuery

$(document).ready(function () {
$("#loanamount").change(function() {
    var amount = $('#loanamount').val();
    var rate = $('#rate').val();
    var term = $('#term').val();
    $.post('superGlobalsGet.php', {amount: amount, rate: rate, term: term}, function(data) {
        $('#payment').html(data.payment); 
        $('#totalint').html(data.totalint);
    }, "json");
});

PHP

<?php

    if(isset($_POST['amount'], $_POST['rate'], $_POST['term'])) {
        $amount = $_POST['amount'];
        $rate = $_POST['rate'];
        $term = $_POST['term'];
        $convertRate = $rate + 2;
        $newRate = $convertRate + 3;
        $convertTerm = $term + 4;
        $loanPay = $newRate + 5;
        $totInt = ($loanPay * $convertTerm) - $amount;

        echo json_encode(array("payment" => $loanPay, "totalint" => $totInt));
    }
?>

Add the content type before sending the response :

...
header('Content-Type: application/json');
echo json_encode(array("payment" => $loanPay, "totalint" => $totInt));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM