How I get my info with jQuery? - javascript

What I'm trying to do is to fill a table with some info from JSON file big.json, I need to do this with jQuery.
It looks like this now but not working:
<div class="stink">
<table>
<tr>
<th>Car</th>
<th>fault1</th>
<th>fault2</th>
</tr>
<script>
$.getJSON( "data.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
</script>
</table>
</div>
the JSON file structure is:
{
"Mercedes": {
"fault1":"not working",
"fault2":"key issues"
},
"BMW": {
"fault1":"not starting",
"fault2":"control problem"
}
}
How can I parse in the table those info with JQUERY ?

As you have a table, you'd better not show your info with lists, but use the table. With this:
$.getJSON( "data.json", function( data ) {
$.each( data, function( key, obj ) {
var items = [];
items.push( "<td>" + key + "</td>" ); //Car name
items.push( "<td>" + obj.fault1 + "</td>" ); //fault1
items.push( "<td>" + obj.fault2 + "</td>" ); //fault2
$( "<tr/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( ".stink table" );
});
});
I tried to modify your code at little as possible so you understand it better.

Related

Search in .net MVC with AJAX. What can I do for the following code?

I want to do a search with AJAX. I simply did with the get method through passing search string in controller but that not I want
Below my controller code, where I get the search value from URL and return DATA (which is a list)
if (search != null)
{
if (search.ToLower().ToString() == "paid")
{
DATA = DATA.Where(a => a.Purchased_Price > 0).ToList();
}
else if (search.ToLower().ToString() == "free")
{
DATA = DATA.Where(a => a.Purchased_Price == 0).ToList();
}
else
{
DATA = DATA.Where(a => a.Purchased_File_Name.ToLower().StartsWith(search.ToLower()) || a.Purchased_Category.ToLower().StartsWith(search.ToLower()) || a.User1.Email.ToLower().StartsWith(search.ToLower()) || a.Purchased_Price.ToString().StartsWith(search)).ToList();
}
ViewBag.SoldList = DATA.ToPagedList(page ?? 1, pageSize); *this is what I actually did*
return Json(DATA , JsonRequestBehavior.AllowGet); *this is trial I do not know this work or not*
}
Below is the script which I wrote in view. Where I am going wrong? I'm not aware of that. I want whatever list comes with the help of whatever search I entered. To be printed in the table. Table is just above this script; I don't think it's needed so I did not include that.
<script>
$(document).ready(function () {
$("#search_button").on("click", function () {
var search_value = $("#searchText").val();
alert(search_value);
var SetData = $("#tabledata"); *tabledata is id of tbody tag *
SetData.html("");
console.log("setddata");
console.log(SetData);
$.ajax({
type: "get",
url: "/Home/MySoldNotes?search=" + search_value, *home is controller, mysoldnotes is action*
contentType: "application/ json; charset = utf - 8",
dataType: "html",
success: function (result) {
console.log("result");
console.log(result);
$.each(result, function (index, value) {
var data = "<tr>" +
"<td>" + value.NoteDetail.File_Name + "</td>" +
"<td>" + value.Purchased_Category + "</td>" +
"<td>" + value.User1.Email + "</td>" +
"<td>" + value.NoteDetail.Sell_Price + "</td>" +
"<td>" + value.Req_Solved_Date + "</td>" +
"</tr>"
SetData.append(data);
});
},
error: function (err) {
alert("Error aa gai");
console.log(err.responseText);
}
});
});
});
</script>
You must pass object to controller from ajax call. Example
<script>
$(document).ready(function () {
$("#search_button").on("click", function () {
var objParam = new Object();
objParam.search_value = $("#searchText").val();
$.ajax({
type: "POST",
url: "/Home/MySoldNotes"
contentType: "application/json; charset = utf-8",
data: JSON.stringify(objParam)
success: function (result) {
console.log("result");
console.log(result);
$.each(result, function (index, value) {
var data = "<tr>" +
"<td>" + value.NoteDetail.File_Name + "</td>" +
"<td>" + value.Purchased_Category + "</td>" +
"<td>" + value.User1.Email + "</td>" +
"<td>" + value.NoteDetail.Sell_Price + "</td>" +
"<td>" + value.Req_Solved_Date + "</td>" +
"</tr>"
SetData.append(data);
});
},
error: function (err) {
alert("Error aa gai");
console.log(err.responseText);
}
});
});
});
</script>
Then in your controller
public JsonResult MySoldNotes(string search_value)
{
// Do whatever and return json as result
}
List<BuyerReq> DATA = dc.BuyerReqs.Where(a => a.seller_id == ab && a.Status == true).AsQueryable().ToList();
return Json(DATA, JsonRequestBehavior.AllowGet);
while returning from the controller I am getting an error(not success my AJAX call).
but when I am doing this for testing purpose :
var aa = "checking"; return Json(aa, JsonRequestBehavior.AllowGet);
this works. I am not getting the exact error.

Getting data from JSON file based on clicked item by id

Because my other question, didn't solved my issue, and i tried everything what i know, and every time i am getting more stuck. Please combine this question with my other.
I am building my movie library.And i have two pages, index and movie.html.
Index.html will a page where will display movie items, each item, will have a name, a picture, score, short summary and director and screenplay names.And, also i will have a name from author, if the movie is based from book. All of that is taken from JSON file, that i have created locally.
In other html page, movie.html, i am planning to have more fancy design with more information. Like:wins, synopsis,cast and their characters, etc.
But here is the problem i am facing.
What I have tried:
I have this so far in
index.html
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
for ( var key in data[ i ] ) {
if ( key === "novel" ) {
$( '#jsonLoad' ).append( '<a href="movies.html?id='+data[i].id'" class="itemsHolder">' +
"<div class="titleHolder">" +
"<h2>" + data[ i ].name + "</h2>" +
"</div>" +
"<div class="novelAuthor">" + "<p class="NovelTxt">" + "Novel by" + " " + data[ i ].novel +"</p>" + "</div> " +
"<div class="posterHolder">" + data[ i ].posterPath + "</div>" +
"<div class="summaryShort">" + data[ i ].summary + "</div>" +
"<div class="raiting"><p>" + data[ i ].imdb + "</p></div><div class="genderMovie"> " + data[ i ].gender + "</div> " +
"<div class="directorNdScreen">" + 'Directed by ' + " <p class="director">" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class="screenplay">" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>" )
}
}
if(!data[i].novel){
$( '#jsonLoad' ).append( '<a href="movies.html?id='+data[i].id+'" class="itemsHolder">' +
"<div class="titleHolder">" +
"<h2>" + data[ i ].name + "</h2>" +
"</div>" +
"<div class="posterHolder">" + data[ i ].posterPath + "</div>" +
"<div class="summaryShort">" + data[ i ].summary + "</div>" +
"<div class="raiting"><p>" + data[ i ].imdb + "</p></div><div class="genderMovie"> " + data[ i ].gender + "</div> " +
"<div class="directorNdScreen">" + 'Director by ' + " <p class="director">" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class="screenplay">" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>" )
}
}
} )
} );
My JSON file, i have 20 objects, i will post just 2.
[
{
"id": 1,
"name": "Harry potter and the Sorcerer's Stone",
"year": 2001,
"movieStill" : " <img src='imgsMovie/HP1/StillPhoto/StillPhotoBackground.jpg'/>",\
},
{
"id": 2,
"name": "Harry potter and the Chamber of Secrets ",
"year": 2001,
"movieStill" : " <img src='imgsMovie/HP2/StillPhoto/StillPhotoBackground.jpg'/>",\
}
]
And my movie.html looks like this.
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
$( '.MovieInfo' ).append(
"<div class="imgStill">" + data[ i ].movieStill + "</div>"
)
}
} );
} );
I know in my movie.html i loop in every object.
How can i write an if statement, that will take per one object with own id, and display what is there.
Here, when i click on Harry potter 1 item, i got two images, from hp1 and hp2,
i just want to show only the one value from item i have clicked. And this means also for the rest of the properties, like different director etc, just to name a few.
It looks like in your movie.html you are just appending the images to .MovieInfo, which would not separate them out but have them all lumped together. You can instead read the id of from the data argument and only display the id associated with the movie you clicked.
Since you are already passing in a GET query to the url (movies.html?id=) you can just grab the value of id from the GET query and start with that (let's call it getID() for now). Afterwards just wrap the .MovieInfo append statement with an if statement checking the data argument for that value.
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
if (data[i].id === getID()) {
$( '.MovieInfo' ).append(
"<div class="imgStill">" + data[ i ].movieStill + "</div>"
)
}
}
});

get selected row id jquery datatable row selection

i cannot get selected row id. I'm using datatable row selection. I'm getting [],[""] in console log. I have looked for other questions on SO and tried but no help
My javascript code is
$(document).ready(function () {
var selectedids = [];
var otable = $('#Table1').DataTable({
"bSort": false,
"rowCallback": function (row, data) {
if ($.inArray(data.DT_RowId, selectedids) !== -1) {
$(row).addClass('selected');
}
}
});
$('#Table1 tbody').on('click', 'tr', function () {
var id = this.id;
var index = $.inArray(id, selectedids);
var ids = $.map(otable.rows('.selected').data(), function (item) {
return item[0]
});
console.log(ids)
if (index === -1) {
selectedids.push(id);
console.log(selectedids);
} else {
selectedids.splice(index, 1);
}
$(this).toggleClass('selected');
});
});
I'm filling up my datatable with json data from controller in mvc
$('#ID').change(function () {
$("#t1 tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("")',
dataType: 'json',
data: { id: $("#ID").val() },
success: function (data) {
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td>" + item.id + "</td>"
+ "<td>" + item.yyy + "</td>"
+ "<td>" + item.aaa + "</td>"
+ "<td>" + item.eee + "</td>"
+ "<td>" + item.yyygg + "</td>"
+ "</tr>";
$('#Table1 tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
You could spare yourself a lot of pain, if you used dataTables select extension :
var table = $('#example').DataTable({
select: {
style: 'multi'
}
})
var selectedIds = [];
table.on('select.dt', function(e, dt, type, indexes) {
selectedIds.push(indexes[0]);
console.log(selectedIds);
})
table.on('deselect.dt', function(e, dt, type, indexes) {
selectedIds.splice(selectedIds.indexOf(indexes[0]), 1);
console.log(selectedIds);
})
demo -> http://jsfiddle.net/0w1p7a3s/

Datables Searching / Filtering with rendered data

I am trying to apply filtering to a dataTables table using select boxes. I found the following code which allows me to setup the select boxes and filter based on the column data:
https://datatables.net/examples/api/multi_filter_select.html
This code worked perfectly, however I am now using the render method to pull all the columns together into one. We are doing this so we can style each row to create a single 'Ticket'.
Unfortunately now the filtering does not work. I imagine it may be a result of the columns no longer displaying but would appreciate some direction and help :)
Current Code:
$('#ticket_list').DataTable( {
"columnDefs": [
{
"render": function ( data, type, row ) {
return '<span class="client-data"> ' + data + ' </span>'
+ '<span class="priority-data"> ' + row[1] + ' </span>'
+ '<span class="status-data"> ' + row[2] + ' </span>'
+ '<div class="subject-data"> ' + row[3] + ' </div>'
+ '<i class="fa fa-user"></i><span class="agent-data"> ' + row[4] + ' </span>'
+ '<span class="date-data"> ' + row[5] + ' </span>';
},
"targets": 0
},
{ "visible": false, "targets": [ 1,2,3,4,5 ]}
],
"columns": [
{ "title": "" }
],
"pageLength": setPageLength(),
"dom": '<"#search-box"f> rt <"#pagination.col-xs-12"p> <"#table-information.col-xs-12"i>',
language: {
search: "_INPUT_",
searchPlaceholder: "Search"
},
initComplete: function () {
this.api().columns([0,1,2]).every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( ".ticket-filtering" )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
console.log(val)
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
},
} );
CAUSE
You render function returns HTML string unconditionally disregarding the type argument but this function is used to get the data for multiple purposes: displaying, ordering, filtering, type detection.
SOLUTION
Use type detection in render function and only return HTML when data is needed to be displayed (type === 'display').
"render": function ( data, type, row ) {
if(type === 'display'){
data = '<span class="client-data"> ' + data + ' </span>'
+ '<span class="priority-data"> ' + row[1] + ' </span>'
+ '<span class="status-data"> ' + row[2] + ' </span>'
+ '<div class="subject-data"> ' + row[3] + ' </div>'
+ '<i class="fa fa-user"></i><span class="agent-data"> ' + row[4] + ' </span>'
+ '<span class="date-data"> ' + row[5] + ' </span>';
}
return data;
},
DEMO
See this jsFiddle for code and demonstration.

Hyperlinking URL value in JSON file

How can I set the URL value in my JSON file to a hyperlink when displayed in the table?
JSON
{
"one": "http://urltovideo.mp4",
"two": "The second list item",
"three": "The third list item"
}
jQuery
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<div class='panel panel-default'><div class='panel-heading'>" + key + "</div><div
class='panel-body'><a href=''>" + val + "</a></li></div></div>" );
});
$( "<ol/>", {
"class": "my-new-list",
html: items.join( "" )
}).fadeIn(900).appendTo( "body" );
});
You need to check if val is containing a link:
$.each( data, function( key, val ) {
var link = (val.indexOf('http') > -1) ? '' + val + '' : val;
items.push( '<div class="panel panel-default"><div class="panel-heading">' + key + '</div><div
class="panel-body">' + link + '</li></div></div>');
});
Also, for cleaner code, you should use " for HTML attributes like class="..." and ' for Javascript strings, like: '<a href="' + val + '">'
See jsFiddle

Categories

Resources