Send 2 array by ajax - javascript

First I want to create a simple array with data from input
And I want to do a loop and create an array with the line from the table.
some code here.
var first_array = {
"warehouse": $("#warehouse").val(),
"pricelist": $("#pricelist").val(),
"date": $("#date").val(),
"docstatus": "DR",
"paymentterm": $("#paymentterm").val()
}
var second_array = []; //Thanks to sagar1025 help create the second array
$("#table_main tbody > tr").each(function() {
var celdas = $(this).find('td');
second_array.push({
"line": $(celdas[0]).html(),
"code": $(celdas[1]).html()
});
});
/*Here my ajax*/
$.ajax({
data: {
array1: first_array,
array2: second_array
},
url: "<?php echo base_url() ?>main/save_data",
type: 'POST',
async: false,
cache: false,
success: function(response) {
},
error: function() {
toastr.error('ERROR', '', {
progressBar: true,
closeButton: true
});
}
});
Now I need to loop the second array in my php file
Here is how I declare one var from the first_array
$docstatus = trim($this->input->post('array1[docstatus]', TRUE));
$array = $this->input->post('array2[]', TRUE);
Im using codeigniter

This is how you push or add multiple objects to an array
var second_array = [];
$("#table_main tbody > tr").each(function() {
var celdas = $(this).find('td');
second_array.push({
"line": $(celdas[0]).html(),
"code": $(celdas[1]).html()
});
});
The Ajax call should be like something like this:
$.ajax({
data: {
array1: first_array,
array2: second_array
},
url: "<?php echo base_url() ?>main/save_data",
type: 'POST',
async: false,
cache: false,
success: function(response) {
},
error: function() {
toastr.error('ERROR', '', {
progressBar: true,
closeButton: true
});
}
});

I think you are confusing between arrays and object, arrays are denoted with [] example var array=[1,2,3,4] objects are denoted with {} ex: var Obj={color:"red"}
you could send an object in your ajax call that contains both arrays or both objects depending on what you want so for instance you could do something like:
var globobj={}
var first_object= {
"warehouse": $("#warehouse").val(),
"pricelist": $("#pricelist").val(),
"date": $("#date").val(),
"docstatus": "DR",
"paymentterm": $("#paymentterm").val()
}
var second_object= {
"line": $(celdas[0]).html(),
"code": $(celdas[1]).html()
}
globobj.first_object=first_object
globobj.second_object=second_object
so now that your objects are both combined you could use the globobjto make you ajax call

Related

Access json data using jquery for setting values

I bring data into json string which comes as r.d in my below code.
Now I want to access the field of it. so how should I access it ?
Here is the code
$.ajax({
url: "GET_DATA_BY_STORE.aspx/GETSTOREINFO",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ STORE_ID: STORE_ID }),
async: true,
processData: false,
cache: false,
success: function (r) {
alert(getJSONValue[0].STORE_ID);
},
error: function (xhr) {
// alert('Error while selecting list..!!');
}
})
And in r.d I get data as
Once you have converted it as json object using JSON.parse you can access properties like you normally do with javascript objects:
var jsonString = '{"d": [{"field1": "value1", "field2": 15.0}, {"field3": [1,2,3]}]}'
var r = JSON.parse(jsonString)
console.log(r.d)
// output: [ { field1: 'value1', field2: 15 }, { field3: [ 1, 2, 3 ] } ]
console.log(r.d[0].field1)
// output: value1
console.log(r.d[0].field2)
// output: 15
console.log(r.d[1].field3)
// output: [ 1, 2, 3 ]
// you can also use brackets notation to access properties in object
console.log(r.d[0]["field1"])
// output: value1
// or you can iterate properties if the data type of a field is an array (r.d is an array)
r.d.forEach(function(prop) {
console.log(prop);
})
// output: { field1: 'value1', field2: 15 }
// { field3: [ 1, 2, 3 ] }

jQuery Autocomplete showing result label as undefined

The list is being filtered properly but the label is showing as undefined. When I select the item, the value is binded.
Below is my code along with the screenshots:
$(document).on('ready',function(){
$('#search').autocomplete({
source: function(req,res) {
$.ajax({
url: "/search",
dataType: "json",
type: "GET",
data: {
term: req.term
},
success: function(data) {
res($.map(data, function(item) {
return {
label: item.name,
value: item.id
};
}));
},
error: function(xhr) {
alert(xhr.status + ' : ' + xhr.statusText);
}
});
},
select: function(event, ui) {
}
});
});
Before Selection
After selection
I tried debugging the label and value using alert function. The values are perfect. I'm unable to figure out the error.
item.name
item.id
Here is the callback response:
[
{
"id":"1",
"name":"Android"
},
{
"id":"2",
"name":"Akira"
},
{
"id":"3",
"name":"Andy"
},
....
]
You are returning different property names in ajax success function.
Can you try to use these property names instead.
[
{
"label":"1",
"value":"Android"
},
....
]
$.ajax({
url: "url",
type: 'POST',
data: {
},
success: function (res) {
//console.log(res);
var obj = JSON.parse(res);
$('#od').html('<option value=""> Select</option>');
for (var i = 0, len = obj.length; i < len; i++){
$('#id').append('<option value='+ obj[i].item_id +'> '+ obj[i].item_name +'</option>');
}
}
});
here is my code for get all option you can try this

Dynamically set datasource for jquery datatable columns

Is there a way we can dynamically set data source of datatable columns? Like I set columns.data by hardcoding each property name like this:
$.ajax({
data: JSON.stringify(data),
url: urlGetProviderQualificationTimeData,
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (obj) {
if (obj.success) {
$('#tblProds').dataTable({
data: obj.data.ProdsDetails,
columns: [
{ "data": "PName" },
{ "data": "PTime" } //hardcoded mapping of properties
]
});
}
},
});
ProdsDetails sample array:
Array[2]
0:Object
PName:"ATT",
PTime:"6.48"
1:Object
PName:"CENTURYLINK",
PTime:"3.67"
Is there a way we can get rid of this hardcoded mapping of properties and columns?
Here is your array :
var array=[
{PName:"ATT",PTime:"6.48" },
{PName:"CENTURYLINK",PTime:"3.67"}
];
Now, You should get all the keys and build final array:
var obj=array[0];
var keys=[];
for(var k in obj)
keys.push({"data":k});
Now, keys array looks like this:
[
{"data":"PName"},
{"data":"PTime"}
]
And the last step is to assign array to columns property of DataTable:
columns:keys
Now this should look like this:
columns:[
{ "data": "PName" },
{ "data": "PTime" }
]
Hope this helps !.
I had the same problem and worked around this by creating an extra json array for the columns.data property. Is used a php function to loop through the headers and put it into a json array.

How to send a list of int from Javascript (Ajax) to C#?

normaly I would write
$.ajax({
url: '#Url.Action("PlantHistoryContent", "PlantStatus")',
data: {id: 1},
async: false,
type: "POST"
})
when I want to pass the integer id to server side in C#:
public void PlantHistoryContent(int id)
{
///
}
How to do the same with a list of integer?
So I have a object-list of unkown length and want to pass it as a list to server side?
My server side should be
public void PlantHistoryContent(List<int> id)
{
///
}
How to write the ajax call data parameter to this?
A list in JavaScript looks like:
var list = [ 1, 2, 3, 4 ];
To build it you can do:
var list = [];
list.push(1);
list.push(2);
list.push(3);
list.push(4);
Then when you send it you can do:
$.ajax({
url: '#Url.Action("PlantHistoryContent", "PlantStatus")',
data: { ids: list },
async: false,
type: "POST"
})
or
$.ajax({
url: '#Url.Action("PlantHistoryContent", "PlantStatus")',
data: { ids: [ 1, 2, 3, 4 ] },
async: false,
type: "POST"
})
By default form-encoding is used. The request body will look like:
ids[0]=1&ids[1]=2&ids[2]=2&ids[3]=3
With form-encoding there is no way to know what the type of the parameter is. They're all strings.
If you use JSON as your transfer encoding instead you can send integers because JSON knows string and ints and list etc.
$.ajax({
url: '#Url.Action("PlantHistoryContent", "PlantStatus")',
data: { data: JSON.stringify({ ids: [ 1, 2, 3, 4 ] }) },
async: false,
type: "POST"
})
Now your request body looks like:
data=%5B1%2C2%2C3%2C4%5D

Loading data from ajax breaks functionality

I am trying to create a real-time filter on a table using knockoutjs.
I have managed to get everything to work when I statically create the observable array like this:
$(function() {
var assets = [
{id: "1", poster: "Pic010.jpg", name: "Asset1", category: "category1", type: "Movie", popup: "1" },
{id: "2", poster: "Pic06.jpg", name: "Asset2", category: "category2", type: "Movie", popup: "2" },
{id: "3", poster: "Pic04.jpg", name: "Asset3", category: "category1", type: "Pop-up", popup: "3" },
{id: "4", poster: "Pic07.jpg", name: "Asset4", category: "category2", type: "Pop-up", popup: "4" },
{id: "5", poster: "Pic011.jpg", name: "Asset1", category: "category3", type: "Promo", popup: "5" }
];
var viewModel = {
assets: ko.observableArray(assets),
query: ko.observable(''),
search: function(value) {
viewModel.assets.removeAll();
for(var x in assets) {
if(assets[x].name.toLowerCase().indexOf(value.toLowerCase()) >= 0) {
viewModel.assets.push(assets[x]);
}
}
}
};
viewModel.query.subscribe(viewModel.search);
ko.applyBindings(viewModel);
});
JSFiddle of working code: http://jsfiddle.net/7ZLdk/1/
Now when I try to load the observable array data via ajax like this:
var assets = [];
$.ajax({
url: '/Assets/getJson/',
type: "GET",
dataType: 'json',
success: function (data) {
console.log(data);
viewModel.assets(data);
}
});
the data is displayed correctly in the table when the page is loaded, but when I start typing in the search input, all the data disappears.
I would appreciate it if someone could explain what I am doing incorrectly in the AJAX load? TIA
You are better off creating a ViewModel function, so the viewmodel only accesses data within itself:
$(function() {
$.ajax({
url: '/Assets/getJson/',
type: "GET",
dataType: 'json',
contentType: "application/json",
success: function (data) {
console.log(data);
var viewModel = new ViewModel(data);
ko.applyBindings(viewModel);
}
});
});
function ViewModel(assets) {
var self = this;
self.assets = ko.observableArray(assets);
self.allAssets = assets;
self.query = ko.observable('');
self.search = function(value) {
self.assets.removeAll();
for(var x in self.allAssets) {
if(self.allAssets[x].name.toLowerCase().indexOf(value.toLowerCase()) >= 0) {
self.assets.push(self.allAssets[x]);
}
}
};
self.query.subscribe(self.search);
}
I have resolved the problem.
I was not populating the assets array. This is the updated ajax call:
$.ajax({
url: '/Assets/getJson/',
type: "GET",
dataType: 'json',
contentType: "application/json",
success: function (data) {
console.log(data);
viewModel.assets(data);
assets = data; // THIS WAS MISSING
}
});

Categories

Resources