jquery - How do I post specific json data from php/mysql instead of all data
I have this code working pretty well except that it's going to post all of the results from php where I just want specific json_encoded data. Here's the PHP that pulls from my database.
<?php
session_start();
$_SESSION['charname'] = 'Egahtrac';
require_once ('mysqli_connect.php');
$q = "SELECT * FROM dps WHERE charname='" . $_SESSION['charname'] . "';";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$dmg = $row['dmg'];
$curr_hp = $row['curr_hp'];
$tot_hp = $row['tot_hp'];
$attk_spd = $row['attk_spd'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['attack'])) {
if ($curr_hp > 0) {
$row['curr_hp'] = $row['curr_hp'] - $row['dmg'];
$q = "UPDATE dps SET curr_hp='" . $row['curr_hp'] . "' WHERE charname='" . $_SESSION['charname'] . "';";
$r = mysqli_query($dbc, $q);
echo json_encode($row);
}
}
}
Here's the jQuery
$('input#attack').on('click', function() {
$.post('dpsloop2.php', { attack: true }, function(data) { $('span#curr_hp').text(data.dmg); });
});
// see here that i'm just trying to test if it works by echo'ing the dmg value to the curr_hp span to see if it changes.
$('#dpsform').submit( function() {
return false;
});
I know this has something to do with the .text(data) part. But if I tried to do .text(data.curr_hp) it doesn't work. I've checked to see that the json array is echoing the proper format from php, so why can't I access that data.curr_hp from the JSON array?
Answer
Solution:
In your PHP you should only call
echo json_encode(something)
once. The JSON response has to be a single object or array; if you want to return multiple things, you need to put them in an array. So you should just do:Then need to use the
dataType
argument to$.post()
to tell it that the response is JSON. Then it will parse it for you.If you want to return the whole row, it should be:
and the JS should be something like:
Answer
Solution:
Just got it to work, Here's the solution and it works perfectly. I had to declare data as a serialized array.