Render HTML of an AJAX response - ajax

I'm using Select2 AJAX remote option to fetch data:
$('#t').select2({
ajax: {
url: '../ajax/results.php',
data: function (params) {
return {
search: params.term,
page: params.page || 1
};
}
}
});
So far so good, result are returned like this (please notice the <small> tag):
{
"results": [
{
"id": "1",
"text": "Doe Joe, <small>Mr.</small>"
},
{
"id": "2",
"text": "Smith Anne, <small>Mrs.</small>"
},
{
"id": "3",
"text": "Rossi Mario, <small>Mr.</small>"
},
...
],
"pagination": {
"more": false
}
}
In the <select>, the <small> tag is printed as-is, instead of being parsed.
Select2 docs says that HTML are not rendered by default and that the rendered result must be wrapped in a jQuery object to work, but no further example is given.
All the examples that involve templateResult, indeed, does not give feedback on how to pass AJAX result (i.e. https://select2.org/dropdown#templating )
Please, any help?

The templating example is right, I just need to wrap everything in a <span> tag for it to work:
function formatItem (item) {
if (!item.id) {
return item.text;
}
return $('<span>' + item.text + '</span>');
}
$('#t').select2({
ajax: {
url: '../ajax/results.php',
data: function (params) {
return {
search: params.term,
page: params.page || 1
};
}
},
templateResult: formatItem,
templateSelection: formatItem
});

Related

DataTable can not pass parameters from Ajax to ASP.NET MVC controller

I have this problem when trying to pass a string parameter from DataTable with Ajax to an ASP.NET MVC controller: the parameter is not being sent.
I tried many forms of "data:" options. Please help me, I think I'm missing something important.
When (as a test) I initialize the parameter at the beginning of the controller with ttt="CO" everything goes fine!
$('#tblVacation').DataTable({
"ajax": {
"url": '/Vacation/LoadData2',
"contentType": "application/json;charset=utf-8",
"type": 'GET',
"dataType": 'JSON',
"data" : ' { ttt: "CO" }'
"dataSrc": "",
},
"columns": [
{ "data": "vacationId", width: "5%" },
{ "data": "operatorId", width: "3%" },
{ "data": "operator", width: "10%" },
{ "data": "type", width: "3%" },
]
});
And the controller is:
[HttpGet]
public ActionResult LoadData2(string ttt)
// ttt="CO";
{
List<Vacation> data = null;
try
{
data = DB.Vacations.Include(x => x.Operator).ToList();
var result = data.Select(x => new Vacation_VM
{
VacationId = x.VacationId,
OperatorId = x.OperatorId,
Vacation_doc = x.Vacation_doc,
Operator = x.Operator.Name,
Type = x.Type,
}).Where(m => m.Type == ttt);
return new JsonResult(result);
}
catch (Exception ex)
{
ViewBag.Message = ex.Message;
}
return new JsonResult(null);
}
I also tried with
var entity = {
ttt: "CO"
}
var dataToSend = JSON.stringify(entity);
and
"data": function () {
return dataToSend;
},
but it's still not working. I will need in the future to pass multiple parameters.
Thanks a lot, I will appreciate any advice.
Replace the ajax call part with the followings:
"ajax": {
type: 'GET',
url: '/Vacation/LoadData2',
data: { ttt: "CO" },
dataType: 'JSON',
async: true,
cache: false,
},

Select2 - Change name="param" to other name for post request

I have the following search box for getting data from backend:
<select class="form-control kt-select2" id="megaagent_rainmaker_select" name="param" multiple="multiple" style="width: 100%"></select>
This is my select2 javascript code:
var rainmakerSelect = function () {
// Private functions
var demos = function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// multi select
$('#megaagent_rainmaker_select').select2({
language: "es",
placeholder: "Escriba y seleccione",
allowClear: true,
maximumSelectionLength: 1,
ajax: {
url: '/admin/megaagent/getrainmaker',
type: "get",
dataType: 'json',
delay: 150,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
return {
init: function () {
demos();
}
};
}();
jQuery(document).ready(function () {
rainmakerSelect.init();
});
I get results returned and I can select one without problem.
After I select a value, I send update request to backend, this is my payload:
{
"_token": "bPl0hZJQxw5wAxNCqVOOKqrXXwkD5AZZOFPumrpC",
"mc_id": "11",
"megaagent_id": "16",
"megaagent_name": "David Cortada",
"megaagent_business_name": "bsame cambio",
"megaagent_uma_id": "umaid",
"megaagent_api_key": "apikey",
"param": "963",
"megaagent_phone_number": "phone",
"megaagent_email": "email",
"megaagent_address": "address",
"megaagent_facebook": "fb",
"megaagent_instagram": "inst",
"megaagent_twitter": "twi",
"megaagent_linkedin": "link",
"megaagent_image": "image",
"megaagent_status": "Activo"
}
What I want to achieve is to change param name to other on post request (example: "megaagent_rainmaker_id" = "963",.
I changed it in <select name="param"> but that breaks the search, no results are returned when I type in search box.
Does anyone knows the solution for this?
Regards

Datatables: Button for Showing Photo for Each Filename

I am very new to Datatables and this might be simple, but surely I am missing something. I am trying to create a button column that uses the filename of each row and uses it to make an ajax call to display a picture on click. What I get wrong is that, every button of the column displays the same image, and not the image of the filename for each row. Here is the code:
$.ajax ({
url: "http:// ...... /Services/DBPrintDatatable?customer_id=" + projectid,
type: "GET",
dataType: 'json',
async: false,
success: function(data) {
$('#projectsdt').show();
projectsTable = $('#projectsdt').DataTable({
"pageLength": 10,
"data": data,
"scrollX": true,
"aaSorting": [],
"columns": [
{ "data": "upload_date" },
{ "data": "filename" },
{ "data": "uploader" },
{ "data": "upload_place" },
{ "data": "is_ok" },
{ "data": "custom_verdict" },
{
data: { "data": "filename" },
render: function ( data, type, row ) {
return "<a data-fancybox='gallery' class='btn btn-success' href='http://......./Services/DBShowImage?filename='+ { 'data': 'filename' }>Show</a>";
}
},
] ,
});
Thank you in advance!
If the image url required is like
http://......./Services/DBShowImage?filename=filenameFromData
Then you should generate it first inside the render like below code
href='http://......./Services/DBShowImage?filename="+ row.filename+"';
render: function ( data, type, row ) {
return "<a data-fancybox='gallery' class='btn btn-success' href='http://......./Services/DBShowImage?filename="+ row.filename+"'>Show</a>";
}

ExtJS: How to hide specific data on store with filtering?

I want to hide a record on Grid that returns from server.
I've setted a filter on store and can reach that specific data but how I'll handle to hide/ignore this record?
fooStore: {
....
filters: [
function(item) {
let me = this;
let theRecord = item.data.status === MyApp.STATUS; //true
if (theRecord) {
console.log(theRecord); //True
console.log("So filter is here!!")
//How to hide/ignore/avoid to load this specific data record to load Grid??
}
}
]
},
Returned JSON;
{
"success": true,
"msg": "OK",
"count": 3,
"data": [
{
//Filter achives to this record and aim to hide this one; avoid to load this record.
"id": 102913410,
"status": "P"
},
{
"id": 98713410,
"status": "I"
},
{
"id": 563423410,
"status": "A"
}
]
}
I can't save my fiddle cause i don't have sencha forum's account so i give you my code :
Ext.application({
name : 'Fiddle',
launch : function() {
var model = Ext.create('Ext.data.Model', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'status', type: 'string'},
]
});
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
model: model,
proxy: {
type: 'ajax',
url: 'data.json',
reader: {
type: 'json',
rootProperty: 'data'
}
},
filters: [function(item) {
if (item.data.status === "P") {
return true;
}
else {
return false;
}
}],
listeners: {
load: {
fn: function() {
console.log(this.getRange());
}
}
}
});
}
});
Also i create data.json like this :
{
"success": true,
"msg": "OK",
"count": 3,
"data": [{
"id": 102913410,
"status": "P"
}, {
"id": 98713410,
"status": "I"
}, {
"id": 563423410,
"status": "A"
}]
}
I thinks it's near to you'r code and after the loading of the store the filter work as you can this :
Here is sencha fiddle link : https://fiddle.sencha.com/#view/editor
If this can't work, i don't understand what the fuck doing...

InvalidPathException: No action config found for the specified url

I am getting below error as Ajax call response.
Below is the response body for Ajax call.
Apache Tomcat/7.0.61 - Error report
HTTP Status 500 - org.apache.struts.chain.commands.InvalidPathException: No action config found for the specified url.type Status reportmessage org.apache.struts.chain.commands.InvalidPathException: No action config found for the specified url.description The server encountered an internal error that prevented it from fulfilling this request.Apache Tomcat/7.0.61
Is it something to do with JRE 7?
Here is the JavaScript code from my JSP file.
I have defined a table in my JSP file which is referenced here.
function showLogHistory() {
var questionId = document.getElementById('txtQuestionId').innerHTML;
var url = "myAction.do?dispatchMethodName=showmyAudit&questionId="+questionId;
if ( $.fn.DataTable.isDataTable('#tblmyAudit') ) {
$('#tblmyAudit').DataTable().destroy();
}
$('#tblmyAudit').DataTable( {
"initComplete": function(settings, json) {
$("#tblmyAudit tbody tr.data-in-table").each(function () {
var i=0;
$(this).find('td').each(function (index) {
var currentCell = $(this);
var nextCell =
$(this).closest('tr').next('tr').find('td').eq(i).length > 0 ?
$(this).closest('tr').next('tr').find('td').eq(i) : null;
if ( currentCell.text() !== nextCell.text()) {
currentCell.css('backgroundColor', 'yellow');
}
i=i+1;
});
});
},
"ajax": {
"url": url,
"cache": true
},
"columns": [
{ "data": "questionId" },
{ "data": "Category" },
{ "data": "Area" },
{ "data": "question" },
{ "data": "answer" },
{ "data": "updated_by" },
{ "data": "updated_date" }
],
"scrollX": true,
"columnDefs": [ {
"targets": [ '_all' ],
"orderable": false
} ],
"createdRow": function( row, data, dataIndex ) {
$(row).addClass( 'data-in-table' );
}
} );
$('#detmyAudit').modal('show');
}
URL that gets generated for Ajax seems proper.

Resources