Sending data in array of objects to server - ajax

I am developing an app that when I don't have internet connection it must send to localStogare, later I could send the data to server when it is online, I will do this manually.
Once I get the data with JS from localStorage store it in a variable
let encuestas = [];
if ( localStorage.getItem('encuestas') ) {
encuestas = JSON.parse(localStorage.getItem('encuestas'))
}
after that, I have an array like this one:
encuestas = [
{
"code": "2124",
"sells": 2124,
"latitude": "14.8550091",
"longitude": "-90.0685453",
"visit_date": "2019-04-02",
"visit_time": "21:23:54",
"user": 1,
"answers": [
{
"question": 4,
"answer": "Si"
},
{
"question": 1,
"answer": "No"
}
]
},
{
"code": "2140",
"sells": 2140,
"latitude": "14.8550156",
"longitude": "-90.0685451",
"visit_date": "2019-04-02",
"visit_time": "21:40:13",
"user": 2,
"answers": [
{
"question": 4,
"answer": "No"
},
{
"question": 1,
"answer": "No"
}
]
},
{
"code": "2146",
"sells": 2146,
"latitude": "14.855016",
"longitude": "-90.0685448",
"visit_date": "2019-04-02",
"visit_time": "21:46:17",
"user": 2,
"answers": [
{
"question": 4,
"answer": "No"
},
{
"question": 1,
"answer": "No"
}
]
}
]
now I need to send the data with a loop to server, I have done this functions but I can't send the data, I don't receive any error message
This must receive the data index I need to send
const sendDataToServer = encuesta => {
axios({
method: 'post',
headers: {
'Authorization': `Token ${sessionStorage.getItem("token")}`
},
url: `${baseURL}customers/`,
contentType: 'application/json',
data: encuesta
})
.then(res => {
encuestas.shift()
})
.catch(e => {
console.log(e)
})
}
This must send each one to server and later, delEcuestas, must set the array as an empty array
const enviarDatos = () => {
for ( const i in encuestas ) {
sendDataToServer(encuestas[i])
}
delEncuestas();
}
I hope you can help me, thanks!!

I'm not immediately seeing why there aren't requests made when this code executes. That said we can probably get this working with some more readable and idiomatic code.
Modifying an array with shift(), that's part of the looping condition, inside the loop construct is generally discouraged (if not an actual bug). So it's worth refactoring this code anyway.
Now, assuming your backend can handle the requests in any sequence, then using the axios.all() function to make the requests asynchronous is probably advisable.
Something like this:
const enviarDatos = () => {
let axiosPromises = enquestas.map(enquesta => {
return axios({
method: 'post',
headers: {
'Authorization': `Token ${sessionStorage.getItem("token")}`
},
url: `${baseURL}customers/`,
contentType: 'application/json',
data: encuesta
});
});
axios.all(axiosPromises).then(results => {
// All promises are resolved/rejected
// E.g. results = [promiseResolution1, promiseResolution2, etc.]
delEncuestas();
}
).error((err) => {});
}

Related

Datatables AJAX POST rejected by elastic: Expected [START_OBJECT] but found [VALUE_STRING]

I am trying to fix a connection to mu local elastic instance but still getting various errors when trying to used server side call.
After various tries I came to situation when getting "Expected [START_OBJECT] but found [VALUE_STRING]".
Trying to find the reason and a solution over internet but no success.
Here is my code.
<script>
$(document).ready(function () {
var query = '{ "query" : { "match_all" : {} } }';
console.log (query);
query = JSON.stringify(query);
console.log (query);
$('#integrations').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://localhost:9200/integrations-prod/_search?size=1000&source_content_type=application/json",
//WORKS EVEN WITH GET BUT NOT AS SERVERSIDE "url": `http://czchown5029751.prg-dc.dhl.com:9200/integrations-prod/_search?size=1000&source_content_type=application/json&source=${query}`,
//WORKS EVEN WITH GET BUT NOT AS SERVERSIDE "url": `http://czchown5029751.prg-dc.dhl.com:9200/integrations-prod/_search?size=10000`,
data : function ( d ) {
return query;
},
"contentType": "application/json",
//"cache": "false",
"type": "POST",
//"jsonp": "true",
"dataType": "json",
"dataSrc": "hits.hits",
"columnDefs": [ { "defaultContent": "-", "targets": "_all" } ]
},
"columns": [
{ "data": "_source.name" },
{ "data": "_source.description" },
{ "data": "_source.valid" },
{ "data": "_source.status_id" },
{ "data": "_source.region_id" },
{ "data": "_source.validated_time" }
]
} )
});
</script>

jQuery Datatable Pipeline using server side - data not loading

I am working on jQuery datatable and trying to implement pipeline feature using server side processing. (following the code same as suggested in the below jQuery site)
https://datatables.net/examples/server_side/pipeline.html
Actual Scenario
My implementation differs only in the data part where my data is array of objects but as per the reference, the data is ajax sourced..
My Ajax response from REST API ::
{
"status": true,
"data": [{
"dbid": "xyz",
"name": "QA Pt",
"email": "a+123#gmail.com",
"isactive": true,
"Datecreated": "2018-06-04",
"lastmodified": "2018-06-04",
"newfields": {
"firstname": "QA",
"lastname": "Pt",
"viewonlyadmin": "no",
"usertype": 0
},
"userid": "85097428"
}, {
"dbid": "xyz",
"name": "QA Pt",
"email": "a+123#gmail.com",
"isactive": true,
"Datecreated": "2018-06-04",
"lastmodified": "2018-06-04",
"newfields": {
"firstname": "QA",
"lastname": "Pt",
"viewonlyadmin": "no",
"usertype": 0
},
"userid": "85097428"
}],
"recordsTotal": 597,
"recordsFiltered": 597,
"draw": 1
}
Pipeline feature and the Pagination part works perfectly but the data in table is always shown as "No matching records found"
When i tried debugging the code, in drawcallback function 'settings' object -> aoData is always empty.
Below is the screenshot of the table.
Scenario 2
The other fix I tried is by passing json.data to drawcallback function instead of drawcallback(json) in ajax success function. In this case, the data is shown in the table but the pagination part is failing. PFB the screenshot.
Any one have idea on why this data is not being applied to the table? Looking for some help on fixing this issue..
Assuming you are trying to return json from API as follows.
return Json(new
{
// this is what datatables wants sending back
draw = 1,
recordsTotal = result.Count(),
recordsFiltered = 10,
data = result
});
Just change this to return Json(result); So your json result looks like
[{
"Latitude": 18.00,
"Longitude": 23.00,
"Name": "Pune"
}, {
"Latitude": 14.00,
"Longitude": 24.00,
"Name": "Mumbai"
}, {
"Latitude": 34.004654,
"Longitude": -4.005465,
"Name": "Delhi"
}, {
"Latitude": 23.004564,
"Longitude": 23.007897,
"Name": "Jaipur"
}]
Now, in your ajax success, make datatables like this. Reason to use ajax success is it is assumed that you get all the data at one round trip to server.
$.ajax({
url: "Your API Url",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function (result) {
var my_columns = [];
$.each(result[0], function (key, value) {
var my_item = {};
my_item.data = key;
my_item.title = key;
my_columns.push(my_item);
});
$('#table1').DataTable({
"data": result,
"columns": my_columns
});
}
});

Why my ajax call do not work?

I am not able to detect why my ajax call do not work. I am trying to read the contents of text file but it do not work, The problem is control never go to .done(function(data))
function makeCustomerTree()
{
// debugger
alert('customertree');
$.ajax(
{
url:"~/bootstrap/js/LiveMap/Ajax/JsonStringCarryingData/customer-tree-json.txt",
data: {},
type: "GET"
}).done(function (data)
{
alert('done');
$('#tree_loader').html('');
tree = $.fn.zTree.init($("#customerTree"), setting, data);
tree = $.fn.zTree.getZTreeObj("customerTree");
}).fail(function (jqXHR)
{
alert('fail');
$('#tree_loader').html('<font color="red">Unable to load.</font>');//jqXHR.responseText);
});
}
Where my file customer-tree-json.txt contains the contents like this:
[
{
"icon": "/static/tree/icons/user-20.png",
"pId": 7,
"id": 18,
"itemType": "lcustomer",
"name": "sachin bhatia"
},
{
"itemType": "ldevice",
"pId": 18,
"name": "UK 06 AA 3840",
"open": true,
"id": "007060500336",
"icon": "/static/tree/icons/device-20.png"
}
]
After seeing your directory tree, relative URL has to be :
url:"/bootstrap/js/LiveMap/Ajax/JsonStringCarryingData/customer-tree-json.txt"

Attempting to load Ext store with JSON data from AJAX request returns error

Am attempting to load and Ext Store with Ext 4.0.7.
It is returning an Object doesn't support this property or method error when i call the loadRawData method on the store in the success callback of the AJAX request.
Here is the data i am loading:
{
"data": [
{
"id": 1,
"source": "1445261",
"target": "1437043",
"sourceType": "user",
"redirectUrl": "http://www.google.co.uk",
"message": "this is a notification message",
"targetType": "user",
"messageType": "notification",
"sentDate": "1354758001",
"notificationType": "notification",
"parameters": "null",
"read": "false",
"readDate": 1354758001
},
{
"id": 2,
"source": "1445261",
"target": "1437043",
"sourceType": "user",
"redirectUrl": "http://www.google.co.uk",
"message": "this is a notification message",
"targetType": "user",
"messageType": "notification",
"sentDate": "1354758001",
"notificationType": "notification",
"parameters": "null",
"read": "false",
"readDate": 1354758001
},
{
"id": 3,
"source": "1445261",
"target": "1437043",
"sourceType": "user",
"redirectUrl": "http://www.google.co.uk",
"message": "this is a notification message",
"targetType": "user",
"messageType": "notification",
"sentDate": "1354758001",
"notificationType": "notification",
"parameters": "null",
"read": "false",
"readDate": 1354758001
}
]
}
This is the store code and ajax request:
var infoStagingStore = Ext.create('Ext.data.Store', {
model: 'SCB.RMWB.InfoBar.Model.Message',
storeId: 'Staging',
autoLoad: false,
pageSize: 10,
proxy: {
type: 'pagingmemory',
reader: {
type: 'json',
root: 'data'
}
},
listeners: {
load: function(){
console.log('loaded');
}
}
});
Ext.Ajax.request({
url: '/rmwb/resources/js/app/infoBar/data/data.json',
timeout: 60000,
method: 'GET',
scope: this,
params: '',
success: function(resp) {
console.log(resp.responseText);
var store = Ext.data.StoreManager.lookup('Staging');
store.loadRawData(resp.responseText, true);
},
failure: function(resp, opts) {
},
callback: function(options, success, resp) {
}
});
Can't quite see why this is returning an error?
As in my comment, you donĀ“t need a pagingmemory store. What you need is an ajax store because the pagingstore is for allowing pagination with data you have in memory but there is no reason to use it seeing your requirement.
So if you use an standard ajax proxy, you will be able to load it in the normal way (using the .load() method). Then, when you need to add more record from the server you what you have to do is just call the load method again but with the addRecords option.
For example (untested sample):
// load store with historical data
infoStagingStore.load();
// load more records to the store from a different resource
infoStagingStore.load({
url: '/rmwb/resources/js/app/infoBar/data/data.json',
addRecords: true
});
Seeing as you've assigned your store to a variable called infoStagingStore could you not just reference that directory in your ajax call?
Ext.Ajax.request({
url: '/rmwb/resources/js/app/infoBar/data/data.json',
timeout: 60000,
method: 'GET',
scope: this,
params: '',
success: function(resp) {
console.log(resp.responseText);
//var store = Ext.data.StoreManager.lookup('Staging');
infoStagingStore.loadRawData(resp.responseText, true);
},
...

AJAX call to REST service doesn't display results in page but a call to the same response in a flat file does

I'm trying to make a call to WCF Data Services and display the results in a GridPanel.
The call works and returns the correct JSON except the GridPanel doesn't display any results.
I tried copying the returned json into a file also on the webserver and replacing the destination url for that. This worked correctly and displays the results.
So as far as I can tell the JSON, the code and the service are all correct but they don't work together properly.
The Ext JS
Ext.define('Customer', {
extend: 'Ext.data.Model',
fields: ['Id', 'CustomerName'],
proxy: {
headers: {
'Accept' : 'application/json'
},
type: 'rest',
url: 'Service.svc/Customers',
reader: {
type: 'json',
root: 'd'
}
}
});
The JSON back from the service
{
"d" : [
{
"__metadata": {
"uri": "http://localhost:52332/testservice.svc/Customers(1)",
"type": "PierbridgeShinePlatformTestModel.Customer"
},
"Id": 1,
"CustomerName": "fred",
"Invoices": {
"__deferred": {
"uri": "http://localhost:52332/testservice.svc/Customers(1)/Invoices"
}
}
},
{
"__metadata": {
"uri": "http://localhost:52332/testservice.svc/Customers(2)",
"type": "PierbridgeShinePlatformTestModel.Customer"
},
"Id": 2,
"CustomerName": "Mr Fred",
"Invoices": {
"__deferred": {
"uri": "http://localhost:52332/testservice.svc/Customers(2)/Invoices"
}
}
}
]
}

Resources