Jquery Ajax passing array inside data obect - javascript

I am trying to pass an object into the data property of this jquery ajax request. All work's fine, but the fields property, which is an array, does not get recognized (returns all fields, when these are the two I am requesting).
I've tried JSON.stringify, but this returns an error for 'bad request'. How do I pass this object with an array inside correctly?
function energyQuery(token){
$.ajax({
type: 'GET',
url: url,
headers: {'Content-Type': 'application/json', 'Authorization': 'Token token=' + token},
data: {
'start': '2019-01-05',
'end': '2019-01-10',
'limit': 0,
'measurement': 'analysis',
'fields': ['energy_out', 'energy_in'] // if I pass 'energy_out' it works
},
success: function(data){
//console.log(data);
response = JSON.stringify(data);
console.log(response);
},
error: function(errMsg) {
console.log('Query:' + JSON.stringify(errMsg));
}
});
}
error message:
Please note that fields MUST either be a single valid field string or a list of valid field strings.

Send it as post and point to correct datatype
var array = ['energy_out', 'energy_in'];
var dataObj = {
'start': '2019-01-05',
'end': '2019-01-10',
'limit': 0,
'measurement': 'analysis',
'fields': array
};
var data = JSON.stringify(dataObj);
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: data,
contentType: "application/json"
});
Also on back-end side create correct model to recieve data.

If you are implementing also the server side, please consider to change the array of strings to a "particular string".
What I mean?
CASE 1 : pass array as string
'fields': '[\'energy_out\', \'energy_in\'])'
Then in the server side read the string and convert it to an array.
This is the solution that I use in Java: I read a String then I convert it to an array of integer,strings,... and so on.
CASE 2: use a particular separator, pass the field as a string;
'fields': 'value1,value2,value3'
Supposing you use , as separator, then you must split string by ,.
It's better to ask (via web service) arrays as a single string so each client can implement in a simple way of to pass data in the get method.

'fields': ['energy_out', 'energy_in']
It's not a standard json format. just change the type of parameter 0 'fields': 'energy_out,energy_in' and when receive use split,

Related

jQuery AutoComplete not rendering correctly

I have two jQuery autocomplete components on my site. Both nearly exactly the same however, one displays correctly and one doesnt.
The code for the working one is:
#Html.TextBoxFor(model => model.Part, new { #id = "txtPartCode" })
$('#txtPartCode').autocomplete({
minLength: 3,
source: function (request, response) {
$.ajax({
url: apiEndpoint + 'api/Part/Filtered/' + $('#txtPartCode').val(),
method: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
response(data);
}
});
}
});
The code for the failing one is:
#Html.TextBoxFor(model => model.ParentRequestId, new { #id = "txtParentRequest" })
$('#txtParentRequest').autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: apiEndpoint + 'api/Request/' + $('#txtParentRequest').val(),
method: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
response(data);
}
});
}
});
As you can see they are very similar. The response from the API for the working one is ["string1", "string2", "string3"] and for the broken one is [1,2,3,4].
The jQuery libraries are included in my bundles so should be the same on all pages. I have used jquery.js, jquery-ui.js and jquery-ui.css.
I cant work out the difference between them as to why the one does not display correctly.
The broken one displays as follows:
Any help with this would be greatly appreciated. Please let me know if more info is required
EDIT - Solution But Why?
So the issue appeared to be that the jQuery Autocomplete component did not like an input of an array of integers.
This seems quite strange to me and I believe an autocomplete should be able to cope with integers. Does anybody know why this is or if there is a setting to handle it?
jquery-ui autocomplete would work good with String responses. Your response data should be a list of strings and not integers (as the value attribute for the input element is always a string).
Try converting the response data to string either at client side or server side. I prefer doing it at the client side.
$('#txtParentRequest').autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: apiEndpoint + 'api/Request/' + $('#txtParentRequest').val(),
method: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
// Convert the integer list to a string list
var stringList = $.map(data, function(element){
return element + "";
})
response(stringList );
}
});
}
});
It's because JQuery autocomplete supports only two array formats as explained below:-
source Type:
Array or String or Function( Object request, Function
response( Object data ) ) Default: none; must be specified Defines the
data to use, must be specified. Independent of the variant you use,
the label is always treated as text. If you want the label to be
treated as html you can use Scott González' html extension. The demos
all focus on different variations of the source option - look for one
that matches your use case, and check out the code.
Multiple types supported: Array: An array can be used for local data.
There are two supported formats: An array of strings: [ "Choice1",
"Choice2" ] An array of objects with label and value properties: [ {
label: "Choice1", value: "value1" }, ... ] The label property is
displayed in the suggestion menu. The value will be inserted into the
input element when a user selects an item.
You can have a look at API documentation for more details:
http://api.jqueryui.com/autocomplete/
So as per me you can convert your array to string from backend or you can convert it by Javascript like this:-
$('#txtParentRequest').autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: apiEndpoint + 'api/Request/' + $('#txtParentRequest').val(),
method: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
if(data!=null && data.length>0){
var numberArray=data.map(String);
response(numberArray);
//Or response(data.map(String));
}
}
});
}
});

Can Mockjax handle single IDs Api from Json file

I'm using Mockjax for the first time to mock a Restful API which will return a series of data given an id. Right now i have a json file that has several Items, and i would like to have a function inside Mockjax (or where necessary) to return only the queried ID. how can I achieve this?
current code :
$.mockjax({
url: "/Api/Cases/{caseId}",
proxy: "/mocks/cases nuevo.json",
dataType: 'json',
responseTime: [500, 800]
});
$.ajax({
type: 'GET',
url: '/Api/Cases/',
data: {caseId: taskId},
success: function(data){
//use the returned
console.log(data);
}
});
current error:
GET http://localhost:8080/Api/Cases/?caseId=100 404 (Not Found)
Great question... yes, you can do this. But you'll have to write the functionality yourself using the response callback function and then making a "real" Ajax request for the file (instead of using the proxy option). Below I just make another $.ajax() call and since I have no mock handler setup for that endpoint, Mockjax lets it go through.
Note that setting up URL params is a little different than you suggest, here is what the mock setup looks like:
$.mockjax({
url: /\/Api\/Cases\/(\d+)/, // notice the regex here to allow for any ID
urlParams: ['caseID'], // This defines the first matching group as "caseID"
responseTime: [500, 800],
response: function(settings, mockDone) {
// hold onto the mock response object
var respObj = this;
// get the mock data file
$.ajax({
url: 'mocks/test-data.json',
success: function(data) {
respObj.status = 200;
// We can now use "caseID" off of the mock settings.urlParams object
respObj.responseText = data[settings.urlParams.caseID];
mockDone();
},
error: function() {
respObj.status = 500;
respObj.responseText = 'Error retrieving mock data';
mockDone();
}
});
}
});
There is one other problem with your code however, your Ajax call does not add the ID to the URL, it adds it to the query string. If you want to use that API endpoint you'll need to change your source code $.ajax() call as well. Here is the new Ajax call:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId, // this will add the ID to the URL
// data: {caseId: taskId}, // this adds the data to the query string
success: function(data){
//use the returned
console.log(data);
}
});
Note that this presumes the mock data is something like:
{
"13": { "name": "Jordan", "level": 21, "id": 13 },
"27": { "name": "Random Guy", "level": 20, "id": 27 }
}
What I have ended up doing, is: I have left the $.mockjax function untouched, and i have manipulated the data inside the ajax request, using jquery's $.grep function as follows:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId,
success: function(data){
//note you have to parse the data as it is received as string
data = JSON.parse(data);
var result = $.grep(data, function(e){ return e.caseId == taskId; });
//since i'm expecting only one result, i pull out the result on the 0 index position
requestedData = result[0];
}
});
The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test see Jquery API, And since our test is that the caseId attribute of the element equals to the taksId variable sent, it will return all the elements that match the given Id, in this case, only one, this is why I've taken only the result on the 0 index position requestedData = result[0];
**Note: **
A more suited solution would be a mixture between what i've done and #jakerella 's answer, since their method implements the find element method inside the mockjacx function, and my function presumes a usual JSON response:
[{"caseId": 30,"name": "Michael"},{"caseId": 31,"name": "Sara"}]

.serialize() an array of variables in Javascript

I have a list of variables available to me and I want to send it via $.ajax post. What format would I have to keep these in to use the function .serialize? I keep getting this error:
Object 'blank' has no method 'serialize'
I've tried to make them an array and I've tried jQuery.param(). I have a feeling this is simple but I can't seem to get it. Thanks!
var $data = jQuery.makeArray(attachmentId = attachmentID, action = 'rename', oldName = filename, newName, bucketName, oldFolderName, newFolderName, projectId = PID, businessId = BID);
var serializedData = $data.serializeArray();
//alert(theurl);
$.ajax({ type: "post", url: theurl, data: serializedData, dataType: 'json', success: reCreateTree });
.serialize is for form elements:
Encode a set of form elements as a string for submission.
The $.ajax documentation says for the data option:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So all you need to do is passing an object. For example:
$.ajax({
type: "post",
url: theurl,
data: { // <-- just pass an object
attachmentId: attachmentID,
action: 'rename',
// ...
},
dataType: 'json',
success: reCreateTree
});
It seems you're used to the PHP style of array's (associated arrays). In Javascript, objects are basically the same thing (though can be MUCH more complicated).
So if you are trying to create an array like this in php it would be
$array = array(
"foo" => "bar",
"bar" => "foo",
);
in Javascript using an object instead of an array it would be
var arr = {
foo: "bar",
bar: "foo"
}

JQuery $.ajax() post - data in a java servlet

I want to send data to a java servlet for processing. The data will have a variable length and be in key/value pairs:
{ A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
The data doesn't need to be formated this way, it is just how I have it now.
var saveData = $.ajax({
type: "POST",
url: "someaction.do?action=saveData",
data: myDataVar.toString(),
dataType: "text",
success: function(resultData){
alert("Save Complete");
}
});
saveData.error(function() { alert("Something went wrong"); });
The $.ajax() function works fine as I do get an alert for "Save Complete". My dilemna is on the servlet. How do I retrieve the data? I tried to use a HashMap like this...
HashMap hm = new HashMap();
hm.putAll(request.getParameterMap());
...but hm turns out to be null which I am guessing means the .getParameterMap() isn't finding the key/value pairs. Where am I going wrong or what am I missing?
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:abc#invalid.ts
you can use ajax post as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:
&A2168=1&A1837=5&A8472=1&A1987=2
On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:
Enumeration keys = request.getParameterNames();
HashMap map = new HashMap();
String key = null;
while(keys.hasMoreElements()){
key = keys.nextElement().toString();
map.put(key, request.getParameter(key));
}
To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

convert objects to JSON and send via jquery ajax

I've 1 object:
var myobject = {first: 1, second: {test: 90}, third: [10, 20]};
and I want to send it as JSON string via jQuery ajax.
How can I do it? (i test JSON.stringify(), but it doesn't work in IE)
Thanks.
If you specify your myobject as the data parameter to the jQuery .ajax() method, it will automatically convert it to a query string, which I believe is what you want.
e.g.
$.ajax({
url: /* ... */,
data: myobject,
/* other settings/callbacks */
})
From the docs:
data
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs.
You should be able to pass your object to the 'data' parameter of the ajax function -
$.ajax({
type: "POST",
url: "some.php",
data: myobject ,
success: function(msg){
alert( "Data Saved: " + msg );
}
});

Categories

Resources