Get array from sortable jQuery serialize - javascript

I have a jQuery sortable with 3 list items with the following ID's
id_1
id_2
id_3
This gets sorted by the user and serialized using the following code
var order = $("#rank").sortable('serialize');
saveResponses(order);
and printed. Which looks like this...
id[]=1&id[]=3&id[]=2
So I've got a couple of questions...
Why does the underscore get converted to "[]="
Is there a strait forward way to get an array of the original ID's? I mean without just doing a string split, and replacing the characters?

serialize converts the data into a query string. The data is formatted (converted to an array) so you can use it in a URL as a query string (GET data).
You probably want toArray:
var order = $("#rank").sortable('toArray');

Related

How can a linq query be converted to JavaScript array containing only values?

I have a JavaScript grid library (it creates a table on the page) that accepts a JavaScript array as input, for rendering in the grid. I'm not certain, however, how to convert a Linq-to-SQL query (against a SQL Server database) to a JavaScript array containing only values.
I tried this, but it included the table column names in the JSON key (and I don't want JSON anyway, I want a JavaScript string array, unless this can be converted to an array?):
JsonConvert.SerializeObject(query)
Example of the format I need to produce:
[1,2,3],[4,5,6]
Environment: .NET Core 3.1
edit: Here is a sample of what I've currently got, this returns the less than desirable JSON (due to the query results being so large, having a JSON key for very element is going to literally double the size of the query):
Devices Table
ID Name
1 iPhone7
2 iPhone8
3 iPhone9
Needed Array (Note: no column names)
[1, "iPhone7"],[2, "iPhone8"],[3, "iPhone9"]
Current C# code in the controller method (returns undesirable key for every element currently)
var query = db.Devices;
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
Technically, you could do this:
var query = db.Devices.AsEnumerable()
.Select(d => new object[]{d.ID, d.Name});
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
But then the code on the other end of your request is going to have to translate all those arrays back into objects.
It's rarely worthwhile to complicate your model like this in order to optimize the size of your network traffic. If you're pulling enough items over the wire to make this a performance issue, you're likely to encounter a variety of other performance issues. I would first consider other options, like implementing paging.
Did you try
var query = db.Devices.ToList();
var array = JArray.FromObject(query);
return Ok(formattedResult)

How to fill a select with default object by ajax

I do have a JSON string which I receive by ajax which is correctly ordered:
{"label":"Gr\u00f6\u00dfe","values":{"4302":"XS","4184":"S","4185":"M","4186":"L","4187":"XL","4188":"XXL","5165":"3XL","4340":"4XL"}}
This JSON fills a select. The problem is, that the options are automatically reordered ( I don't know why? ) based on the value key which means that I do not get the correct option order for the select.
The option looks like:
S,M,L,XL,XXL,XS,4XL,3XL
The correct order should be
XS,S,M,L,XL,XXL,3XL,4XL
What can I do to get the correct order?
In JavaScript there is no guaranteed order for the properties on objects. Instead, you should use an array in your JSON to ensure order. Something like this:
{"label":"Gr\u00f6\u00dfe","values":[{"4302":"XS"},{"4184":"S"}, ...]}
You can format the objects in the values array anyhow you'd like, but the idea is when concerned with order, use arrays.

Proper way to use split-command and ","

i have following problem:
i have an array with a lot of data retrieved from mssql and hand it over to a jsp, i will simplify it in a example:
("test","1","test2","2")
those are 4 fields. With split(",") i seperate the 4 fields, so that i can take each value and assign them to html-objects.
Now through a coincidence i found out, that if the Array is filled as follows:
("test","1","test,2","2")
where "test,2" is one text, the split command seperates the 4 values to 5 values. Is there any alternative or way so that the split command ignores the "," that are part of a string of a field?
Greetings,
Kevin
Update:
Sorry for the missunderstandings guys here i tried to simplify the code as far as i can:
<script>
var jsArray = [];
<%
// Getting ArrayList from a request Attribute with a lot of data rows
ArrayList arrayList = (ArrayList)request.getAttribute("DSList");
for(int i=0;i<arrayList.size();i++){
%>
// Pushing each row to javascript array
jsArray.push("<%= ((ArrayList)arrayList.get(i))%>");
<%
}%>
// thats the split command that gets one line of the whole dataset
Stringarray = jsArray[x].substr(1,jsArray[x].length-2).split(","); // where x is the current record
</script>
now i can simply call each filed with
Stringarray[n] //where n is the field number
thats how the code looks like, the problem now is that if in one of the Strings in any record line is a "," then the split command obviously would give back the wrong field count. I hope now it's more clear what i mean
You can use non-greedy regex to filter out value inside "" and then remove "" from the words using array#map.
var string = '("test","1","test,2","2")';
var array = string.match(/"(.*?)"/g).map(function(item){
return item.replace(/"/g,'');
});
console.log(array);
Essentially, you have a backend data source and a front-end consumer. It just so happens that they reside on the same page, since you're using JSP to generate the page and the data. So treat it like a synchronous API, just embedded into the page.
How would you transmit data between and API and JavaScript? JSON.
So, stringify your result array into a JSON string and embed that into the JSP page, then JSON.parse() that in JavaScript and iterate as you would any other array.
Since I don't see your JSP code, I can't propose a more specific solution that what's linked here for creating JSON in JSP: how to add a list of string into json object in jsp? and Creating a json object in jsp and using it with JQuery

How to fetch comma separated values from mentioned string

I want to fetch comma separated IDs and types from below string.
I tried through split but that requires multiple split to fetch desired result.
Please suggest an efficient way to fetch desired output like like 1234,4321 using js/jquery.
var tempString=
'[{"id":"1234","desc":"description","status":"activated","type":"type","name":"NAME"},
{"id":"4321","desc":"description1","status":"inactivated","type":"type","name":"NAME1"}]';
To get "1234,4321", you can do
var ids = tempString.map(function(v){return v.id}).join(',');
If you want to be compatible with IE8, then you can do
var ids = $.map(tempString, function(v){return v.id}).join(',');
Following question edit :
If tempString isn't an array but really a JSON string, then you'd do
var ids = $.map(JSON.parse(tempString), function(v){return v.id}).join(',');
As pointed out, that's not a String in your example. Some quotation marks went missing.
At any rate, look into #dystroy's answer, but I think you are dealing with JSON objects, and you should probably be useing a json parser (or even javascripts raw eval if you must) and then fetch your components as object properties and arrays.
Check out jquery's parseJSON
You should use any Javascript parser api for JSON to decode the given string into keys and subsequent values. As mentioned by 'Miquel', jQuery has one
first off what you have above isn't a string, it is an array of objects.
BUT
if it were a string (like so )
var tempString = '[{"id":"1234","desc":"description","status":"activated","type":"type","name":"NAME"}]
[{"id":"4321","desc":"description1","status":"inactivated","type":"type","name":"NAME1"}]';
Then you would want to use something like .match();
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/match
var IDs = tempString.match(/([0-9]+)/gi);

Split to get the text between separators?

I am making a cross domain AJAX request, and because of this, I can't pass the original array from the PHP page to my HTML page. Instead, the request gets the results as a string. I have it set up so that the syntax looks like this:
([SCHOOL] Name [/SCHOOL][STATUS] Status [/STATUS])
([SCHOOL] Other name [/SCHOOL][STATUS] Other status [/STATUS])
On my HTML page, I want to be able to form an array from these different values, in the form of:
Array (
[0] =>
[0] Name
[1] Other
[1] =>
[0] Name
[1] Other status
)
This way, I can use a for loop to get specific values.
The only problem with is that split only does just that, splits things. Is there a way in JS to find the text within separators, and form an array from it? In the example again, it'd find all text within the parenthesis, and form the first array, then within that array, use the text between [SCHOOL][/SCHOOL] for the first object, and use the text between [STATUS][/STATUS] for the second object.
Ideally, you would use something more suited to storing arrays on the server side. I would recommend JSON. This would be trivial to encode using php, and decode using javascript.
If you do not have that option server side, then you can use regex to parse your text. However, you must be sure that the contents does not have your delimiters within in it.
It is not clear how you get your target data structure from your source, but I would expect something like this might work for you:
str = "([SCHOOL] Name [/SCHOOL][STATUS] Status [/STATUS])\n\
([SCHOOL] Other name [/SCHOOL][STATUS] Other status [/STATUS])"
arr =[]
m = str.match(/\(.+?\)/g)
for(i in m){
matches = m[i].match(/\(\[SCHOOL\](.+?)\[\/SCHOOL\]\[STATUS\](.+?)\[\/STATUS\]\)/)
arr.push([matches[1],matches[2]])
}
console.dir(arr)

Categories