I have the exact same code running on two different servers, with the route returning a collection to an AJAX call. On my local machine, the response comes through as an array but on the remote and a coworker's machine it comes through as an Object.
Definitely the same code (pushed from local, pulled to remote)
The collections are definitely in the same format (did a dd() and they're the same)
The request and response headers are the same
It works on the remote if I DON'T sort the collection first, but that makes no difference to my local, and the dd()s look exactly the same.
Local response example (15 entries):
[{id: 80, title: "Banner, Bruce", eventColor: "green", order: 1, availability: false},.....]
Remote response example (29 entries)
{"0":{"id":18,"title":"Bond, James","eventColor":"green","order":1,"availability":false},.....}
AJAX:
$.ajax({
url: '/roster/' + roster_type + '/resources',
processData: false,
contentType: false,
async: true,
cache: true,
type: 'POST',
data: formData,
dataType: 'JSON'
}).done(function (resources) {
// This line right here works fine on my machine because the array has a length,
// not on the remote where resources.length is undefined
if(resources.length > 10 && view.type == 'resourceTimeGrid') {
changeView('resourceTimelineDay');
}
successCallback(resources);
getRosterEvents();
}).fail(response => {
showErrorMessage(response);
failureCallback(response);
});
The sortBy method sorts the collection by the given key. The sorted
collection keeps the original array keys, so in this example we'll
use the values method to reset the keys to consecutively numbered
indexes:
(Source: https://laravel.com/docs/6.x/collections#method-sortby - emphasis mine)
Using values() resets the array indexes, so JavaScript then sees a nice numbered array.
Related
I have 3 MongoDB collections and each of them are defined something like:
#app.route('/getMyData', methods=['GET'])
def getMyData():
myDataCollection = db["data_1"]
data = list(myDataCollection.find({},{"Name":1,"Website":1,"Twitter":1,"Description":1,"_id":0}))
return jsonify(data=data)
Then I retrieve these data using AJAX requests (one for each collection so 3 requests) as follows:
function getDataFromDB() {
$.ajax({
url: '/getMyData',
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
// code goes here
}
});
}
How can I simplify this? It seems like I cannot query multiple collections in MongoDB.
MongoDB is designed so that each operation/query deals with one collection.
MongoDB CRUD Introduction
The design of your DB should take this into consideration. So if you need lists of each collection you'll have to have one for each.
As Blakes Seven mentioned, what you could do is set up some server side script that makes the three calls, then organises the response 'data' so that you only have one call in your application. You're still having to make three DB calls though; just depends on your application/DB/server design.
I know this has been asked multiple times, but unfortunately it's still unclear to me. How do I pass array of integer as parameter to the url of an Ajax call? I need the elements of the array to show in the url.
This is inside script tags in the View :
function DeleteRoom(id, IDarray) {
$.ajax({
url: "/api/Room/DeleteRoom?RoomId=" + id + "&userDevicesId="+ IDarray,
type: "DELETE",
dataType: 'json',
data: IDarray, //data that will be passed to the array (?)
traditional: true, //if I get it right, this serializes the array
success: function (data) {
... }
});
}
This is the API
public void DeleteRoom (int id, [FromUri] int[] IDarray)
This only reads the first element in the array from database, and so it deletes only the first element. It's like I'm passing Int! Then the browser crashes (stop script) and I get this error
DELETE .../api/Room/RemoveRoomWithDevices?RoomId=2392&userDevicesId=1549
204 No Content 62ms
XML Parsing Error: no element found Location: moz-nullprincipal
Is the url syntax wrong? Or else, is there suggestions to make this work?
You can use JSON.stringify()
here is your url
url: "/api/Room/DeleteRoom?RoomId=" + id + "&userDevicesId="+ JSON.stringify(IDarray)
Btw why you are using again a data attribute in ajax call..? Since you have included data array in the url.
I'm getting some values from a WCF Data Service right, but I don't know how to handle this information. Here goes my ajax code:
$.ajax({
url: "../Services/ChannelWCF.svc/QuotaSet?$filter=month(Date) eq 12",
dataType: "json",
success: function (data) {
console.log(data)
}
And here that I get from the console:
An array with 2 objects that I'm not able to handle. I need to get the values from each object of the array returned and save it to another variables. I tried iterating in "data" with $each(....) but I always get "undefined" from the console when I try to print the values of each object.
Inside the data object there are two fields. value is the one you want. Use the following:
$each(data.value,function(){.....})
I am loading a large (~300 MB) JSON file by using the following code:
$.ajax({
type: 'GET',
url: path,
dataType: 'json',
data: {},
async: false,
success: function(json_object) {
console.log("success!");
} error: function(request, error) {
console.log(request["statusText"]);
}
});
Running it outputs "InternalError: allocation size overflow". Is there any way to get around this that does not involve making the file smaller?
You'll need to set up a buffer. However, why on earth are you passing so much data? That would be an extremely unreasonable wait for any user.
EDIT
Buffering isn't really something you can do from the ajax side (according to How to buffering an Ajax Request?). However, you can set something up server side (if it's your server returning the data) to send it in pieces, then use ajax to request each piece.
If it's not your server, or your requesting from an API or something, then look and see if they accept any parameters to define the size of the return object - this way you can request it in chunks.
I have a C# web application which uses ajax method to GET and POST data. Is there any difference between GET and POST methods in passing data (in case of contentType,data,dataType)?
$.ajax({
type: 'GET',
url: "url",
contentType: "application/json; charset=utf-8",
data: { value: "data" },
dataType:"json",
success: function (data) {
alert(data);
},
error: function (data) {
alert("In error");
}
});
});
GET encodes the information into the url, the more info you GET the longer your URL becomes.
POST stores data in an array and passes that array to the next page. your Url remains unmodified.
While that may not seem like a huge deal, URLs do have a maximum length and errors will ensue if you exceed it. In addition and call to a specific url may fail due to the modifications GET makes. Apart from that, They are similar enough in function to be interchangeable for most purposes.
In normal form method also GET is used to sent some insensitive small chunk of data to server in querystring, whereas POST is used for sending large and secure data to the server
In case of using ajax GET is commonly used, POST is feasible only when you have to do DB interactions on server or there's some sensitive data involved, read more here http://www.jquery4u.com/ajax/key-differences-post/