JSON GET data using Javascript/JQuery [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What I am trying to do is, get data from my MySQL database using a Javascript/JQuery GET request and place this information within an HTML table to display which shifts do not contain a User ID.
I am struggling to understand how to display the JSON get data on the page and how to place this within a table on the HTML page.
I am using PHP on my localhost server to retrieve the data and I am able to retrieve the information in a JSON string.
The function that does this is here:
function marketplaceShifts(){
include ('config.php');
$sql = "SELECT *
FROM shift
WHERE user_id IS NULL";
$result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$return = array();
foreach ($result as $row){
$return[]=array('id'=>$row['shift_id'],
'User id'=>$row['user_id'],
'Date of shift'=>$row['date_shift'],
'Start of Shift'=>$row['start_time'],
'End of Shift'=>$row['finish_time']);
}
$conn = null;
header('Content-type: application/json');
echo json_encode($return);
}
This is the function that retrieves the data that I am looking for and works when using Postman to show me the JSON strings with the information I need.

Using jQuery's $.getJSON(), you can grab JSON data from a URL, and do what you want with it, like rendering it on the page (you can also do it without the library). For this method, make sure you include jQuery in your page.
The request can be made that way:
$(document).ready(function(){
$.getJSON('path/to/your/json.php', displayData);
});
Then, just create a displayData() function to do the work:
function displayData(data){
var table = $('<table></table>'), // Create a table element
row = $('<tr></tr>'), // Create a row
keys = Object.keys(data[0]); // Grab the headings
for(var i=0, l=keys.length; i<l; i++){ // For each of them
var cell = $('<th></th>').text(keys[i]); // Create cell, insert text
row.append(cell); // Append cell to row
} // End for
table.append(row); // Append row to table
for(var i=0, l=data.length; i<l; i++){ // For each data element
row = $('<tr></tr>'); // Create row
for(var j=0, k=keys.length; j<k; j++){ // For each key
var cell = $('<td></td>').text(data[i][keys[j]]);// Create cell, insert value
row.append(cell); // Append cell to row
} // End for
table.append(row); // Append row to table
} // End for
$('body').append(table); // Append table to body
}
JS Fiddle Demo

Related

Giving an new index to a table row after deleting other row

My code is a simple form with 3 input fields. Once the user fills them all in and presses the button it will add a row to the table with the input data aswell as an index number. Like this:
https://imgur.com/g5ToOpF
im trying to give each row in a table an index number that is correct with the amount of rows inserted. This works but now I want it to update the index number when I remove one of the rows from the table.
The following function is triggered when the customer fills in an input field with the desired index number that they want to delete and then press a button.
function removeRow() {
let tabel = document.getElementById("tabel");
let rows = tabel.getElementsByTagName("tr");
let indexNumber = document.getElementById("indexnumber").value;
Object.entries(rows).forEach(([key]) => {
if(key === indexNumber) {
tabel.deleteRow(indexNumber);
}
})
}
This works and deletes the row that the customer whats but it doesn't update the index numbers for the other rows. So when I delete row 5. My table will look like this.
https://imgur.com/Zz3sBSI
I figure I have to loop through all of the rows and set the index to the correct number again. Can anyone help me out :) ?
For the full code check:
https://codepen.io/Botert/pen/bJLLWL
grtz,
Botert
To answer your question, try adding the following snippet in your removeRow() function:
for (var i=1; i<rows.length; i++) {
var dataRow = rows[i].children[3];
dataRow.textContent = i;
}
Fiddle here: https://jsfiddle.net/ufszamv4/
It's outside of the scope of the question, but consider taking a different approach to the problem. Try placing your rows in an object that has its properties removed. The goal is to simply delete a row without having to update the rest of the data.

Standard way of building an arbitrary length table in Javascript

I'm receiving data from a websocket (live stream), and trying to put it into a table. I'm currently using the following code:
var table = document.getElementById("websocket-data");
function writeToScreen(message) {
var new_row = table.insertRow(0);
var cell1 = new_row.insertCell(0);
var cell2 = new_row.insertCell(1);
var obj = JSON.parse(message.data);
console.log(obj.value);
cell1.innerHTML = obj.id;
cell2.innerHTML = obj.value;
}
This works, and creates a new row for every JSON packet. The functionality that I am looking for is: On receipt of a JSON, if the id is not in the table, then create a row with id and value, however, if the id is already in the table, simply update the value. I've come across a few ways of doing this, but I'd like to know what the 'proper' way to do it is. I was thinking that perhaps the data should go into an array, and then the array should populate the table, but that would involve repopulating the entire table every time the array changed... I'm happy to use JQuery or similar if necessary.
You could use an array and repopulate the table every time like you said, and if the table will only ever be small then you may not run into issues with that.
One possible alternative of many is maintaining an object in the background with your ids as keys and then store the value and the table row index as values.
Something like:
var tableStore = {};
function recieveMessage(message) {
var obj = JSON.parse(message);
// if the id is not in the tableStore, add it!
if (tableStore[obj.id] === undefined) {
// insert new row into table and save the index into `newTableRowIndex`
// store a blank value (updated below) and the index in the table where it will be displayed
tableStore[obj.id] = {value: undefined, tableIndex: newTableRowIndex};
}
// if the value recieved is different than the stored value, update the row
if (obj.value !== tableStore[obj.id].value) {
tableStore[obj.id].value = obj.value; // store the new value
var row = getTableRow(tableStore[obj.id].tableIndex); // your own function to get the row based on index
// update the row to display the new information
}
}
This could be improved and made to be more organized but you should get the idea.
This way it would only update anything in the display if the new information recieved is different than the old information already stored.
This way should also perform better than using an array would if the table has the potential to get very large as you would not need to search through the entire array every time to see if the id is already stored or not. You would simply access the tableStore entry directly using the id.

JQuery get count of rows

Very Quick points. I have seen very similar questions here on SO but they usually use the table ID or assume there is only one table. I have a page with many tables using the same template (no unique ID) and would like to know if when a particular data is loaded, if the rows are empty. I have tried :
jQuery: count number of rows in a table
Jquery- Get the value of first td in table and many others
//var row = $(this).closest('table tbody:tr:first');
// var row = $(this).closest('tr').children('td:first').text();
// var row = $(this).closest('tr').length;
// var row = $(this).closest('tr').children('td:first').length;
// var row = $(this).closest('table').find("tbody").children().length;
// var row = $(this).closest('table').children('tr:last').index() + 1;
// var row = $(this).closest('table').rowIndex;
// var row = $("tbody").has("tr");
// var row = $(this).closest('tbody').has("tr");
var row = $('#tbody').children('tr:first').length;
But cannot get the right answer.
Below is the table structure:
To get number of rows, use length or size()
//$(this) assumed as element inside table.
$(this).closest('table').find('tr').length
As you mentioned that you've many tables in a page. you need to let jQuery identify the table index from where you want to get tr length.
To get the specific table, use eq()
//To get TR length in 2nd table of a page
$('table:eq(1) tr').length
FYI,
For class selector, use $('.table:eq(1) tr').length
Use $(document).ready(function(){} to wrap your code, that will work when your page gets ready.
Looking at your table structure,
you can use
$(".dataTable tr").length
to get the count of rows in table
$("table").each(function(){
console.log($(this).find("tr").length));
})
This will log the count of trs in all tables that you have in your page
If you want to run some code when data gets loaded into any table you got to use Mutation Observer
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
//create observer
var observer = new MutationObserver(function(mutations, observer) {
console.log("Table Loaded");
//whatever you want to do when table is loaded
});
//set to observe childs ( options )
observer.observe(document.querySelector("table"), {
subtree: true,
childList:true,
attributes:true
});
I went through people's suggestions which mostly assumed (like the other pages) that there was an ID and that there was a single table on the page although the question mentioned it wasn't so.
Ended up using: var row = table_values.context.tBodies["0"].firstElementChild;
I got this by inspecting the tbody via dev tools.

insert into database with dynamic form with javascript (codeigniter) [duplicate]

This question already has an answer here:
PHP into database with dynamic form with javascript (codeigniter)
(1 answer)
Closed 7 years ago.
I build an app but I found new problem, I want to insert multiple data using javascript to add more form dynamically (then insert into table). Okay in my FIGURE, number 1,2,3 that's clear. But when I insert into the table , it can't succesfully. (number 4 is my function to insert data, but all of may form cannot insert (number 5) , only 1 data can insert ). what's wrong ? thanks
FIGURE
use for loop like this, your $_POST must be under loop.
for ($i = 0; $i < count($_REQUEST['heading']); $i++) {
$heading = $_POST["heading"][$i];
$address = $_POST["address"][$i];
$array_addmore[$i] =
array(
"heading" => urlencode($heading),
"address" => urlencode($address)
);
}

Correct way to use SELECT INTO with WebSQL and HTML 5?

speeddial.storage.Sync = function() {
chrome.bookmarks.getChildren(String(localStorage['rootFolderID']), function(newSync){
speeddial.storage.db.transaction(function(tx){
tx.executeSql('DELETE FROM bookmarksSync',null,null,speeddial.storage.onError);
tx.executeSql('DELETE FROM groupsSync',null,null,speeddial.storage.onError);
for (var i=0; i<newSync.length; i++){
if(!newSync[i].url)
{
tx.executeSql('SELECT INTO groupsSync FROM groups', [],null
,speeddial.storage.onError);
}
...
//above is the end of else statement
}
})
})
}
I want to use SELECT * INTO to copy some values from one SQL table to another. When I use the above
I get near INTO syntax error.
I WANT TO NOW HOW TO DO BOTH THINGS - copy the values of some columns form table A to table B based on a specific column value, and completely replacing the contend of table A with this of table B
Thank you ;)
Try:
INSERT INTO groupsSync SELECT * FROM groups
For more information on websql queries look into sqlite INSERT INTO syntax documentation

Categories