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)
Related
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
In my Angular app I'm returning results via an API call, and allowing users to filter those results through a series of checkbox selections. Right now I'm running into an issue where, while results are returned as expected when one value is sent for a certain filter, when multiple values are selected (like filtering by more than one zipcode, for instance) I get zero results printed to the view. No errors, just no results.
After scratching my head for a while, using Chrome devtools network tab, I finally determined that the problem is that rather than wrapping each item in quotes in the payload - like this: "90001", "90002", what's being sent is this: "90001, 90002". In other words, quotes are wrapped around as if it were one value, not two.
This is the code, where I'm using a "join" to put together the values that are selected:
this.sendZipcode.emit(this.zipcodeFilters.text = arr.length === 0 ? undefined : arr.join(','));
I'm not sure how I can adjust the way this "join" is constructed, or find some other solution instead of "join", in order to have each item wrapped in quotes, rather than wrapped like one long string.
FYI, this is what I see in the network tab of Chrome devtools after selecting two zipcodes. As I explained, it's wrapped like one string, rather than as two values:
addresses.zipCode: {$in: ["90001, 90002"]}
Array.prototype.join will return a string. So you are converting your array to a single string which is being sent as a string. You want to send an array. Simply remove the join call and return arr directly.
String: "value, value"
Array: "value", "value"
This has driven me "doo-lally" this afternoon!
A vendor (Zaxaa) uses a multi-dimentional form thus:
<form method="post" name="zaxaa" action="xxxx">
<input type="text" name="products[0][prod_name]" value="ABC">
<input type="text" name="products[0][prod_type]" id="pt" value="FRONTEND">
</form>
** This is my understanfing of how a multdimentional array is set up, and it seems to pass the variables to the server OK.
However, dependant on what other inputs are set to on the test form, the [prod_type] (and others) may need to change to "OTO" This is obviously going to be a javascript function, (but not the variant that starts with "$" on code lines ... whatever that type is!)
I have tried
document.zaxaa.products[0].prod_type.value
document.getElementById('products[0][prod_type]').value
document.getElementsByName('products[0][prod_type]').value
but in everycase, I get "products is not defined". (I have simplified the form as there are ten product[0] fields)
I've solved it... mainly a glaring error on my part. The getElementById worked fine ... except in my test script I'd used getElementById[xxx] and not getElementById(xxx)!! ie "[" rather than "(" Does help if you get the syntax right!
But I will take notice of those other methods, such as enclosing both array arguments in ["xxx"].
getElementById didn't work because the only one of those elements that has an id is the second input, with id="pt".
On any modern browser, you can use querySelector to get a list of the inputs using a CSS selector:
var nameInput = document.querySelector('input[name="products[0][prod_name]"]');
var typeInput = document.querySelector('input[name="products[0][prod_type]"]');
Then use their value property. So for instance, to set the name to "OTO":
document.querySelector('input[name="products[0][prod_name]"]').value = "OTO";
Use querySelectorAll if you need a list of relevant inputs, e.g.:
var nameInputs = document.querySelectorAll('input[name="products[0][prod_name]"]');
Then loop through them as needed (the list as a length, and you access elements via [n] where n is 0 to length - 1).
Re
* This is my understanfing of how a multdimentional array is set up...
All that HTML does is define input elements with a name property. That name property is sent to the server as-is, repeated as necessary if you have more than one field with that name. Anything turning them into an array for you is server-side, unrelated to JavaScript on the client. (The [0] is unusual, I'm used to seeing simply [], e.g name="products[][prod_name]".)
You can access it in this syntax:
document.zaxaa['products[0][prod_name]'].value
document.zaxaa.products[0].prod_type.value
The name is a single string, not making a nested structure to access the input. It would need to be
document.zaxaa["products[0][prod_type]"].value
// or better:
document.forms.zaxaa.elements["products[0][prod_type]"].value
The complicated name does only serve to parse the data into a (multidimensional) array on the server side, but all data will be sent "flattened".
document.getElementById('products[0][prod_type]').value
The id of your input is pt, so this should work as well:
document.getElementById("pt").value
document.getElementsByName('products[0][prod_type]').value
getElementsByName does return a collection of multiple elements - which does not have a .value property itself. Instead, access the first element in the collection (or iterate it completely):
document.getElementsByName('products[0][prod_type]')[0].value
I have a HTML page full of data separated by commas and each row ends in a (br /) tag. In Javascript I can get this from the DOM by asking for the innerHTML of the element containing the data.
My question is how to parse the innerHTML to get the data out from between the commas and start on the next line when it hits the (br /) tag?
You can probably ignore the rest as that is my question above.
When I parse each line I will start a new object and put the data into it. I'm just not sure what to do with the innerHTML!
I did put the data through a CSVtoarray function I found but ended up with an array of one large array instead of an array of arrays for each line. I can work my way through this array creating objects from the data along the way but turning the innerHTML into a single array seems an unnecessary step when I could parse the data straight into object.
The data is put there via AJAX. I can change the format that the data comes in. As I said I have it separating data with commas and (br /) tag at the end of the line. I do not know if this is stupid or not.
So, you want to csv-parse a file where newlines are indicated with <br /> instead of \n? Just use that separator in your CSV-Parser then. Simple version:
text.split("<br />".map(function(line){ return line.split(","); })
You could also split by regular expressions, like
text.split(/\s*<br ?\/>\s*/)...
If you really habe the CSV data in a DOM, you could remove all the br-element and use the remaining (text) nodes as the lines-array.
You mention that you have control over the data you're getting via AJAX, and you're right that your current approach is not the best idea. First off, you should never try to parse HTML on your own, even if you think it's "simple" – different browsers will give you different innerHTML for the exact same content. Instead, use the DOM to find the information you're looking for.
That said, the correct approach here is just to return a JSON object from the server; you'll then have direct access to your data. Nearly every server-side language has some kind of facility to output JSON, and JavaScript can parse the JSON string natively1 with JSON.parse().
From the server, return:
{items: [
{ id: 0, name: '...' },
{ id: 1, name: '...' },
...
]}
On the client (assuming jQuery),
$.getJSON('/path-to-script/', function(d) {
for (var i = 0; i < d.items.length; i++) {
d.items[i].id;
}
});
1 - in modern browsers
You could simply do this if you just want to "get the data out from between the commas":
yourElem.innerHTML = yourElem.innerHTML.split(",").join("");
Or if you just want an array of lines:
var lines = yourElem.innerHTML.split(",");
That'll return an array of lines with <br> elements intact. It's not clear if that's what you want, though.
I currently have the following javascript array:
var stuffs = ['a', 'b'];
I pass the above to the server code using jQuery's load:
var data = {
'stuffs': stuffs
};
$(".output").load("/my-server-code/", data, function() {
});
On the server side, if I print the content of request.POST(I'm currently using Django), I get:
'stuffs[]': [u'a', u'b']
Notice the [] at the prefix of the variable name stuffs. Is there a way to remove that [] before it reaches the server code?
This is default behavior in jQuery 1.4+...if you want the post to be &stuffs=a&stuffs=b instead of &stuffs[]=a&stuffs[]=b you should set the traditional option to true, like this:
$.ajaxSetup({traditional: true});
Note this affects all requests... which is usually what you want in this case. If you want it to be per-request you should use the longer $.ajax() call and set traditional: true there. You can find more info about traditional in the $.param() documentation.
When an array is submitted using a GET request, through a form or AJAX, each element is given the name of the array, followed by a pair of optionally empty square brackets. So the jQuery is generating the url http://example.com/get.php?stuff[]=a&stuff[]=b. This is the only way of submitting an array, and the javascript is following the standard.
POST requests work in exactly the same way (unless the json is sent as one long json string).
In PHP, this is parsed back into the original array, so although the query string can be a little strange, the data is recieved as it was sent. $_GET['stuff'][0] works correctly in PHP.
I'm not sure how Django parses query strings.
The [] indicates that the variable is an array. I imagine that the appending of the [] to your variable name is Python/Django's way of telling you it is an array. You could probably implement your own print function which does not show them.