How to fix problem with json_encode() via an xml request - javascript

So I have a problem with my Code.
This is my index.html.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="container">
</div>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Nachrichten aus JSON zurueckparsen
var messages = JSON.parse(this.responseText);
//alle Nachrichten durchgehen
messages.forEach(function(message) {
var container = document.getElementById('container');
var messageElement = document.createElement('div');
messageElement.id = 'message'+message.id;
messageElement.innerHTML = message.message;
container.appendChild(messageElement);
//Onclick Handler für die message hinzufügen
messageElement.onclick=function() {
alert('message '+message.id+' clicked');
}
});
}
};
xhttp.open("GET", "login.php", true);
xhttp.send();
</script>
</body>
</html>
And this is my login.php:
<?php
$ar = array();
for ($i = 0; $i < 10; $i++) {
array_push($ar, array("test", "123"));
}
var_dump(json_encode($ar));
?>
So like you see I'm trying to make 10 arrays with the array_push method. But when I open the index it says "undefined" and that 10 times. Please help me.

It says "undefined" because there are no defined keys for "id" and "message" in your response.
You need to set the keys for response. Try this.
<?php
$ar = array();
for ($i = 0; $i < 10; $i++) {
$ar[] = array("id"=>$i, "message"=>"test $i");
}
echo json_encode($ar);
?>

Try this.
In PHP you don't need to use the array_push method to add a new element to the array.
Instead, you use this pattern since PHP extends the array automatically.
$ar[] = [];
<?php
$ar = [];
for ($i = 0; $i < 10; $i++) {
$ar[] = ['test', '123'];
}
var_dump(json_encode($ar));
?>

Related

How to get MySQL data from PHP to Javascript via XMLHttpRequest and output the data chronologically?

I've managed to get the MySQL data that I needed in order for me to display it onto the notification's container. Now I have a problem at manipulating the data I needed. Instead of printing the objects one by one, it prints the same object at multiple times. Here is the source code.
PHP MySQL data getter
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname= 'notifications';
$dsn = "mysql:host=$host;dbname=$dbname";
$connection = new PDO($dsn, $username, $password);
$sql = 'SELECT * from notifications ORDER by date';
$query = $connection->prepare($sql);
$query->execute(PDO::FETCH_OBJ);
$array_list = [];
while($row = $query->fetch()){
array_push($array_list, $row);
}
echo json_encode($array_list);
?>
Javascript that gets the value of MySQL data from PHP file. Don't mind the long string, it's just an element that will be added up to the notification container when scrolled down.
var notificationContainer = document.getElementById('notifications-container');
notificationContainer.addEventListener("scroll", myPageScroll);
var index = -1;
function myPageScroll(){
var theScrollTop = notificationContainer.scrollTop;
var theScrollHeight = notificationContainer.scrollHeight;
var height = notificationContainer.clientHeight;
//THIS IS WHERE I HAVE A PROBLEM. IT PRINTS THE SAME OBJECT 5 TIMES.
if(theScrollTop + height >= theScrollHeight){
for(i = 0; i < 5; i++){
testing();
index = index + 1;
}
}
}
function testing(){
var xhr = new XMLHttpRequest();
xhr.open("POST", "data_getter.php");
xhr.onload = function(){
var jsvar = this.response;
jsvar = JSON.parse(xhr.responseText);
console.log(jsvar[index]);
notificationContainer.insertAdjacentHTML('beforeend', jsvar[index].notification_content);
};
xhr.send();
}
Html file
<div class="drop-down-container" id="notifications-container"></div>
<script src="header.js"></script>
Though when I printed the objects into the console, it has the organized data.
This is because when you get any fetch response the for loop has done iterating so index (inside the testing function) always has the same value. You need to pass index has parameter of testing function.
var notificationContainer = document.getElementById('notifications-container');
notificationContainer.addEventListener("scroll", myPageScroll);
var index = -1;
function myPageScroll(){
var theScrollTop = notificationContainer.scrollTop;
var theScrollHeight = notificationContainer.scrollHeight;
var height = notificationContainer.clientHeight;
//THIS IS WHERE I HAVE A PROBLEM. IT PRINTS THE SAME OBJECT 5 TIMES.
if(theScrollTop + height >= theScrollHeight){
for(i = 0; i < 5; i++){
testing(index); // pass index as parameter
index = index + 1;
}
}
}
function testing(index){ // index has been added as parameter
var xhr = new XMLHttpRequest();
xhr.open("POST", "data_getter.php");
xhr.onload = function(){
var jsvar = this.response;
jsvar = JSON.parse(xhr.responseText);
console.log(jsvar[index]);
notificationContainer.insertAdjacentHTML('beforeend', jsvar[index].notification_content);
};
xhr.send();
}

Is there a way I can dynamically increment the number of items being showed on the html page using ajax, php and plain js

This is what I have
The JS file:
var loadBtn = document.getElementById('loadButton');
loadBtn.addEventListener('click', fetchProducts);
let quantity = 3;
function fetchProducts() {
quantity = quantity + 3;
var xhr = new XMLHttpRequest;
xhr.open('GET', `php/products.php?quantity=${quantity}`, true);
xhr.onload = function () {
if (this.status == 200) {
var products = JSON.parse(this.responseText);
var output, i;
for (i = 0; i < products.length; i++) {
output += `
<div id="pCard" class="p-card">
<p id="pName" class="p-name">${products[i].item_name}</p>
<p id="pAbout" class="p-about">${products[i].item_description}</p>
</div>
`;
}
document.getElementById('products').innerHTML = output;
}
}
xhr.send();
}
The PHP file:
include 'config.inc.php';
$quantity = $_GET['quantity'];
$sqlFetch = "SELECT id,item_name,item_description FROM items ORDER BY id ASC LIMIT $quantity";
$result = mysqli_query($connection, $sqlFetch);
$products = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($products);
I expected, after defining the quantity in the js file the fetchProducts function would increment the quantity of products and parse the quantity through GET to the php file.
Instead, this is what am getting from products.php:
Notice: Undefined index: quantity in C:\wamp64\www\simplesites\ss9_ajax\php\products.php on line 7

Using PHP array in the JS code in PDO

I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.
I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_zagon = 1;
$id_kurat = 1;
$usid = 78;
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$gyvuliu_array = array();
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = $num;
}
$array_encode = json_encode($gyvuliu_array);
?>
<script>
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliai_fermoje = '<?php echo $array_encode; ?>';
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
I guess something is bad with the $num variable but I'm not sure.
EDIT:
I've changed the second for loop and it looks like it's working:
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m
EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
You have to remove quotes, why? If you put the value in quotes that mean var gyvuliai_fermoje is a string not an array
Could You please try this once
$stmt1 = $pdo->prepare("SELECT GROUP_CONCAT(num) as nums FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$row = $stmt1->fetch();
$array_encode = json_encode(explode(",",$row["nums"]));
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
Try this
var gyvuliai_fermoje = <?php echo json_encode($array_encode, JSON_HEX_QUOT | JSON_HEX_APOS); ?>;
Problem solved! :) For future visitors, combined all this stuff you guys said, we have this code:
// PDO Connection
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . ';
charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepared statement with placeholders
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
// Binding query result to the $num variable (1 is the first column)
$stmt1->bindColumn(1, $num);
// Executing query and replacing placeholders with some variables
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
// Creating a PHP array
$gyvuliu_array = array();
// Fetching through the array and inserting query results using $num variable ((int) makes sure a value is an integer)
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = (int)$num;
}
// Encoding PHP array so we will be able to use it in the JS code
$array_encode = json_encode($gyvuliu_array);
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
for (var i = 0; i < gyvuliai_fermoje.length; i++) {
// Stuff you would like to do with this array, access elements using gyvuliai_fermoje[i]
}
</script>
I hope it will help you to understand how to use a PHP array in the JS code in PDO :)

Third dropdown populated based from second and first dropdown selections

I am creating an internal web tool that inserts data into a database. I was trying to find out how to create a three-tier dropdown selection, where I would insert the third dropdown's value into the DB.
I stumbled across this answer here:
Populate another select dropdown from database based on dropdown selection
But was done as a two tier dropdown.
My php code is this:
<?php
require 'connect.php';
$query = "SELECT customer_id,customer FROM schema.customer";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$categories[] = array("customer_id" => $row['customer_id'], "customer" => $row['customer']);
}
$query = "SELECT contract_id, customer_id, contract FROM schema.contract";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$subcats[$row['customer_id']][] = array("contract_id" => $row['contract_id'], "contract" => $row['contract']);
}
// Third dropdown which isn't originally included with the previous answer
$query = "SELECT subcontract_id, contract_id, subcontract FROM schema.subcontract";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$subsubcats[$row['contract_id']][] = array("subcontract_id" => $row['subcontract_id'], "subcontract" => $row['subcontract']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
$jsonSubSubCats = json_encode($subsubcats);
?>
Now, the given answer was this:
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
//Below wasn't part of the answer
echo "var subsubcats = $jsonSubSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].customer,categories[i].customer_id);
}
}
function updateSubCats(){
var catSelect = this;
var customer_id = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[customer_id].length; i++){
subcatSelect.options[i] = new Option(subcats[customer_id][i].contract,subcats[customer_id][i].contract_id);
}
}
</script>
</head>
<body onload='loadCategories()'>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
</body>
</html>
But I needed help with the third tier options based from the second dropdown selection. Thanks in Advance. :)
Was able to figure it out.
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
echo "var subsubcats = $jsonSubSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].customer,categories[i].customer_id);
}
}
function updateSubCats(){
var customer_id = this.value;
var subcatSelect = document.getElementById("subcatsSelect")
subcatSelect.onchange = updateSubSubCats;;
for(var i = 0; i < subcats[customer_id].length; i++){
subcatSelect.options[i] = new Option(subcats[customer_id][i].contract,subcats[customer_id][i].contract_id);
}
}
function updateSubSubCats(){
var subsubcatSelect = this;
var contract_id = this.value;
var subsubcatSelect = document.getElementById("subsubcatsSelect");
subsubcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subsubcats[contract_id].length; i++){
subsubcatSelect.options[i] = new Option(subsubcats[contract_id][i].subcontract,subsubcats[contract_id][i].subcontract_id);
}
}
</script>

PHP looped output of mySQL table is missing one row

Summary of problem: I have a mysql table with some data, I use some phpcode to display the data to an html page, to setup JavaScript variables before a page loads. The loop seems to work fine with one exception, the first row of the table gets dropped or doesnt show. I cant figure out why, is there a small bit of logic Im missing?
I have a mySQL table here:
http://gyazo.com/ac75247b1a3f11f59721f03ff9c80d08
and some php code to display it here:
//...
$sql = "SELECT * FROM ".TABLE_CALCULATOR." WHERE calculation_status = 'A'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$num_rows = mysql_num_rows($result);
if(count($num_rows) > 0 ){
while ($row = mysql_fetch_assoc($result)) {
$calculator_data[] = $row;
}
}else{
// Send Notication to admin Calculator not set
}
//...
<?php
if(!empty($calculator_data)){
foreach($calculator_data as $k => $v ){
if($v['name_value'] == 'perWinPriceMatrix'){
$per_win_matrinx = explode(",", $v['calculation_values'] );
$per_win_matrinx_final = array_chunk($per_win_matrinx, 5, true);
foreach($per_win_matrinx_final as $key => $values ){
$var[$key] = $key.':['.implode(',',$values).']';
}
?> var <?php echo $v['name_value'] ;?> = <?php echo "{".implode(",", $var)."}";?>;<?php echo "\n";
}else{
?> var <?php echo $v['name_value'] ;?> = [<?php echo $v['calculation_values'] ;?>];<?php echo "\n";
}
}
}
?>
this is the output:
var tax_bronze2 = [30,20,20,5,0];
var tax_bronze3 = [30,20,20,5,0];
var tax_bronze4 = [25,20,20,5,0];
var tax_bronze5 = [25,20,20,5,0];
var tax_silver1 = [35,30,30,5,0];
var tax_silver2 = [30,20,20,5,0];
var tax_silver3 = [30,20,20,5,0];
var tax_silver4 = [30,20,20,5,0];
var tax_silver5 = [30,20,20,5,0];
var tax_gold1 = [70,50,30,10,0];
var tax_gold2 = [60,40,20,8,0];
var tax_gold3 = [60,40,20,8,0];
var tax_gold4 = [60,40,20,8,0];
var tax_gold5 = [60,40,20,8,0];
var tax_platinum1 = [100,75,40,10,0];
var tax_platinum2 = [80,65,40,10,0];
var tax_platinum3 = [80,65,40,10,0];
var tax_platinum4 = [80,65,40,10,0];
var tax_platinum5 = [80,65,40,10,0];
var tax_diamond1 = [0,0,0,0,0];
var tax_diamond2 = [120,85,50,20,0];
var tax_diamond3 = [120,85,50,20,0];
var tax_diamond4 = [120,85,50,20,0];
var tax_diamond5 = [120,85,50,20,0];
var perWinPriceMatrix = {0:[4,4,4,4.5,4.75],1:[5,5.3,5.7,6.2,6.2],2:[7.8,8.6,9.7,10.8,11.8],3:[13,15,17,18,18],4:[19,21,25,30,40]};
var price_matrix = [19,20,20,20,32,24,24,24,24,42,46,51,53,56,60,60,65,74,79,140,186,214,242,298];
var provisionalPrice = [60,80,9.25,13,1.3,0.75];
question: Why is output missing a row?
delete $row = mysql_fetch_array($result); this line fetch row #1

Categories

Resources