Im using MySQL to obtain data into $username and $chance.
There are two usernames in the data but it only loads the first one.
var data = [
{
"name" : "<?php echo $username; ?>",
"hvalue" : <?php echo $chance; ?>
},
];
To give a correct answer, we'll have to know what your variables $username and $chance exactly look like.
If you only have a string there, then only one value is possible.
If these variables are php arrays, you'll have to use json_encode to make a JSON array from them, before you can add them to your javascript object. (see https://secure.php.net/manual/en/function.json-encode.php)
Anyway, the best way to send a PHP array to JS would be to create the whole array in PHP and then encode it to JSON in order to use all the values in JS.
var data = <?php echo json_encode($data); ?>
More advanced: use an ajax request to avoid mixing up PHP an JS. But that's another story.
Related
I am creating an Inline Edit data by using X-editable with PHP Dropdown Select Box. I am facing an issue in that I am not able to create a dynamic select option in jquery from database data.
Actually, I want to echo the source format of text in PHP so I can add in jquery. The snippet below is in the correct format, but I don't know how to echo that text dynamically using data from PHP.
-- PHP --
$stmt = $connect->prepare("SELECT * FROM `profile`");
$stmt->execute();
-- JQUERY --
$('#employee_data').editable({
container: 'body',
selector: 'td.gender',
title: 'Gender', dataType: 'json',
source: [{value: "Male", text: "Male"}, {value: "Female", text: "Female"}]
});
Please help me to create this json structure [{value: "Male", text: "Male"}, {value: "Female", text: "Female"}] from a server-side query and pass it into the editable() function's argument in jquery.
I tried this, but it didn't work:
$result = $stmt->fetchAll();
foreach($result as $data => $value) {
$data = array('value' => $value["category_id"], 'text' => $value["category"]);
}
$category_list = json_encode($data);
There is a simple logic error here - you are overwriting the value of $data every time your loop runs, so you'll only ever end up encoding the value of whatever the last entry in your data was.
Instead you need to declare an array, and then add items to that array each time you loop:
$result = $stmt->fetchAll();
$list = array();
foreach($result as $data => $value) {
$list[] = array('value' => $value["category_id"], 'text' => $value["category"]);
}
$category_list = json_encode($list);
And then in the JavaScript, simply write:
source: <?php echo $category_list; ?>
There are several points to inform you of...
If you are not using any placeholders in your sql, then using a prepared statement is needless overhead. Just use query().
Do not ask for more data from your SELECT clause than you actually intend to use. I don't know how many columns are in your table, but you only need to be fetching category_id and category according to your posted script.
By aliasing your column names in your SELECT clause, you can avoid the extra step of iterating the result set's rows just to adjust the keys.
There seems to be a disconnect in your post between category_id & category versus gender & gender. I don't know exactly what data is being used to create these <option>s, but I would like to tell you that there is never any benefit to repeating identical text in the option's text and the same option's value attribute. In other words, <option value="Male">Male</option> should only ever be written as <option>Male</option>; the former is simply redundant markup bloat. I will assume that category_id and category are not identical values, so there should be no concern for redundancy.
fetchAll() is most appropriately used when you are not iterating the data in the same "layer". Because the server-side (php) data is being passed to the client-side (js), there is no need to manually iterate the result set to create an array; just let fetchAll() do all of the work.
Code: (assuming you are querying in the same file that you are printing to screen)
source = <?php echo json_encode($pdo->query("SELECT `category_id` AS `value`, `category` AS `text` FROM `profile`")->fetchAll()); ?>
There is a bounty of good advice/techniques # https://phpdelusions.net/pdo_examples/select
I am working with following APIs:
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
https://store.steampowered.com/api/appdetails?appids=GAMEID
(gameid example: "730" - counter strike)
My goal with both of these is to search them for data. For example I want the first API to give me a name of a game based on it's ID and the second one to give me specific information about a game for example if it has trading cards (id:29 in the API).
I tried a few things but I am kinda lost on this beacuse I don't really understand JSON so I would really appreciate some help.
I am open to both PHP and JS solutions.
IN PHP, you can use the json_decode() function to convert JSON data into an array. You can them access the values as you do for a classic array :
$appID = 730 ;
$url = 'https://store.steampowered.com/api/appdetails?appids=' . $appID ;
$content = file_get_contents($url) ; // retrieve the JSON data string from the website
$data = json_decode($content, true); // convert the JSON string into PHP array
echo $data[$appID]['data']['name'] ; // Counter-Strike: Global Offensive
var_dump($data[$appID]['data']['is_free']); // bool(true)
I have a JSON formed #Javascript and passed to PHP via AJAX , problem is that I cannot assign keys to each JSON Object inside the JSON Array .
The JSON Array looks something like this :
[{"jobId":"90","cname":"Subhasish","removal_id":101,"quantity":"3"},{"jobId":"90","cname":"Subhasish","removal_id":102,"quantity":"2"},{"jobId":"90","cname":"Subhasish","removal_id":103,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":104,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":105,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":106,"quantity":"5"},{"jobId":"90","cname":"Subhasish","removal_id":107,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":108,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":109,"quantity":"4"}]
,Now , in PHP ,how to iterate the data , I am a newbie to PHP , so please excuse me if I am asking a very silly question.
The link you provided has examples with key, mine is without key.
Thanks
$json = '[{"jobId":"90","cname":"Subhasish","removal_id":101,"quantity":"3"},{"jobId":"90","cname":"Subhasish","removal_id":102,"quantity":"2"},{"jobId":"90","cname":"Subhasish","removal_id":103,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":104,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":105,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":106,"quantity":"5"},{"jobId":"90","cname":"Subhasish","removal_id":107,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":108,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":109,"quantity":"4"}]';
$array = json_decode($json,true);
foreach($array as $item) {
echo $item['jobId']."-".$item['cname']."-".$item['removal_id']."-".$item['quantity']."\n";
}
Output
90-Subhasish-101-3
90-Subhasish-102-2
90-Subhasish-103-4
90-Subhasish-104-4
90-Subhasish-105-0
90-Subhasish-106-5
90-Subhasish-107-0
90-Subhasish-108-0
90-Subhasish-109-4
Example
Using json_decode($json_object).
$json = json_decode($json_object);
foreach($json as $j){
print_r($j)
}
I have an array stored in a mysql table, like this:
[3,5,6,7,8]
When I select it, encode it as JSON in PHP and then parse it into a javascript object, instead of it becoming an array, it just becomes a string "[3,5,6,7,8]". I know it's not possible to store it as an array in a single field, so.. what could I do so it will convert properly to an array instead of string?
My current code:
test = JSON.parse('[{"id":43,"incidence":"[0,3,6,7]"}]')
I could solve it removing the " on the string, but mysql returns it with the string, php encodes with the quotes and javascript parses with quotes. So basically, is there a way to remove it in this process?
The problem lies on how you are constructing your array prior turning it into JSON. Since you are retrieving these results from the database, I am assuming you are constructing a multidimensional array that may look something like this:
$results = array(
array(
"id" => 43,
"incidence" => "[0,3,6,7]"
)
);
Because incidence is a string, it is giving you those errors when using it in JS. To solve you need to turn that string into an array. Now, since you might have more than one result (being that these are database results) you need to iterate through the result array and turn that string into an array like this:
foreach ($results as &$row) { // <-- notice the & symbol (Passing by reference)
$no_brackets = trim($row["incidence"], '[]');//if you stored your array as comma delimited value, you would not need this.
$row["incidence"] = explode(',', $no_brackets);
}
Lastly, use json_encode and pass it to JS.
Final Result:
<?php
foreach ($results as &$row) {
$no_brackets = trim($row["incidence"], '[]');
$row["incidence"] = explode(',', $no_brackets);
}
$json = json_encode($results);
?>
<script>
var obj = JSON.parse('<?= $json ?>');
console.log(obj);
</script>
Hope this helps.
You need to do a little fiddling to get this to work.
Try this
<?php
$string = '[3,5,6,7,8]';
$t = str_replace(array('[',']'), '', $string);
$array = explode(',', $t);
echo json_encode($array);
The result is
["3","5","6","7","8"]
Here is my code:
I am getting data from mysql query and getting array of values. But i am not able to populate in javasript. could you please any one help me out...
PHP Code:
$parishFamilyInfo = $parishFamilyInfoBO->sendBirthdayGreeting($personalInfoSearchDO, $parishFamilyInfoSearchDO);
foreach ($parishFamilyInfo as $parishFamily){
if(!empty($parishFamily->email)){
print_r($parishFamily);
}
}
JavaScript:
$(document).ready(function(){
var t = $('#people').bootstrapTransfer(
{'target_id': 'multi-select-input',
'height': '15em',
'hilite_selection': true});
t.populate([ /*here i need to populate php array value*/
{
value:"<?php print_r($parishFamily->email);?>",
content:"<?php print_r($parishFamily->name);?>"
},
]);
//t.set_values(["2", "4"]);
//console.log(t.get_values());
});
print_r is only for debugging. It's not for anything else. Let me quote the documentation:
print_r — Prints human-readable information about a variable
As stated above, it is a debugging function that's used to print the contents of a variable in a more readable manner. It just returns a string — JavaScript does not and will not understand this format.
Use JSON (JavaScript Object Notation) instead. It is is a light-weight data interchange format that is very popular nowadays. You can use the built-in function json_encode to create the JSON representation of your PHP array and then transfer it to JavaScript. JSON being language independent and based on the JavaScript scripting language, your JavaScript code will now be able to parse the array:
t.populate([
{
value: <?php echo json_encode($parishFamily->email); ?>,
content: <?php echo json_encode($parishFamily->name); ?>
},
]);