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 + '\')\">';
Related
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.
I want to display fontawesome icon if the user level is equal to 1 or etc. How can i do that in this code. i got an error if i used if else statement inside. Thanks in advance!
function show_product(){
$.ajax({
type : 'ajax',
url : '<?php echo site_url('User/userData')?>',
async : true,
dataType : 'json',
success : function(data){
var html = '';
var i;
var q = '';
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+data[i].create_at+'</td>'+
'<td>'+data[i].user_email+'</td>'+
'<td>'+data[i].user_name+'</td>'+
'<td>'+data[i].user_lastname+'</td>'+
'<td>'if (data[i].user_level == '1') {
++
}'</td>'+
'<td>'+data[i].status+'</td>'+
'</tr>';
}
$('#show_data').html(html);
}
});
}
You can do using the ternary operator
function show_product(){
$.ajax({
type : 'ajax',
url : '<?php echo site_url('User/userData')?>',
async : true,
dataType : 'json',
success : function(data){
var html = '';
var i;
var q = '';
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+data[i].create_at+'</td>'+
'<td>'+data[i].user_email+'</td>'+
'<td>'+data[i].user_name+'</td>'+
'<td>'+data[i].user_lastname+'</td>'+
'<td>'+ data[i].user_level==1?'<i class="fa"></i>':'<i class="fa"></i></td>'
+
'<td>'+data[i].status+'</td>'+
'</tr>';
}
$('#show_data').html(html);
}
});
}
The problem is most likely because the code don't know that you want run the if statement.
'<td>'if (data[i].user_level == '1') as you can see there is nothing separating the string <td> and the statement if (data[i].user_level == '1')
Try something like this:
function show_product() {
$.ajax({
type: 'ajax',
url: '<?php echo site_url('
User / userData ')?>',
async: true,
dataType: 'json',
success: function(data) {
var html = '';
var i;
var q = '';
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<td>' + data[i].create_at + '</td>' +
'<td>' + data[i].user_email + '</td>' +
'<td>' + data[i].user_name + '</td>' +
'<td>' + data[i].user_lastname + '</td>' +
'<td>';
if (data[i].user_level == '1') {
html += '<i class="fas fas-user"></i>'
}
html += '</td>' +
'<td>' + data[i].status + '</td>' +
'</tr>';
}
$('#show_data').html(html);
}
});
}
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 a bunch of jQuery functions which gets JSON data from a MySQL database and displays it on certain pages within my application.
i have about 15 of these functions that look similar to the below and i would like to tidy them up and convert them to one major function which returns data based on the variables passed to the function. IE getdata(subscriptions) would display the subscriptions.
My issue is i'm not sure how to pass the column names to the function from the ajax query and remove the value.column-name from the function.
Example function from application
function GetSubscriptions(){
$.ajax({
url: 'jsondata.php',
type: 'POST',
dataType:'json',
timeout:9000,
success: function (response)
{
var trHTML = '';
$.each(response, function (key,value) {
trHTML +=
'<tr><td>' + value+
'</td><td>' + value.subscription_name +
'</td><td>' + value.subscription_cycle +
'</td><td>' + value.subscription_cost +
'</td><td>' + value.subscription_retail +
'</td><td>' + value.subscription_profit +
'</td><td>' + value.subscription_margin +
'</td><td>' + value.subscription_markup +
'</td></tr>';
});
$('#subscription-results').html(trHTML);
},
});
}
Any help is very much appreciated as i'm fairly new to jQuery
You can refer to this code:
function GetSubscriptions(){
$.ajax({
url: 'jsondata.php',
type: 'POST',
dataType:'json',
timeout:9000,
success: function (response)
{
$('#subscription-results').html(parseColumns(response));
},
});
}
function parseColumns(columns) {
var html = '';
if (Object.prototype.toString.apply(columns) === '[object Array]') {
$.each(columns, function(key, value) {
html += parseColumn(value);
})
} else {
html += parseColumn(columns);
}
function parseColumn(column) {
var trHTML = '<tr><td>' + column + '</td>';
for (var key in column) {
trHTML += '<td>' + column[key] + '</td>'
}
trHTML += '</tr>';
return trHTML;
}
return html;
}
I have written some ajax code using an open source library to do jquery pagination.
when the page first loads, it properly queries and displays the first 25 records from my database. But all subsequent requests fail with a parse error.
I can't see anything different between the formatting of data in the first page vs. other pages.
I've tried to use JSON Lint but none of my json passes, even the query for page 1.
My json data looks like this:
"[{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\"and the final update\",\"number\":\"72212\",\"updatedname\":\"28112\",\"createdname\":\"conversion script\",\"user\":\"28507\",\"position\":\"1\",\"device_id\":\"2\",\"user_id\":\"2\",\"password\":\"Wh16dteaR\",\"updateddatetime\":\"2013-10-07 15:14:28\"},{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\"Bauer\",\"number\":\"72787\",\"createdname\":\"conversion script\",\"user\":\"28509\",\"position\":\"2\",\"device_id\":\"4\",\"user_id\":\"4\",\"password\":\"EHVOzIx1\"},{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\" Woosly\",\"number\":\"72822\",\"createdname\":\"conversion script\",\"user\":\"28510\",\"position\":\"3\",\"device_id\":\"5\",\"user_id\":\"5\",\"password\":\"IP8rsdOE\"}]"
And then I use the parseJSON method to convert the above string into an object.
Here's the main routine that makes the ajax call and parses:
$.ajax({
url: mypath + '?startpos=' + page_index * items_per_page + '&numberofrecordstograb=' + items_per_page + '&viewtype=json',
dataType: 'json',
success: function(data){
data = $.parseJSON(data); //converting to a javascript object vs. just string...
if (data !=null) {
for(var i=0;i<data.length;i++){
var deviceobj = data[i];
newcontent = newcontent + "<TR>";
newcontent=newcontent + '<TD>';
//add EDIT hyperlink
if ($("#editdevicesettings").val() == "true") {
var temp = $("#editlinkpath").val();
newcontent=newcontent + temp.replace("xxx",deviceobj["device_id"]) + ' ';
}
//add DELETE hyperlink
if ($("#deletedevice").val() == "true") {
var temp = $("#deletelinkpath").val();
newcontent=newcontent + temp.replace("xxx",deviceobj["device_id"]);
}
newcontent=newcontent + '</TD>';
newcontent=newcontent + '<TD>' + deviceobj["number"] +'</TD>';
newcontent=newcontent + '<<TD>' + deviceobj["user"] + '</TD>';
newcontent=newcontent + '<<TD>' + deviceobj["password"] + '</TD>';
if (deviceobj["name"]) {
newcontent=newcontent + '<TD>' + deviceobj["name"] + '</TD>';
}
else {
newcontent=newcontent + '<TD> </TD>';
}
newcontent=newcontent + '<TD>' + deviceobj["description"] + '</TD>';
newcontent = newcontent + "</TR>";
}// end for
// Replace old content with new content
$('#Searchresult').html(newcontent);
}//end if
},
error: function(request, textStatus, errorThrown) {
console.log(textStatus);
},
complete: function(request, textStatus) { //for additional info
//alert(request.responseText);
console.log(textStatus);
}
});
// Prevent click eventpropagation
return false;
}//end pageselectCallback()
I'm not sure how to go about troubleshooting this.
Any suggestions would be appreciated
I decided to reduce the number of records returned to one per page... to narrow down the offending record.
now that I know which record it is, i should be able to resolve problem.