This is my javascript function which accepts id as a signature and alert the selected text of dropdown
function sendata(id) {
$(document).ready(function () {
$(id).on('change', function () {
var ctlevel = $(id).find("option:selected").text();
var selectedValue = $(id).val();
alert("Selected Text: " + ctlevel + " Value: " + selectedValue);
});
});
}
here ,i called the function but it didn't work and it did not alert the text message of dropdown also the data is not sent to controller .but when i replace the senddata function with the inner code of that function it works ??
$(document).ready(function () {
senddata('#ddtname');
$.ajax({
url:'#Url.Action("Getdata", "ConfigClass")',
type: "GET",
data: {'ctname':ctlevel},
dataType: "text",
//Response carry bunch of data from controller
success: function (response) {
alert(response);
//parse json obj to js
var obj = JSON.parse(response)
var ele = document.getElementById('sel');
$('#sel').empty();
//append default value to dropdown
var s = '<option value="-1">SubjectName</option>';
//using loop for populating dropdown ,values retrive through ajax
for (var i = 0; i < obj.length; i++) {
// POPULATE SELECT ELEMENT WITH JSON.
s+='<option value="' + obj[i]['aid'] + '">' + obj[i]['assignsubject'] + '</option>';
}
$('#sel').html(s);
},
error: function () {
alert('not working :(');
}
});
});
Related
I´m trying to get a list with Ajax when a modal shows up, but for some reason my method always receives a null variable. I´m sure that the issue is on the Ajax call, because if I test my method using 1 as an argument instead of the value from Ajax, it returns the list the way I wanted.
JS:
$("#visualizacao").on('show.bs.modal', function (e) {
var data = $(e.relatedTarget);
var idAviso = data.context.dataset.avisoid;
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/' +idAviso,
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});
C#
[HttpGet]
public JsonResult ListaVisuAviso(string avisoId)
{
//var avisoid = 1;
var avisoid = Convert.ToDecimal(avisoId);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
}
I discovered what was causing the "issue". To use this way of sending the parameter, my route config on the backend was expecting it to be a parameter called "id". So I would either change my receiving parameter to "id" instead of "avisoId" like the following:
[HttpGet]
public JsonResult ListaVisuAviso(string id)
{
//var avisoid = 4;
var avisoid = Convert.ToDecimal(id);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
Or, I would have do specify the name of the parameter on the JS, like this "?usuarioId=", this way the route would know that it´s not the id parameter:
$("#visualizacao").on('show.bs.modal', function (e) {
var idAviso = $(e.relatedTarget).attr('data-avisoid');
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/?usuarioId =' + idAviso,
dataType: 'json',
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});
I have more than three TextBoxes. I want to send this data as in the code. The "indeks " value is always the last click. How do I keep the index?
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
if (txtvalue != "") {
if (i)
field += " and ";
field = field + "[" + obje[indeks]+ "]" $(this ).val() + "'";
i++;
}
});
});
},
As I wasn't sure if I got your question right, I prefered to comment on your topic - but now it seems that my answer helped you, so I decided to post it as an actual answer:
1st step: declare an array outside your success handler
2nd step: push the index and the value for the element into this array
3rd step: loop through all entries of the array and build your 'select' statement
Here is your edited example:
https://jsfiddle.net/Lk2373h2/1/
var clickedIndexes = [];
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
$(this).attr('id', i);
var txtvalue=$(this).val();
if (i)
clickedIndexes.push({
index: indeks,
value: $(this ).val()
});
var selectString = "";
for (var u = 0; u < clickedIndexes.length; u++) {
selectString += "[" + obje[clickedIndexes[u].index].ALAN + "]" + "=" + "'" + clickedIndexes[u].value + "'";
}
field = selectString;
i++;
});
});
},
I have a form that submits a new entry via ajax and returns the entry data. I'm trying to get the returned data to be automatically selected in the Select2 field. I can get the id entered as the input value, but I'm not sure how to get the text to be displayed in the span.
Here's the JS I have so far:
function clientFormatResult(client){
var markup = client.first_name + ' ' + client.last_name + ' (' + client.username + ')';
return markup;
}
function clientFormatSelection(client) {
$('#client-input').empty();
$('#client-input').append('<input type="hidden" name="client" value="' + client.id + '" />');
return client.first_name + ' ' + client.last_name + ' (' + client.username + ')';
}
$('#client-selection').select2({
placeholder: 'Select a client',
allowClear: true,
minimumInputLength: 1,
ajax: {
type: 'POST',
url: 'clients/get_client_list',
dataType: 'json',
data: function (term) {
return {filter: term};
},
results: function (data) {
return {results: data};
}
},
formatResult: clientFormatResult,
formatSelection: clientFormatSelection,
dropdownCssClass: 'bigdrop',
initSelection: function (element, callback) {
var id = element.val();
if(id != '') {
$.ajax('clients/get_client_list/'+id).done(function(data) {
data = $.parseJSON(data);
callback(data);
});
}
}
});
$('#add-client-form').submit(function(e) {
e.preventDefault();
var form = $(this),
url = form.attr('action'),
data = form.serialize();
$.post(url, data, function(data, status, xhr) {
$('.form-response').fadeOut(400);
if(status == 'success') {
$('#add-client-modal').modal('hide');
data = $.parseJSON(data);
$('#client-selection').select2('val', data.client_id);
} else {
$('#add-client-failure').fadeIn(400);
}
});
});
As you can see, the text displayed is meant to be like "John Smith (smithj)".
I sorted it out, it was an issue with the data I was returning. Select2 was expecting an id variable, but I was returning it as client_id.
I have values that come from a dynamically created table from it's selected rows. inside each selected row i want all the td.innerText values that belong to be sent to a C# page, but i don't know how to. I was using JSON but I dont know if i used it properly.
function selectedRows()
{
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
serial = td[1].innerText;
kanbanNumber = td[2].innerText;
customer = td[3].innerText;
description = td[4].innerText;
quantity = td[5].innerText;
}
console.log(serial + ' ' + kanbanNumber + ' ' + customer + ' ' + description + ' ' + quantity);
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: "labelSerial=" + serial + "&kanbanNumber=" + kanbanNumber + "&customer="
+ customer + "&description=" + description + "&quantity=" + quantity
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}
EDIT: sorry I must have read this too quickly. This should do it. create an array and add the data object to it in the loop.
If you just create a json object using key value pairs you can send that object to your c# controller.
function selectedRows() {
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
var dataArray = new Array();
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
var InfoObject = {
serial: td[1].innerText;
kanbanNumber: td[2].innerText;
customer: td[3].innerText;
description: td[4].innerText;
quantity: td[5].innerText;
};
dataArray.push(InfoObject);
}
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: dataArray
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}
I am new to ajax and am trying to get the following script working. I just want to take info from a json object and print it to the document.
Here is the JSON file called companyinfo.json:
{
'id':1,
'name':'Stack'
}
The Ajax request looks like this:
ar xhr = false;
var xPos, yPos;
$(function(){
var submitButton = $("#dostuff");
submitButton.onclick = sendInfoRequest;
});
function sendInfoRequest (evt) {
if (evt) {
var company1 = $("#companyInput1").val;
var company2 = $("#companyInput2").val;
}
else {
evt = window.event;
var company = evt.srcElement;
}
$.ajax({
url : 'companyinfo.json',
dataType: 'json',
data: company1,
success: function(data) {
console.log(data);
var items = new Array ();
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
}
});
return false;
}
console.log(data.id);
To start simple. I just console.log the data.id to see if the script returned a value from the json file.
To write it to the document I would do something like this, calling the showContents function in the callback function above:
function showContents(companyNumber) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseXML;
$("." + data.companyName.toLowerCase + companyNumber).innerHTML(data.companyName)
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
}
}
I'm pretty new to Ajax, but hopefully that makes some sense. Thanks
if you are trying to get something i think you should add
type:"GET"
on your $.ajax it should look like this.
$.ajax({
url : 'companyinfo.json',
dataType: 'json',
type:"GET",
contentType: "application/json; charset=utf-8",
data: company1, //What is your purpose for adding this?
success: function(data) {
console.log(data);
var items = new Array ();
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
}
});
Im not sure about this in your code:
var company1 = $("#companyInput1").val; //should it be with ()??
var company2 = $("#companyInput2").val; //should it be with ()??
should it be with () like this one:
var company1 = $("#companyInput1").val();
var company2 = $("#companyInput2").val();
The easiest way to get and parse JSON is to use $.getJSON
// you need to use a map as your data => {key : value}
$.getJSON("companyinfo.json", {company : company1}, function(data){
console.log(data);
var items = []; // new Array();
$.each(data, function(key, val){
items.push('<li id="' + key + '">' + val + '</li>');
});
// do something with items
});
you can do like this:
$.getJSON("getJson.ashx", { Index: 1 }, function (d) {
alert(d);
});