I have the following .ajax
$.ajax({
url: urlpath,
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(JSON.stringify(data));
},
error: error
});
What I am passing back is a list with 3 columns. When I do alert(JSON.stringify(data));
it shows me the data - 3 columns and 4 rows of data. How do I go about parsing this and storing it into a table?
Say you have a table with an id="my-table", you can substitute your alert with something like:
$('#my-table tr').each(function (r) {
$('td', this).each(function (c) {
// here you cycle on every td (column) of a row to populate it
// example with 3 columns assuming this json structure
// {
"row1": [ 100, 200, 300],
"row2": [ 50, 200, 400 ],
"row3": [ 10, 300, 200]
// }
this.innerHTML = data["row"+r][c]
})
});
$('#my-table tr')... find create an array with your table rows
$('td', this)... apply an anonimous function on every td of the loop current tr (this acts as the search context for tds
Related
I am creating column headers from the rows of a mysql table (Button1) and it works fine. eg: I get headers |A|B|C| in the grid when I query the table for the rows A, B, C.
Button2 queries the same table to get different rows eg D, E. Both queries return expected data.
But, the new header data from Button2 is appended to the column headers created from Button1. ie I get |A|B|C|D|E|.
What I want is just the headers |D|E|. How can I clear the old column headers and replace with the new?
Thanks for any help.
var ColModel = []
var availabilitydept = ''
$("#button1").click(function() {
availabilitydept = 'de85768424332'
set_up_avgrid()
});
$("#button2").click(function() {
availabilitydept = 'de56827997021'
set_up_avgrid()
});
function set_up_avgrid()
{
$("#avgrid").jqGrid("GridUnload")
$('#avgrid').jqGrid('clearGridData');
create_colmodel()
create_grid()
}
function create_colmodel()
{
ColModel.push({name :'Date',index: 'dateindex',resizable : false, align:'left',
frozen : true, width : 80, search: false,
resizable : false});
$.ajax
({
url: 'tl2_get_rooms_by_dept.php',
type: 'GET',
async: false, // ** it don't work with async true.
data: 'userid=' + 'TL2-0001'
+ '&deptid=' + availabilitydept,
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
ColModel.push({name: row.roomname, index: row.roomname + i, align:'center', resizable : false, width:50, search:false});
}
}
});
}
function create_grid()
{
$("#avgrid").jqGrid(
{
shrinkToFit: false,
height : 200,
width : 290,
colModel: ColModel,
});
}
Solved: I'm sure there are better ways but what I ended up doing was to change my query to select all rows from the mysql table, then create the grid. Of course the grid then had a column for each row in the table. To get rid of the unwanted columns I composed a function to loop through the column names and hide/show as required using.
$"#avgrid").jqGrid('hideCol',[row.roomname]);
$("#avgrid").jqGrid('showCol',[row.roomname]);
I have a Shopify site which, when viewing certain product I give the buyer the option of adding other related items at the same time. Each related product has it's own quantity input, with names "quantity1", "quantity2" etc.
What I would like to do is to count how many input names are on my page that contain the text "quantity", then create a loop over this quantity and add each item, via AJAX, that has a quantity greater than zero.
I am very new to this so not really sure what I'm doing, and have tried hours of looking into a solution but keep hitting a brick wall.
I have done the easy part, which is counting the number of "quantity" inputs using this code:
var len = $('input[id^=quantity]').length;
This is successful, but I am struggling on the loop within the AJAX call, I have tried lots of different code but none works. I would effectively like to do the following:
function addItemToCart(variant_id, qty) {
var len = $('input[id^=quantity]').length;
data = {"id": $('#quantity'+loopnumber).parent().attr('name'),
"quantity": parseFloat($("#quantity"+loopnumber).val()),
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function()
I understand I have not put the for loop code in here but that's because I don't know where to put it, and am hoping that someone could help me out please. The "loopnumber" text in the data fields would refer to the current iteration of the loop, so iteration 1 would look for the input name "quantity1" and look for it's respective value, post that to the AJAX cart, and on success loop over the next quantity values until it reaches the for loop limit. At which point it then redirects to the cart.
I know that I could simply do the following, without the loop, but this is wasteful in my opinion:
var quantity1 = parseFloat($("#quantity1").val());
var qty1 = $('#quantity1').parent().attr('name');
var quantity2 = parseFloat($("#quantity2").val());
var qty2 = $('#quantity2').parent().attr('name');
var quantity3 = parseFloat($("#quantity3").val());
var qty3 = $('#quantity3').parent().attr('name');
var quantity4 = parseFloat($("#quantity4").val());
var qty4 = $('#quantity4').parent().attr('name');
var quantity5 = parseFloat($("#quantity5").val());
var qty5 = $('#quantity5').parent().attr('name');
data = {
"id": prodid,
"quantity": mainquantity,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
data = {
"id": qty1,
"quantity": quantity1,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
data = {
"id": qty2,
"quantity": quantity2,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
data = {
"id": qty3,
"quantity": quantity3,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
data = {
"id": qty4,
"quantity": quantity4,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
data = {
"id": qty5,
"quantity": quantity5,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() { window.location.href = '/cart'
;
}
});
;
}
});
}})}})}})}})};
Any help is greatly appreciated!
Thanks
Jon
I've sorted it, I was overly complicating things. All I had to do was create an array and that negates having to create an AJAX loop which I couldn't get working. It's also MUCH quicker to add all the items to the AJAX cart in one go too.
I have an issue with ajax calling. It works correct except one thing, when I try to get data with the same option more than one times returns the new response but also still return the data of the previous response.
I think that there is something that I've missed.
ajax script
$('#search').on('click', function () {
var date = $("#date").val();
$.ajax({
type: 'GET',
url: '{{Route("dashboard.status")}}',
data: {
date: date
},
dataType: "JSon",
success: function(response){
console.log(response.manager_hourlog);
// Employee report script
var colors = ["#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"];
#if ($auth->user_type != 1)
// manager report script
var managerchartbar = {
labels: response.manager_projects,
datasets:
[{
label: response.users,
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
data: response.totals
},]
};
var ctx = document.getElementById('manager').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: managerchartbar,
options: {
title: {
display: true,
text: 'Project Report chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
#endif
},
error: function(xhr){
console.log(xhr.responseText);
}});
});
});
</script>
You should change your method to POST for json request/response API, will be more secure and avoid laravel cache view it.
type: 'POST',
Try to change method to POST (do same for your api server and route).
If not work, please show your laravel API code.
you should set cache property to false or append "_={timestamp}" to the GET parameter
so add cache to your request:
cache:false
or append timestamp to your url:
url: '{{Route("dashboard.status")}}'+'_='+ + new Date().getTime(),
I am using a kendo multiselect widget for users to select different values pulled from the database via an ajax call. The ajax call takes one parameter, searchValue, which will narrow down the returned data. Here is my controller:
[HttpPost]
public JsonResult ProfitabilitySearch(string searchValue)
{
return Json(InventoryDataAccess.ProfitabilitySearch(searchValue));
}
1) How do you get the value from the text box to use as your searchValue? I commented the area in question below.
Here is my dataSource:
var searchDataSource = new kendo.data.DataSource({
transport: {
read: function () {
$.ajax({
type: 'POST',
url: Firm.ProfitabilitySearchURL,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
//'SuperClient' is test data to see if it works, but what do i
//need to make searchValue = what I type?
data: JSON.stringify({ searchValue: 'SuperClient'}),
success: function (data) {
return data.RESULT;
}
});
}
},
group: { field: 'category' },
serverFiltering: true
});
And here is where I create the multiselect widget:
var TKSearch = $("#TKSearch").kendoMultiSelect({
dataSource: searchDataSource,
autoBind: false,
minLength: 3,
placeholder: 'Search Timekeepers...',
dataTextField: 'label',
dataTextValue: 'value',
delay: 200
}).data("kendoMultiSelect");
I'm not sure if this will help, but here is the structure of the json that is returned from the ajax call:
{"label":"SUNFLOWER REALTY CORP. (023932)","value":"023932","category":"RC"}
Solving the first question above may answer my second question so I will wait to ask that until after.
You can use functions for the request parameters.
var searchDataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: 'POST',
url: Firm.ProfitabilitySearchURL,
contentType: 'application/json; charset=utf-8',
data: {
searchValue: function () {
// better: use a model property instead of this
return $("#TKSearch").data('kendoMaskedTextBox').value();
}
},
success: function (data) {
options.success(data.RESULT);
}
});
}
},
group: { field: 'category' },
serverFiltering: true
});
Notes
This really should be a GET request. Use POST for requests that actually change data on the server and GET for requests that merely retrieve data from the server.
You do not have to JSON.stringify() yourself. jQuery does that transparently.
Specifying dataType is completely superfluous, jQuery will figure this out from the response headers.
Reading the input value via jQuery is not clean. Use the data-bound model property instead.
The callback invocation (options.success())
This sample lacks HTTP error handling, you must add that.
I want to add about 150 element from a xml file to a select control that is inside a jqGrid cell. I was thinking of doing this in two ways:
1.Using the editoptions value:
{ name: 'language', width: 100, sortable: false, editable: true, edittype: 'select', editoptions: { value: languageElem()} }
using data received from the method:
function languageElem() {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'jqService.asmx/GetLanguages',
data: {},
dataType: "json",
success: function (data) {
alert("success");
}
});}
But I'm having trouble forwarding the data from the ajax part.
2.Simply accessing the select control inside the jqGrid cell and manually adding the options whenever the edit button is pressed.
The problem over here is that I have no idea how to access the control itself.
The code I used over here is:
function startEdit() {
if (selRow > -1) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'jqService.asmx/GetLanguages',
data: {},
dataType: "json",
success: function (data) {
var cell = jQuery("#MainContent_list").getCell(selRow, "language");
cell.options.length = 0;
for (var i=0;i<data.d.length;i++)
{
}
}
});
jQuery("#MainContent_list").jqGrid('restoreRow', selRow);
jQuery("#MainContent_list").jqGrid('editRow', selRow);
}
My questions are:
1.Related to the first idea, what should I do to fix the method so that the control will receive it's needed values?
2.Related to the second idea, how could I access the control inside the row?
Thanks, Catalin
Instead of value property (editoptions: { value: languageElem()}) you should use dataUrl and buildSelect (see the documentation). Because it's difficult to return from ASMX HTML fragment <select><option>...</option></select> you can provide the list serialized as JSON and convert the server response to HTML fragment using buildSelect. In the answer and in this one you will find additional information. If you would search for dataUrl and buildSelect you will find more information and code example which you could use.