How would pass the parameter into "foodName" from the function that sends the url and id? i.e. could you do something like the function:
call('/url/to/foodlist', "foodList", "food");
and replace
var input = item.food;?
Below is working code but would like a more general function then having to use part of name in the function (replace foodName so that it isn't in this function)
function call(url, id){
var string = '';
$.ajax({
type: "GET",
url: url,
success: function (item)
if (item != '') {
var input = item.foodName;
for (var i = 0; i < input.length; i++) {
string += = '<option value=' + input[i].name + '">' + input[i].name + '</option>';
}
$('#' + id). append(string);
}
});
call('/url/to/foodlist', "foodList");
function call(url, id, paramName){
var string = '';
$.ajax({
type: "GET",
url: url,
success: function (item)
if (item != '') {
var input = item[paramName]; // you can access to the properties using braces
for (var i = 0; i < input.length; i++) {
string += = '<option value=' + input[i].name + '">' + input[i].name + '</option>';
}
$('#' + id). append(string);
}
Related
While everything is running in the software, I get this error when I make a selection from the dropdown list in only one part. Where am I making a mistake? or is it a server error?
I have not received this error in any Laravel before. When trying to get something from a dropdown list, this error comes to the console and there is no reaction on the site.
https://prnt.sc/vaujzf
<script type="text/javascript">
$("ul#product").siblings('a').attr('aria-expanded','true');
$("ul#product").addClass("show");
$("ul#product #adjustment-create-menu").addClass("active");
var lims_product_array = [];
var product_code = [];
var product_name = [];
var product_qty = [];
$('.selectpicker').selectpicker({
style: 'btn-link',
});
$('#lims_productcodeSearch').on('input', function() {
var warehouse_id = $('#warehouse_id').val();
temp_data = $('#lims_productcodeSearch').val();
if (!warehouse_id) {
$('#lims_productcodeSearch').val(temp_data.substring(0, temp_data.length - 1));
alert('Please select Warehouse!');
}
});
$('select[name="warehouse_id"]').on('change', function() {
var id = $(this).val();
$.get('getproduct/' + id, function(data) {
lims_product_array = [];
product_code = data[0];
product_name = data[1];
product_qty = data[2];
$.each(product_code, function(index) {
lims_product_array.push(product_code[index] + ' (' + product_name[index] + ')');
});
});
});
var lims_productcodeSearch = $('#lims_productcodeSearch');
lims_productcodeSearch.autocomplete({
source: function(request, response) {
var matcher = new RegExp(".?" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(lims_product_array, function(item) {
return matcher.test(item);
}));
},
response: function(event, ui) {
if (ui.content.length == 1) {
var data = ui.content[0].value;
$(this).autocomplete( "close" );
productSearch(data);
};
},
select: function(event, ui) {
var data = ui.item.value;
productSearch(data);
}
});
$("#myTable").on('input', '.qty', function() {
rowindex = $(this).closest('tr').index();
checkQuantity($(this).val(), true);
});
$("table.order-list tbody").on("click", ".ibtnDel", function(event) {
rowindex = $(this).closest('tr').index();
$(this).closest("tr").remove();
calculateTotal();
});
$(window).keydown(function(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function() {
if (this === e.target) {
focusNext = true;
}
else if (focusNext) {
$(this).focus();
return false;
}
});
return false;
}
}
});
$('#adjustment-form').on('submit', function(e) {
var rownumber = $('table.order-list tbody tr:last').index();
if (rownumber < 0) {
alert("Please insert product to order table!")
e.preventDefault();
}
});
function productSearch(data) {
$.ajax({
type: 'GET',
url: 'lims_product_search',
data: {
data: data
},
success: function(data) {
var flag = 1;
$(".product-code").each(function(i) {
if ($(this).val() == data[1]) {
rowindex = i;
var qty = parseFloat($('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val()) + 1;
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val(qty);
checkQuantity(qty);
flag = 0;
}
});
$("input[name='product_code_name']").val('');
if(flag) {
var newRow = $("<tr>");
var cols = '';
cols += '<td>' + data[0] + '</td>';
cols += '<td>' + data[1] + '</td>';
cols += '<td><input type="number" class="form-control qty" name="qty[]" value="1" required step="any" /></td>';
cols += '<td class="action"><select name="action[]" class="form-control act-val"><option value="-">{{trans("file.Subtraction")}}</option><option value="+">{{trans("file.Addition")}}</option></select></td>';
cols += '<td><button type="button" class="ibtnDel btn btn-md btn-danger">{{trans("file.delete")}}</button></td>';
cols += '<input type="hidden" class="product-code" name="product_code[]" value="' + data[1] + '"/>';
cols += '<input type="hidden" class="product-id" name="product_id[]" value="' + data[2] + '"/>';
newRow.append(cols);
$("table.order-list tbody").append(newRow);
rowindex = newRow.index();
calculateTotal();
}
}
});
}
function checkQuantity(qty) {
var row_product_code = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('td:nth-child(2)').text();
var action = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.act-val').val();
var pos = product_code.indexOf(row_product_code);
if ( (qty > parseFloat(product_qty[pos])) && (action == '-') ) {
alert('Quantity exceeds stock quantity!');
var row_qty = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val();
row_qty = row_qty.substring(0, row_qty.length - 1);
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(row_qty);
}
else {
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(qty);
}
calculateTotal();
}
function calculateTotal() {
var total_qty = 0;
$(".qty").each(function() {
if ($(this).val() == '') {
total_qty += 0;
} else {
total_qty += parseFloat($(this).val());
}
});
$("#total-qty").text(total_qty);
$('input[name="total_qty"]').val(total_qty);
$('input[name="item"]').val($('table.order-list tbody tr:last').index() + 1);
}
</script>
I don't understand why call_script_id is showing as a string instead of the content stored in the variable. The other variables work fine, but literally, call_script_id is setting id="call_script_id" whereas call_reason_id is setting the proper number.
$.ajax({
url: "../selections/call-reasons.php",
type: 'post',
data: {company_uid:"<?php echo $row['company_uid']; ?>"},
dataType: 'json',
success:function(response){
var len = response.length;
$("#call_reasons").empty();
for( var i = 0; i<len; i++){
var call_script_id = response[i]['call_script_id'];
var call_reason_id = response[i]['call_reason_id'];
var call_type = response[i]['call_type'];
var active = response[i]['active'];
$("#call_reasons").append("<tr><td href='../modals/call-types.php' class='call_reason_row' id=" + call_script_id + ">" + call_reason_id + "</td><td id=" + call_script_id + "></td><td id=" + call_script_id + "></td><td><i class='far fa-edit'></i><i class='far fa-calendar-alt'></i><i class='far fa-trash-alt call_reason_trash' id=" + call_reason_id + "></i></td></tr>");
}
// Brings up the pop up to edit call reasons/types
$(".call_reason_row").click(function() {
$('#main-content',parent.document).load($(this).attr('href'), {call_reason_id: this.id, company_uid: "<?php echo $row["company_uid"];?>", active: active});
});
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
$sql = "SELECT cs.id, cs.call_reason, sct.call_type FROM call_script AS cs INNER JOIN selection_call_types AS sct ON cs.call_reason = sct.id WHERE cs.company_uid = '$company_uid'";
$result = mysqli_query($conn, $sql);
$my_array = array();
while($row = mysqli_fetch_array($result) ){
$call_script_id = $row['id'];
$call_reason_id = $row['call_reason'];
$call_type = $row['call_type'];
$active = $row['active'];
$my_array[] = array("call_script_id" => call_script_id, "call_reason_id" => $call_reason_id, "call_type_id" => $call_type, "active" => $active);
}
I guess I expecting the issue to be in ajax since I'm not as familiar with the language. Instead, it was because I was missing the dollar sign on the variable call_reason_id, in $my_array on the very last line.
I have more than 1000 rows and it is taking much time in taking AJAX response and loading data in dropdwon.
I am using below code .
function fillperson() {
$.ajax({
// delay: 250 ,
url: Url,
type: "GET",
minimumInputLength:0,
data: { isGetAll: false, Id1: 0, ID2:0},
complete: function (data) {
var ele = document.getElementById('ddlperson');
ele.innerHTML = '';
var persondata = JSON.parse(data.responseText);
ele.innerHTML = '<option value="' + -1 + '">Select Person</option>';
ele.innerHTML += '<option value="' + 0 + '">ALL Person</option>';
var totaldata = persondata.length;
var i = 0;
for ( i ; i < data.length; i++) {
ele.innerHTML = ele.innerHTML +
'<option value="' + data[i]['Id'] + '">' +data[i]['name'] + '(' + data[i]['code'] + ')' + '</option>';
}
$('#ddperson').select2();
},
});
}
I have the controller below with the Methods. One takes a parameter and the other does not.
I want to be able to do a search.
When I click on submit button. Nothing happens. My ajax call is not hit.
If question 1 is solved, I want to be able to type in my search criteria and have it
return data in the existing table used in my index view.
Please assist. New to Ajax and mvc.
public class HomeController : Controller
{
public ActionResult Index()
{
//List<Product> myProductList = GetAllProducts();
//return View(myProductList);
//List<Product> myProductList = GetAllProducts();
return View();
}
public ActionResult About()
{
return View();
}
public List<Product> GetAllProducts()
{
string myConnect = ConfigurationManager.ConnectionStrings["ConnectSir"].ConnectionString;
List<Product> prdResults = new List<Product>();
SqlConnection con = new SqlConnection(myConnect);
SqlCommand cmd = new SqlCommand("select * from products",con);
using (con)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Product newProduct = new Product();
newProduct.Id = Convert.ToInt16(reader["Id"]);
newProduct.Name = reader["Name"].ToString();
newProduct.Description = reader["description"].ToString();
newProduct.Price = Convert.ToDecimal(reader["Price"]);
newProduct.UnitsInStock = Convert.ToInt16(reader["UnitsInStock"]);
prdResults.Add(newProduct);
}
}
return prdResults;
}
[HttpPost]
public JsonResult GetAllProducts(string searchName)
{
string myConnect = ConfigurationManager.ConnectionStrings["ConnectSir"].ConnectionString;
List<Product> prdResults = new List<Product>();
string sqlcmd = #"select * from products where name = #name";
SqlConnection con = new SqlConnection(myConnect);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = sqlcmd;
cmd.Parameters.Add("#name", SqlDbType.NVarChar);
cmd.Parameters["#name"].Value = searchName;
cmd.Parameters["#name"].Direction = ParameterDirection.Input;
using (con)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Product newProduct = new Product();
newProduct.Id = Convert.ToInt16(reader["Id"]);
newProduct.Name = reader["Name"].ToString();
newProduct.Description = reader["description"].ToString();
newProduct.Price = Convert.ToDecimal(reader["Price"]);
newProduct.UnitsInStock = Convert.ToInt16(reader["UnitsInStock"]);
prdResults.Add(newProduct);
}
}
//return prdResults;
return Json(prdResults);
}
}
*********************************
Html
#model IEnumerable<MvcAjax.Models.Product>
<script src="../../Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<form>
<div>
<input type="text" name="search" id="searchItem" />
<input type="submit" value="Retrieve" id="btnSearch"/>
</div>
<div>
</div>
<table id="items">
<tr>
<th></th>
<th>
Name
</th>
<th>
Description
</th>
<th>
Price
</th>
<th>
UnitsInStock
</th>
</tr>
</table>
<script type="text/javascript">
$('#btnSearch').click(function () {
$.ajax({
url: 'Home/GetAllProducts/',
type: 'POST',
dataType: 'json',
data: { searchName: $('#searchItem').val() }
}).done(function (data) {
if (data && data.length) {
for (var i = 0; i < data.length; i++) {
var newTR = '<tr>';
//create your TR, such as
newTR += '<td>' + data[i].Name + '</td>';
newTR += '<td>' + data[i].Description + '</td>';
newTR += '<td>' + data[i].Price + '</td>';
newTR += '<td>' + data[i].UnitsInStock + '</td>';
//and so on...
newTR += '</tr>';
$('#items > tr:last').append(newTR);
}
}
});
});
</script>
</form>
Send ajax with data and change content type to application/json; charset=utf-8", like this:
$('#btnSearch').click(function () {
$.ajax({
data: '{searchName:' + $('#searchItem').val() + '}'
url: 'Home/GetAllProducts/',
contentType: 'application/json; charset=utf-8"',
type: 'Get',
dataType: 'html'
})
});
Change
data: { Name: mysearchName }
in your ajax call to
data: { searchName: mysearchName }
as your action method is accepting searchName
[HttpPost]
public JsonResult GetAllProducts(string searchName)
{...
}
Let's focus on your first question. Your action is probably not being called because you're using a non-default route. Also, having actions with the same name and verb is not a good practice.
So, let's change your action signature to:
[HttpPost]
public JsonResult GetAllProducts(string searchName)
HttpPost to change the verb, and JsonResult because we want to use your data with javascript, and that's the best approach.
Final change to your action, let's modify the return statement:
return Json(prdResults);
On your view, we must modify the ajax call:
$('#btnSearch').click(function () {
$.ajax({
url: 'Home/GetAllProducts/',
contentType: 'application/html; charset-ut',
type: 'POST',
dataType: 'json',
data: { searchName: $('#searchItem').val()}
});
});
As soon as we get this working, I'll move to the next question.
Now, the 2nd part. We'll add the lines using javascript.
First of all, let's give an id to your table. Let's call it items
<table id="items">
Let's add a handler to your ajax promise:
$('#btnSearch').click(function () {
$.ajax({
url: 'Home/GetAllProducts/',
type: 'POST',
dataType: 'json',
data: { searchName: $('#searchItem').val()}
}).done(function(data){
if(data && data.length){
for(var i = 0; i < data.length; i++){
var newTR = '<tr>';
//create your TR, such as
newTR += '<td>' + data[i].Name + '</td>';
//and so on...
newTR += '</tr>';
$('#items > tr:last').append(newTR);
}
}
});
});
And that's it
For debugging puporses, let's replace the code within done(data){...} with this:
if (data && data.length) {
for (var i = 0; i < data.length; i++) {
var newTR = '<tr>';
//create your TR, such as
newTR += '<td>' + data[i].Name + '</td>';
newTR += '<td>' + data[i].Description + '</td>';
newTR += '<td>' + data[i].Price + '</td>';
newTR += '<td>' + data[i].UnitsInStock + '</td>';
//and so on...
newTR += '</tr>';
alert(newTR);
$('#items > tr:last').append(newTR);
}
}
else{
alert('empty response. Please set a breakpoint at the action and make sure that something is returning');
}
I am building a mobile application using Sencha Touch 1.0. I need to display report, for that am using grid given by Ext.ux.TouchGridPanel.
It is working fine.
Where as I need to capture Scroll event in Ext.ux.TouchGridPanel.
I have added 'scroll' in bubble event of Dataview.
I am also trying to capture the event after the Dataview created.
But nothing seems to be working. Below is the code which I have changed.
Does anybody has any idea how to capture the start of scroll event?
Thanks in advance.
Ext.ux.TouchGridPanel = Ext.extend(Ext.Panel, {
layout: "fit",
multiSelect: false,
initComponent: function () {
var me = this;
me.items = me.dataview = me.buildDataView();
Ext.ux.TouchGridPanel.superclass.initComponent.call(me);
var store = me.store;
store.on("update", me.dispatchDataChanged, me);
var dataview = me.dataview;
dataview.on('scroll', me.startScroll);
},
dispatchDataChanged: function (store, rec, operation) {
var me = this;
me.fireEvent("storeupdate", store, rec, operation);
},
startScroll: function (scroller, offset) {
console.log('is this event captured???')
var me = this;
me.fireEvent("scroll", this.scroller, offset);
},
buildDataView: function () {
var me = this, colModel = me.colModel, colNum = me.getColNum(false), cellWidth = 100 / colNum,
colTpl = '<div class="x-grid-head">';
colTpl += '<thead><tr class="x-grid-header">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + (col.width - 4) + "%") : '';
colTpl += '<th class="x-grid-cell" ' + width + ' style="' + col.style + '" >' + col.header + '</th>';
}
colTpl += '</tr></thead>';
colTpl += '<tbody ><tpl for="."><tr class="x-grid-row">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + col.width + "%") : '';
colTpl += '<td class="x-grid-cell" style="' + col.style + '" >{' + col.mapping + '}</td>';
}
colTpl += '</tr></tpl></tbody>';
colTpl += '</table></div>'
return new Ext.DataView({
store: me.store,
itemSelector: "tr.x-grid-row",
simpleSelect: me.multiSelect,
scroll: me.scroll,
tpl: new Ext.XTemplate(colTpl,
{
isRowDirty: function (dirty, data) {
return dirty ? "x-grid-row-dirty" : "";
}
}
),
prepareData: function (data, index, record) {
var column,
i = 0,
ln = colModel.length;
var prepare_data = {};
prepare_data.dirtyFields = {};
for (; i < ln; i++) {
column = colModel[i];
if (typeof column.renderer === "function") {
prepare_data[column.mapping] = column.renderer.apply(me, [data[column.mapping], column, record, index]);
} else {
prepare_data[column.mapping] = data[column.mapping];
}
}
prepare_data.isDirty = record.dirty;
prepare_data.rowIndex = index;
return prepare_data;
},
bubbleEvents: [
"beforeselect",
"containertap",
"itemdoubletap",
"itemswipe",
"itemtap",
"selectionchange",
"scroll"
]
});
},
// #private
onScrollStart: function () {
console.log("Are you coming here");
var offset = this.scroller.getOffset();
this.closest = this.getClosestGroups(offset);
this.setActiveGroup(this.closest.current);
},
// #private
onScroll: function (scroller, pos, options) {
}
});
Ext.reg("touchgridpanel", Ext.ux.TouchGridPanel);
We can directly access dataview scroller and check event of the same.
For eg.
newGrid = new Ext.ux.TouchGridPanel({....
after creation of the Panel just access its dataview scroller
newGrid.dataview.scroller.on('scroll', scrollGrid1);
var scrollGrid1 = function(scroller, offsets){
console.log(' Grid scrolling with offset ' + offsets.x + ' & ' + offsets.y);
}