Reputation: 337
I have looked far and wide through many similar questions but none seem to do it for me. They're either unrelated or incredibly overcomplicated - and I'm new to javascript.
What I have is an AJAX form which takes some input, posts it to form.php where it is JSON_encoded and echo'd back to the AJAX call as a response.
<?php
... calculations
..
.
echo json_encode(array("monthly_saved" => $monthly_saved, "peak" => $peak));
?>
This is successfully handled;
POST form.php
200 OK
41ms
HeadersPostResponseHTML
6018066.666666666667200{"monthly_saved":6.6666666666667,"peak":"10"}
Though now I need to harness these values and use them inside a HTML as content!
HELP!
My AJAX function:
$(function () {
$('#quote_form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "form.php",
data: $('#quote_form').serialize(),
dataType: "json",
cache: false,
success: function(data)
{
*WHAT I NEED TO FIGURE OUT*
}
});
});
});
I have been trying to find a solution for hours, yet can't seem to figure this out!
I was thinking of putting something within the success function along the lines of a hybrid between:
document.getElementById("graph_var_1").innerHTML = "(data.monthly_saved";
and
$("#graph_var_1").html(data.monthly_saved);
What would work?
The HTML I need to populate with these variables is:
<div class="result_field"><div id="graph_var_1"></div> (saved <div id="graph_var_2"></div>%)</div>
Upvotes: 1
Views: 288
Reputation: 16283
Firstly this:
6018066.666666666667200{"monthly_saved":6.6666666666667,"peak":"10"}
is not valid JSON, you must be echoing the number 6018066.666666666667200
previously, you should remove this.
Now the response will come in the success
callback as data
. If you want to access a specific bit of your response you can do this:
alert(data.monthly_saved);
This should alert 6018066.666666666667200
You should be able to use $("#graph_var_1").html(data.monthly_saved);
as you have already done to populate the DOM elements
Upvotes: 2