Javascript jquery mobile error [duplicate] - jquery-mobile

I am trying to populate a JQM ListView with a local JSON information. However, no list items are created. Any help would be appreciated. Here is my code:
JSON File Structure:
[
{
"name" : "test"
"calories" : "1000"
"fat" : "100"
"protein" : "100"
"carbohydrates" : "800"
},
{
"name" : "test2"
"calories" : "10000"
"fat" : "343"
"protein" : "3434"
"carbohydrates" : "4343"
}
]
HTML:
<div data-role="page" data-title="Search" id="searchPage">
<ul data-role="listview" data-inset="true" id="searchFood">
</ul>
</div>
JS:
(Updated)
$(document).on("pageinit", "#searchPage", function(){
$.getJSON("../JS/food.json", function(data){
var output = '';
$.each(data, function(index, value){
output += '<li>' +data.name+ '</li>';
});
$('#searchFood').html(output).listview("refresh");
});
});

First of all, the return JSON array is wrong, values (properties) should be separated by commas.
var data = [{
"name": "test",
"calories": "1000",
"fat": "100",
"protein": "100",
"carbohydrates": "800",
}, {
"name": "test2",
"calories": "10000",
"fat": "343",
"protein": "3434",
"carbohydrates": "4343",
}];
Second mistake, you should read value object returned by $.each() function not data array.
$.each(data, function (index, value) {
output += '<li>' + value.name + '</li>';
});
jQueryMobile only enhances the page once when it is loaded. When new data is added dynamically to the page, jQueryMobile must be made aware of the data for the data to be enhanced.
After extracting data from JSON array, append them then refresh listview to restyle newly added elements.
$('#searchFood').html(output).listview("refresh");
Demo

Related

DataTables warning: table id=patients - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

I have Issue with this Datatable Jquery i get this Error:DataTables warning: table id=patients - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
I do this Function on controller:
[HttpGet]
public JsonResult LoadPatients()
{
// Browser list
var totalPatientsList = _unitOfWork.Patients.GetPatients();
var filteredResult = from b in totalPatientsList
select new[] {b.Jeton, b.Nom, b.TelePhone, b.Adresse, b.Villes.Nom,b.Id.ToString()};
return Json(new
{
data =filteredResult
},
JsonRequestBehavior.AllowGet);
}
and i call on index view :
$(document).ready(function () {
var table = $("#patients").DataTable({
ajax: {
url:"/patients/LoadPatients",
dataSrc: ""
},
columns: [
{
data: "jeton"
},
{
data: "nom"
},
{
data: "telephone",
render: function (data) {
return data.toString().replace(
/(\d\d\d)(\d\d\d)(\d\d\d\d)/g, '$1-$2-$3');
}
},
{
data: "adresse"
},
{
data: "villes.nom"
},
{
data: "id",
render: function (data, type, patient) {
return "<a href='/patients/details/ " + patient.id + "' class='btn btn-default btn-xs'>" + "<i class='fa fa-folder'></i>View</a>" +
//"<button class= 'btn-link js-detail' data-detail-id=" + data + "><i class='fa fa-pencil-square'></i></button>" +
"<button class= 'btn btn-danger btn-xs js-delete' data-patient-id=" + data + "><i class='fa fa-trash-o'></i>Delete</button>";
}
}
]
});
I inspect result on chrome i get that:
{
"data": [
["0002020", "patienta", "0670707070", "Zone franche", "Tan", "1"],
["0002029", "tst", "0524242424", "Ma", "M", "10"]
]
}
How can i resolve this Issue thanks in advance
Your JSON does not have any labels - each row is just a data array, for example:
["0002020", "patienta", "0670707070", "Zone franche", "Tan", "1"]
This means you cannot use data labels like this:
data: "jeton"
because the label jeton does not exist in your JSON data.
So, instead, you can change all of these data:... values to title"... - for example:
title: "jeton"
This means that the first value in the array (which is "0002020") will appear in the first column of your table - and the column heading will be "jeton".
And then the second column in your table will contain "patienta" and will use the column heading of "nom" - and so on.
Here is my example using your data:
I think that is all you need to do to fix the issue.
Extra Notes:
Don't forget to update the ajax URL - it loos like you may have already done that.
You may also need to remove the following dataSrc: "" line from the ajax section, so it is this:
ajax: {
url:"/patients/LoadPatients"
},
but I am not sure. Try it both ways.

Datatable - Change row data from html to plain text

The rails application is using the datatable to populate the data which is received from the remote system ( using ajax call) . the things were working fine till the remote system was sending plain text. But now the system is sending the response data as html. Because of that the whole page formating is disturbed. How to display the html returned as it is in the datatable row? The code is as below. The html returned from remote system is displayed in message field.
var logs = window.location.pathname + '/logs.json';
var logTable = $("table").DataTable({
"oLanguage": {
"sSearch": "Search"
},
"paging": false,
"dom" : 't',
"order": [[0, "desc"]],
"ajax": {
"url": logs,
'dataSrc': function ( json ) {
return json;
}
},
"drawCallback": function(){
refreshProgressBar();
},
columns: [
{data : "created_at"},
{data : "level"},
{data : "message"},
],
});

Get order from KnockoutJS viewmodel based on Id

I'm trying to get an order from a KnockoutJS viewmodel, but having a hard time getting this done.
This is what the viewmodel looks like:
{"Orders":
[{"Id":16,"Status":2,
"Products":
[{"Id":14,"OrderId":16,"Price":5},
{"Id":15,"OrderId":16,"Price":10},
{"Id":16,"OrderId":16,"Price":20},
{"Id":17,"OrderId":16,"Price":30}]},
{"Id":17,"Status":2,
"Products":
[{"Id":18,"OrderId":17,"Price":0}]}
]}
This is one of my many tries:
var viewModel = ko.mapping.fromJS(#Html.Raw(Json.Encode(Model)));
ko.applyBindings(viewModel);
$(document).on("click", ".btnDetails", function () {
var oId = $(this).attr('id');
debugger;
var order = ko.utils.arrayFirst(viewModel.Orders(), function (item) {
return item.Id === oId;
});
});
How can I get the complete order with Id 16?
This is not an observableArray(), there are no mutations done. This will only serve as showing the details of an order in a Modal (Twitter Bootstrap).
It looks like your code should work just fine, except that your arrayFirst() function has an error. You should have
var order = ko.utils.arrayFirst(viewModel.Orders(), function(item) {
return item.Id() === oId;
});
Because you mapped your viewmodel properties, comparing the Id of item will still be comparing the ko function. You need to get the value and compare that directly. Once you've done that, order should be the first order that matches the id.
I'm not entirely clear on what you mean by the complete order. but have a look at this jsfiddle
EDIT
re-reading the question again its starting to make sense to me.
To get a reference to the order
add a selectedOrder observable to your viewmodel.
then add a function showOrder that takes in an the order. and set the selectedOrder to the incomming item
on the tag that contains the order data-bind to the click.
and that should get you pretty close to what I believe you need as the selectedOrder will contain all the products as well for display purposes
HMTL
<ul class="list-group" data-bind="foreach: data.Orders">
<li class="list-group-item">
<h3 data-bind="click: $parent.showItem">
Order <span data-bind="text: Id"></span>
</h3>
</li>
</ul>
JS
var model = {
"Orders": [{
"Id": 16,
"Status": 2,
"Products": [{
"Id": 14,
"OrderId": 16,
"Price": 5
}, {
"Id": 15,
"OrderId": 16,
"Price": 10
}, {
"Id": 16,
"OrderId": 16,
"Price": 20
}, {
"Id": 17,
"OrderId": 16,
"Price": 30
}]
},
{
"Id": 17,
"Status": 2,
"Products": [{
"Id": 18,
"OrderId": 17,
"Price": 0
}]
}]
};
var selectedOrder = ko.observable();
function showItem(item) {
selectedOrder(item);
alert("Selected Order: " + item.Id());
}
var vm = {
data: model,
showItem: showItem,
selectedOrder: selectedOrder
};
$(document).ready(function () {
var viewModel = ko.mapping.fromJS(vm);
ko.applyBindings(viewModel);
});

DataTables Error : “Requested unknown parameter”

var headers = [{ "mDataProp": "Agents" },{ "mDataProp": "Buyer" },{ "mDataProp": "Date" }];
$(document).ready(function () {
$('#data-table').dataTable({
"bFilter": false,
"bLengthChange": false,
"iDisplayLength": 25,
"bJQueryUI": true,
"bServerSide": true,
"bProcessing": true,
"sPaginationType": "full_numbers",
"aoColumns": headers,
"sAjaxSource": '/report/TestPaging',
});
});
If I remove the aoColumns from my code the datatable is generated normally, but when I add aoColumns I get :
DataTables warning (table id = 'data-table'): Requested unknown parameter 'Agents' from the data source for row 0
HTML:
<table id="data-table">
<thead>
<tr>
<th>tmp</th>
<th>tmp</th>
<th>tmp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
How can I configure header names? I need them for my sorting.
Do they have to be same as in "th" tags?
Json response from my controller is ok because it renders fine when I remove aoColumns
I have string[][](var data) with 3 strings in each line and return it as
Json(new{
sEcho = param.sEcho,
iTotalRecords = visitRepository.Query.Count(),
iTotalDisplayRecords = visitRepository.Query.Count(),
aaData = data
}, JsonRequestBehavior.AllowGet);
The error you are experiencing is caused by a mismatch between the contents of the JSON and your aoColumns definition. The names you are targeting in aoColumns must be exactly the same as those in the JSON, and the length of each object in the JSON must be equal to the number of columns in the original HTML table. See the docs for clarification. In your case, the JSON should look like this :
[{
"Agents": "tM4Ga0zX",
"Buyer": "ZKwMEiIa",
"Date": "K3lS2yn9"
},
...]
...And your JSON doesnt follow that scheme. If you are not using aoColumns, then the data is inserted by index, not by name - and that is why it is working for you without it.
You configure header names (titles) by the sTitle property :
aoColumns: [
{ mDataProp: "Agents", sTitle : "Agents" },
{ mDataProp: "Buyer", sTitle : "Buyer" },
{ mDataProp: "Date", sTitle : "Date" }
]
see this demonstration based on your question -> http://jsfiddle.net/kLR7G/

Jquery Autocomplete

iam using jquery autocomplete in asp.net project. it's not working. do you have any idea. the code is given below.
<script type="text/javascript">
$(function () {
$('#clientabbrev').val("");
$("#clientstate").autocomplete({
source: "clientstates.aspx",
select: function (event, ui) {
$('#clientstateid').val(ui.item.clientid);
$('#clientstateabbrev').val(ui.item.clientabbrev);
}
});
$("#clientstate_abbrev").autocomplete({
source: "clientstatesabbrev.aspx",
minLength: 2
});
});
</script>
problem is states.aspx returning the data but it is not showing in the jquery autocomplete control.
Your server needs to return a JSON serialized array of objects with properties id, label, and value. E.g. :
[ { "id": "1", "label": "Mike Smith", "value": "Mike Smith" }, { "id": "2", "label": "Bruce Wayne", "value": "Bruce Wayne" }]
Can you confirm with firebug or Fiddler that your server is returning the correct response?
If you're having trouble serializing your data in C#, you can try using JavaScriptSerializer like this:
var result = from u in users
select new {
id = u.Id,
value = u.Name,
label = u.Name
};
JavaScriptSerialier serializer = new JavaScriptSerializer();
var json = serializer.Serialize(result);
// now return json in your response

Resources