I tried to create a function which generates a link and added it to an element. But the .click function wont work. I dont even get an error, thats why I'm not sure if the function or the variable is wrong.
This is my javascript code:
$("#nwa1").click(function(){
var titel = document.getElementById("h1").innerHTML;
link = '';
link += 'nwa_' + titel + '.json'
$.getJSON(link, function(json){
aus = '';
aus += '<table border="1"><tr><th>Kcal</th><th>Eiweiß in g</th><th>Fett in g</th></tr>';
for (i = 0; i < json.werte.length; i++){
aus += '<td>' + json.werte[i].kcal + '</td>' + '<td>' + json.werte[i].eiweiß + '</td>' + '<td>' + json.werte[i].fett + '</td>';
}
aus += '</tr></table>';
$('#div2').html(aus);
})
})
And here is the html page:
<h4 id="nwa1">Nährwertangaben</h4>
<div id="div2" ></div>
The link i want to open with the function is nwa_falafel.json and 'falafel' is my h1-element.
Thank you, for trying to help!:)
This is an issue with the path to your JSON file. Try the (working) code below and check the console for to see if it is logging an error.
$("#nwa1").click(function()
{
alert('genau!');
$titel = document.getElementById("h1").innerHTML;
$link = '';
$link += 'nwa_' + $titel + '.json'
$.getJSON( $link, {
format: "json"
})
.fail(function() {
console.log( "error" );
})
.done(function( data ) {
console.log("done");
console.log(data.werte);
aus = '';
aus += '<table border="1"><tr><th>Kcal</th><th>Eiweiß in g</th><th>Fett in g</th></tr>';
$.each( data.werte, function( i, item ) {
aus += '<td>' + item.kcal + '</td>' + '<td>' + item.eiweiß + '</td>' + '<td>' + item.fett + '</td>';
});
aus += '</tr></table>';
$('#div2').html(aus);
});
});
I added some colors my side just for emphasis:
So if you are getting an error check the location /path to your JSON file as the code works fine.
Related
im curently working on a script that pulls data from google sheets and transforms it in to a html table. but i have links in my google sheets tabele so i want that these links get but in a button that looks nice but icant figure out how to do that.
i curently have this loob
for (var i = 0; i < entry.length; i++) {
html += '<tr>';
html += '<td>' + entry[i]['gsx$komponente']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$name']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$hersteller']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$preis']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$link']['$t'] + '</td>';
html += '</tr>';
}
html += '</table>';
the entry[i]['gsx$link']['$t'] gets me the links i just cant get it to work inside a button
if you have any idea how i can solve this problem please help me
here is the Complete code
<!DOCTYPE html>
<meta charset="ISO-8859-1">
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
// ID of the Google Spreadsheet
var spreadsheetID = "1Xx0qGY_5Ic1KNB7m8Lu5mZqHE4XQzauvcugTVUGwgqk";
// Make sure it is public or set to Anyone with link can view
var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json";
// make JSON call to Google Data API
$.getJSON(url, function(data) {
// set global html variable
var html = '';
// build table headings
html += '<table>';
html += '<tr>';
html += '<th>Komponente</th>';
html += '<th>Name</th>';
html += '<th>Hersteller</th>';
html += '<th>Preis</th>';
html += '<th>Link</th>';
html += '</tr>';
// loop to build html output for each row
var entry = data.feed.entry;
/**
** Change to descending order
** for (var i = entry.length - 1; i >= 0; i -= 1) {
*/
for (var i = 0; i < entry.length; i++) {
html += '<tr>';
html += '<td>' + entry[i]['gsx$komponente']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$name']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$hersteller']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$preis']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$link']['$t'] + '</td>';
html += '</tr>';
}
html += '</table>';
// output html
$('.console').html(html);
});
// loading animation
var loading = $('.loading');
loading.hide();
$(document)
.ajaxStart(function() {
loading.show();
})
.ajaxStop(function() {
loading.hide();
});
</script>
<div class="console"></div>
<div class="loading">
</div>
</body>
</html>
You just need to wrap the link inside <a> tag
for (var i = 0; i < entry.length; i++) {
html += '<tr>';
html += '<td>' + entry[i]['gsx$komponente']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$name']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$hersteller']['$t'] + '</td>';
html += '<td>' + entry[i]['gsx$preis']['$t'] + '</td>';
html += '<td><a href=' + entry[i]['gsx$link']['$t'] + '>' +entry[i]['gsx$link']['$t'] + '</a></td>';
html += '</tr>';
}
i have three tabs. in one i want to load data from database and have a filter by email. when i click the button i want the data of only the user with the email to be displayed in the table in the same tab.
this is my script in view
<script>
jQuery('.savedata').click(function (e) {
e.preventDefault();
jQuery.post('/gettabdata', {
_token: window.csrf_token,
email: jQuery('input[name="email"]').val()
}
function (data) {
var $tableBody = jQuery('#filtered-data tbody');
$tableBody.html('');
jQuery.each(data, function (i) {
$tableBody.append(
'<tr>' +
'<td>' + data[i].User_id + '</td>' +
'<td>' + data[i].email + '</td>' +
'<td>' + data[i].status + '</td>' +
'<td>' + data[i].date + '</td>' +
'<td>' + data[i].time + '</td>' +
'</tr>'
);
});
}
'json');
});
</script>
this is my controller
for the tab in which i want to see the result
else {
$user = \Auth::guard('api')->user();
$post = $request->all();
$email = $request->input('email');
$cond = ' 1=1 ';
if(!empty($post['email'])){
$cond .= " and email like '".$post['email']."'";
}
$qry = 'SELECT User_id, email, status, date, time FROM profile WHERE '.$cond.' ';
$data = DB::select($qry);
$response = $this->analysis($post);
//$getdata=$this->userdata($post);
$data = [
'data'=>$data,
'response'=>$response,
//'getdata'=>$getdata
];
return response()->json($data);
}
try this
Route
Route::get('/get-record-by-email','Controller#getRecord');
//controller
public function getRecord(Request $request)
{
$emailid= Input::get('email_id');
$jsondata= DB::table(your-table)->where('email',$emailid)->get();
return response()->json($jsondata);
}
//Ajax call
$("#btnClick").change(function(e){
//console.log(e);
var email_id = e.target.value;
//alert(email_id);
//$token = $("input[name='_token']").val();
//ajax
$.get('/get-record-by-email?email_id='+email_id, function(data){
$('#filterdata').empty();
//console.log(data);
$.each(data, function(index, obj){
$('#filterdata').append( '<tr>'
'<td>' + obj.User_id + '</td>' +
'<td>' + obj.email + '</td>' +
'<td>' + obj.status + '</td>' +
'<td>' + obj.date + '</td>' +
'<td>' + obj.time + '</td>' +
'</tr>' );
});
})
});
I have a data coming from the database. And Displaying when the ajax function is called. I am able to display it. But, One of the variable is an array data and saved it using implode function. Data is like (a,b,c,d).
Data is displaying in the below format
data1 Data2 Data3 (a,b,c,d) Data5 and so on.
I want to explode the array data and print one below the another.
I should display it like
data1 data2 data3 a data5
b
c
d
Here is the code which i am written to get the data.
<script type="text/javascript">
$('#genreport').on('click',function(){
var Representativeid = document.getElementById("Representativeid").value;
var dateFrom = document.getElementById("dateFrom").value;
var dateTo = document.getElementById("dateTo").value;
var url = '{{URL::to('/admin/GenReport')}}';
$.ajax({
type : 'get',
url : url,
data : {Representativeid:Representativeid,dateFrom:dateFrom,dateTo:dateTo},
success:function(data){
console.log(data);
var $tabledata = $('#tbody');
$tabledata.empty();
for (element in data)
{
var row = '<tr>' +
'<td>' + data[element].date + '</td>'+
'<td>' + data[element].doctor_name + '</td>'+
'<td>' #foreach(explode(',', data[element].products ) as $product)
{{$product}}
#endforeach '</td>' +
'<td>' + data[element].quantity + '</td>'+
'<td>' + data[element].locations +'</td>'+
'<td>' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row);
}
},
error:function(data)
{
alert('fail');
alert(data);
}
});
});
</script>
I am failing in the for-each logic. Please help me to display as i expected.
You cannot use a php function/code(server-side) in your javascript/jQuery code(client-side), as the php code will be parsed before the page is loaded. Instead you need to use javascript code.
First, you need to split the value into an array
var productsArray = data[element].products.split(',');
then you would need to get the array count (.length) to use a rowspan, so it doesn't break your table stucture
var rowSpan = productsArray.length;
....
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
....
finally, you need to loop in javascript, not php, through the array. (note, because the i<0 <td>s go on subsequent rows, you need to add them after)
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
so it would look something like this -
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
// get products array count
var rowSpan = productsArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
row +=
'<td rowspan="'+rowSpan+'">' + data[element].quantity + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].area + '</td>'+
'</tr>';
// append both row and the <td>s in rowAfter
$('#tbody').append(row+rowAfter);
}
just add <tr><td> inside foreach.
Edit:
Also, take a look at this link. table inside a td
I have implemented this with thymeleaf before and have struggled to implement it with javascript and Ajax get request.
Basically the table is generated and in my html script the Ajax get request gets and displays a list of teams into this table, is there a way to include a href or even a button after each row that passes the teams Id to my controller upon clicking the link?
Here is my controller:
$(document).ready(function() {
// DO GET
$.ajax({
type : "GET",
url : "/all",
success: function(result){
$.each(result, function(i, team){
var customerRow = ' <tr>' +
'<td>' + team.id + '</td>' +
'<td>' + team.teamName.toUpperCase() + '</td>' +
'<td>' + team.teamAddress + '</td>' +
'<td>' + team.level + '</td>' +
'<td>' + '' + View Team + '</td>' +
'</tr>';
$('#customerTable tbody').append(customerRow);
});
$( "#customerTable tbody tr:odd" ).addClass("info");
$( "#customerTable tbody tr:even" ).addClass("success");
},
error : function(e) {
alert("ERROR: ", e);
console.log("ERROR: ", e);
}
});
// do Filter on View
$("#inputFilter").on("keyup", function() {
var inputValue = $(this).val().toLowerCase();
$("#customerTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(inputValue) > -1)
});
});
})
You can see my attempt to implement it at the 5th <td> tag.
This will be the controller I am passing the id variable to, just incase.
#RequestMapping(value="/viewteam/{id}", method=RequestMethod.GET)
public String ViewTeam(Model model, #PathVariable Long id) {
Team team = teamRepository.findOne(id);
//the code below should ideally return all the players associated with the above team id in an array list, this array list will be passed via thymeleaf to display all players
model.addAttribute("team", team);
return "singleteam";
}
Looks like you may be over complicating this using the inline .Net syntax. Considering you already have the data back from the ajax you should be able to set the string (like #Musa mentioned) like this:
'<td>View Team</td>' +
Just as a robust example:
var team = {
id: 1,
teamName: "Capitals",
teamAddress: "Capital One Arena",
level: 9001,
};
var customerRow = ' <tr>' +
'<td>' + team.id + '</td>' +
'<td>' + team.teamName.toUpperCase() + '</td>' +
'<td>' + team.teamAddress + '</td>' +
'<td>' + team.level + '</td>' +
'<td>' + 'View Team</td>' +
'</tr>';
$('#customerTable tbody').append(customerRow);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="customerTable">
<tbody>
</tbody>
</table>
I've looked around for a solution but I might just be missing something really obvious because they don't solve my issue. I am no JS wiz at all, just a disclaimer.
I have an ASP project where JavaScript calls some C# code some times. I start my code with this:
window.onload = function () {
LiveSearch();
getCredentials();
getAllUsers();
getIsAdmin();
};
All of these functions work just fine. But the one of interest is getAllUsers() because it contacts the backend via an AJAX call to get some data to fill in a table.
function getAllUsers() {
var result_body = "";
$.ajax({
type: 'GET',
url: '/Home/GetAllUsers',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(""),
success: function (users) {
PushToScope("users", users);
var dict = scope[2];
if (dict.key.length > 0) {
for (var key in dict.value) {
result_body += '<tr onclick="getClickedUserObject(' + dict["value"][key].Initials + ')\">';
result_body += '<td class=\"col-xs-4\">' + dict["value"][key].Name + '</td>'
result_body += '<td class=\"col-xs-4\">' + dict["value"][key].Title + '</td>'
result_body += '<td class=\"col-xs-4\">' + dict["value"][key].Department + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].PrivatePhone + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].WorkEmail + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].WorkPhoneLandline + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].WorkPhoneMobile + '</td>'
result_body += '</tr>';
}
} else {
result_body += '<tr>';
result_body += '<td style=\"col-xs-12\"><b>No Data. Try again, or Contact IT Support.</b></td>';
result_body += '</tr>';
}
$('#result-table').html(result_body);
}
});
}
Like I said, the above works, but the problem comes forth when I click an element in my table. "getClickedUserObject()" below:
function getClickedUserObject(lettercode) {
if (lettercode != undefined) {
var users = scope[2];
var user = users["value"][lettercode];
$('#result-title').html(user.Title);
$('#result-name').html(user.Name);
$('#result-department').html(user.Department);
$('#result-email').html('' + work.WorkEmail + '');
$('#result-work-mobile').html(user.WorkPhoneMobile);
$('#result-work-landline').html(user.WorkPhoneLandline);
$('#result-private-mobile').html(user.PrivatePhone);
if (lettercode == scope[0]) {
$("#HidePrivate").show();
$("#HidePrivate").disabled = false;
$("#HidePrivate").checked = user.HiddenPrivatePhone;
} else {
$("#HidePrivate").hide();
$("#HidePrivate").disabled = true;
}
}
return false;
}
This function never fires, instead I get the error in the title, saying that whatever lettercode I would get from clicking a row is not defined. This is odd to me because looking in the Google Chrome inspector I see this:
So what gives?
I'm not familiar with your function, but maybe the argument should be a string? Looks like you don't have any quotes around it in the function call.
Like so:
result_body += '<tr onclick=\"getClickedUserObject(\'' + dict["value"][key].Initials + '\')\">';