Pulling data with spaces in json [duplicate] - javascript

This question already has answers here:
Access JSON output with spaces
(4 answers)
Closed 3 months ago.
I can't extract the data with spaces in the area that I have shown with the red pen, how can I do this?
$.ajax({
url: "../api/api.php",
type: "POST",
data: {
tc: $("#tcx").val(),
},
success: (res) => {
if (res) {
var json = JSON.parse(res);
$('tbody').html("");
$.each(json, function(key, value) {
$('tbody').append('<tr>' +
'<td>' + value.YAKINLIK + '</td>' +
'<td>' + value.TC + '</td>' +
'<td>' + value.ADI + '</td>' +
'<td>' + value.SOYADI + '</td>' +
'<td>' + value.DOGUM TARIHI + '</td>' +
'<td>' + value.NUFUS IL + '</td>' +
'<td>' + value.NUFUS ILCE + '</td>' +
'<td>' + value.ANNE ADI + '</td>' +
'<td>' + value.ANNE TC + '</td>' +
'<td>' + value.BABA ADI + '</td>' +
'<td>' + value.BABA TC + '</td>' +
'</tr>');
});
} else {
alert("Hata oluştu!");
return;
}
},
error: () => {
alert("Hata oluştu!");
}
});
}
I tried to parse but without success
enter image description here

If you're just trying to read out the value from an object, based on a key that has spaces in it, you can use this syntax:
const myObject = { withoutSpaces: 1, "with spaces": 2 };
const valueOne = myObject.withoutSpaces;
const valueTwo = myObject["with spaces"];
So in your case you want to use something like:
value["DOGUM TARIHI"]

Related

How do I access the value of a td (x3) of the same tr (x1), if I click on the tr (x1 of td (x2))?

How do I access the value of a td (x3) of the same tr (x1), if I click on the tr (x1 of td (x2))?
$(document).ready(function () {
$.ajax({
url: '/api/Usuario/GetPermisosRolPorUsuario',
method: 'GET',
dataType:'JSON',
data: { NitEmpresa,NombreUsuario },
headers: {
'Authorization': 'Bearer '
+ sessionStorage.getItem("accessToken")
},
success: function (data) {
debugger
$('#tblBody').empty();
$.each(data, function (index, value) {
var row =
$('<tr>'
+'<td id="IdUsuario">'+ value.IdUsuario + '</td>'
+ '<td id="RolId">' + value.RolId + '</td>'
+ '<td id="Estado" >' + value.Estado + '</td>'
+ '<td>' + value.Rol + '</td>'
+ '<td>' + value.DescripcionRol + '</td>'
+ '<td>' + value.NombreUsuario + '</td>'
+ '<td>' + value.FullName + '</td>'
+ '<td>' + value.licenciaEmpresa + '</td>'
+ '<td>' + value.RazonSocial + '</td>'
+ '<td>' + value.NitEmpresa + '</td>'
+ '<td>' + value.Correo + '</td>'
+ '<td>' + value.Celular + '</td>'
+ '<td>' + formatDate(value.licenciaFechaExpire) + '</td>'
);
$('#tblData').append(row);
});
Thank you, I managed to access the brothers 'td', as follows:
$('tr td:nth-child(3)', '#tblData').click(function () {
returns to the father to look for his brothers
var $thisRow = $(this).closest('tr')
brothers td
IdUsuario = $('td:first', $thisRow).text();
RolId = $('td:nth-child(2)', $thisRow).text();
Estado= $('td:nth-child(3)', $thisRow).text();
//an alert to print the values
alert(IdUsuario + '-' + RolId + '-' + Estado);
});
},
error: function (jQXHR) {
toastr.error('Sistemas Infinitos Informa: '+jQXHR.responseText);
}
});
});
$.each(data, function (index, value) {
var row =
$('<tr>'
+'<td id="IdUsuario">'+ value.IdUsuario + '</td>'
+ '<td id="RolId">' + value.RolId + '</td>'
+ '<td id="Estado" >' + value.Estado + '</td>'
First, each element in the DOM should have a unique id. By repeating the same ID multiple times, I'm not sure your on('click') events will attach in all browsers and return the value you are looking for. Instead, your click event should look something like this:
$('tr', '#tblData').click(function () {
var id1 = $('td:first-child', this).text();
var id2 = $('td:nth-child(2)', this).text();
var id3 = $('td:nth-child(3)', this).text();
...
}
or if you only want to allow clicking on the first TD:
$('tr td:first-child', '#tblData').click(function () {
var $thisRow = $(this).closest('tr')
var id1 = $(this).text();
var id2 = $('td:nth-child(2)', $thisRow).text();
var id3 = $('td:nth-child(3)', $thisRow).text();
...
}

how to filter data on button click and display on the same tab without reloading the page

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>' );
});
})
});

how to append value in td

I am getting dynamic values in table using Datatables. I am getting my desired value in alert, but I want to show that value in table. for that purpose I used .append, .html but no luck. How can I show = my value in <td>. I also try to gave gave td an id e.g <td id="files">
here is my code:
function format(d) {
var str = d.files;
var myarr = str.split(",");
for (var i = 0; i < myarr.length; i++) {
alert(myarr[i]);
$("#files").append("<a href='/uploads/" + myarr[i] + "'>" + myarr[i] + "</a>");
}
// `d` is the original data object for the row
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr>' +
'<tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr>' +
'<tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr>' +
'<tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr>' +
'<tr>' +
'<td>Files:</td>' + '<td id="files">'
'</td>' +
'</tr>' +
'</table>';
}
I hope it will be a easy fix.any help will be highly appreciable
Your issue is that the #files element doesn't exist at the point you attempt to select it. You need to first add that HTML string to the DOM, then append to it.
Alternatively, you could amend the logic which creates that HTML string to include the output of your for loop, like this:
function format(d) {
var str = d.files;
var filesHtml = str.split(",").map(function(file) {
return '' + file + '';
});
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr><tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr><tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr><tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr><tr>' +
'<td>Files:</td>' +
'<td id="files">' + filesHtml + '</td>' +
'</tr>' +
'</table>';
}
var html = format({
person: 'John Smith',
phone: '1234 567890',
web: 'http://google.com',
ttype: 'Foobar',
files: 'a.jpg,b.jpg'
});
$('div').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

Adding a href to an Ajax generated table in html

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>

how to repeat the rows dynamically in .html() jqueryajax

In the below code am having one table with values from database.After executing the the query if am having 5 values am getting only the first value in my table(inside pop up).in this html() function how can i add the foreach and type of parametrs for for each,
i used ajax,json,jquery
My code is;
success: function (msg) {
var data = $.parseJSON(JSON.stringify(eval("(" + msg.d + ")")));
$('<div></div>')
.appendTo('body')
.html('<div><b>SHAREHOLDER DETAILS</b></br>' + data.Id + '</div>' +
'<div>' + data.name + '</div>' +
'<div>' + data.Id + '</div>' +
'<table border="1" style="background-color:silver;"><tr>' +
'<td>' + 'OwnedBy' + '</td>' +
'<td>' + 'ShareClass' + '</td>' +
'<td>' + 'EffectiveInterest' + '</td>' +
'<td>' + 'DeemedInterest' +'</td>' +
'<td>' + 'SharesOwned' + '</td>' +
'<td>' + 'SharesIssued' + '</td>' +
'</tr>' +
'<tr>' +
'<td>' + data.Id +'</td>' +
'<td>' + data.share + '</td>' +
'<td>' + data.effect + '</td>' +
'<td>' + data.deemed + '</td>' +
'<td>' + data.owned + '</td>' +
'<td>' + data.issued + '</td>' +
'</tr>' +
'</table>')
.dialog({
modal: true,
title: '<div>' + data.Id + '</div>',
zIndex: 10000,
autoOpen: true,
position: ['right', 'top'],
width: 'auto',
height: 'auto',
modal: false,
resizable: false,
closeOnEscape: false,
show: "slide",
hide: "explode",
close: function (event, ui) {
$(this).remove();
}
});
},
I don't know how much effort you've put into solving this on your own, but in the interest of fairness, I'll explain the thought process a bit. What you need to consider is conceptualizing and separating the "rows" from the "general entity", eg, "I have a table with rows which contain data".
The loop itself runs when creating the rows, and has to be performed as a separate action from creating the table itself. Even if you embed the loop logic into the table construction itself (as far as the markup generation itself goes, which I consider bad practice), you still have to consider each row as the result of a loop run, distinct from the table, thead, and tbody. Note, even with the rows (tr), you have another (potential) loop requirement in each cell in the row (td). In this case you don't need a loop at that level, but that points to conceptualizing the rudiments of loop design and utilization.
Here is a method using jQuery element caching and a jQuery.each() loop, which is a type of foreach loop. Note, in Javascript there is no dedicated foreach loop; there is, however, for(var i in object), which allows you to iterate over an object of this kind.
$(document).ready(function(){
var $table = $('<table>'),
$tbody = $('<tbody>'),
$thead = $('<thead>' +
'<tr>' +
'<th>OwnedBy</th>' +
'<th>ShareClass</th>' +
'<th>EffectiveInterest</th>' +
'<th>DeemedInterest</th>' +
'<th>SharesOwned</th>' +
'<th>SharesIssued</th>' +
'</tr>' +
'</thead>'),
$tr = $('<tr>'),
data = {
grp1: {
Id: 'id1',
share: 'share',
deemed: 'deemed',
effect: 'effect',
owned: 'owned',
issued: 'issued'
},
grp2: {
Id: 'id2',
share: 'share',
deemed: 'deemed',
effect: 'effect',
owned: 'owned',
issued: 'issued'
},
grp3: {
Id: 'id3',
share: 'share',
deemed: 'deemed',
effect: 'effect',
owned: 'owned',
issued: 'issued'
}
};
$table
.append($thead, $tbody)
.appendTo(document.body);
jQuery.each(data, function(i, val) {
$tr.clone()
.appendTo($tbody)
.append(
'<td>' + val.Id +'</td>' +
'<td>' + val.share + '</td>' +
'<td>' + val.effect + '</td>' +
'<td>' + val.deemed + '</td>' +
'<td>' + val.owned + '</td>' +
'<td>' + val.issued + '</td>'
);
});
});
http://jsfiddle.net/YFwTe/
You need some sort of iterator function, as you have it the code will only pull the first value.
My suggestion would be to use .each:
var element = $('<table></table>').appendTo('body');
jQuery.each(data, function(i, val) {
element.append(
'<tr>' +
'<td>' + val.Id +'</td>' +
'<td>' + val.share + '</td>' +
'<td>' + val.effect + '</td>' +
'<td>' + val.deemed + '</td>' +
'<td>' + val.owned + '</td>' +
'<td>' + val.issued + '</td>';
'</tr>';
);
});
Haven't tested it just because I don't have a data string, but hopefully that gets you close.

Categories

Resources