How to get a list of cookies with jQuery? - javascript

I'm using external library, jquery.cookies.2.2.0.min.js, and according to the documentation you get a list of all cookies like so.
jaaulde.utils.cookies.filter( /^site/ );
returns list of cookies whose names start with "site"
My code is as follows.
var all_cookies = $.cookies.filter( /^mark/ );
$('aside').html(''+all_cookies+'');
When I execute the above code though, the inner HTML of aside is [object Object]. What am I doing wrong?

This is because Jaaulde returns an object where the key is the name of the cookie and the value is the value of the cookie. So Jaaulde is returning something like this.
{ site_one: 'one',
site_two: 'two' }
You can't convert an object to a string like that. You need to iterate through each key-value pair and append those individually. Which can be done like so.
$.each(all_cookies, function(key, value) {
$('aside').append('Key: ' + key + '; Value: ' + value);
});

Related

How to iterate and print the properties of a java form object in java script?

I have a map of type
Map<String,UserForm>
where
Class UserForm {
String userName;
String password;
//setters ;
//getters;
}
Map<String,UserForm> userMap=new HashMap<String,UserForm>();
I am adding userMap to a json object and sending the object to a JSP page in an ajax call. In javascript, I need to iterate through the userMap and print its properties (userName and password).
This is what I have done so far
for(var i in ajaxResponseData.userMap)
{
if (ajaxResponseData.userMap.hasOwnProperty(i)) {
alert(' Value is: ' + ajaxResponseData.userMap[i].userName);
}
But the above way is showing undefined in the alert box. Please help..
I would suggest double-checking that the response data is coming back in the format you're expecting and then trying to access it. Also, I believe there's no need to check if it has property i, as you are already iterating over it (thus it has been found).. Try the following snippet of code:
console.log(ajaxResponseData.userMap); // to see how your data actually looks like
for (var i in ajaxResponseData.userMap) {
// use the key to access the element
console.log(ajaxResponseData.userMap[i]); // is this the value you're looking for?
}
I have also setup a small example in JsFiddle, that alerts the values: https://jsfiddle.net/kd7u4zLt/

Search key in json object based on value

I populate the options of a select input field based on json data I get from a php-script.
This works fine, but I want to show some extra info, based on the selected option.
Basically, I'm looking for a way to find the key that goes with the selected option:
$("#code").html(result[whichkey]["uniquecode"]);
This fiddle hopefully makes my question a bit more clearer.
Any help is much appreciated!
Given that the option element is created with the uniquecode of the object as its value, why do you even need to access the object again? You can just retrieve the value property of the selected option...?
Assuming this is just because you've oversimplified your example, and the objects within the array do hold other useful data which is not held in the option element itself, then you can use $.grep to filter the array of objects by the selected uniquecode, like this:
var json = '[{"uniquecode":"b32dez2","name":"John Doe","foo":"bar"},{"uniquecode":"a2df32","name":"Adam Smith","foo":"buzz"}]';
var result = JSON.parse(json);
var $sel = $('#names').change(function() {
var value = this.value;
var obj = $.grep(result, function(e) {
return e.uniquecode == value;
});
$("#code").html(obj[0].uniquecode + ' / ' + obj[0].foo)
});;
result.forEach(function(obj) {
$('<option value="' + obj.uniquecode + '">' + obj.name + '</option>').appendTo($sel)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="names"></select>
<div id="code"></div>
Note that I added the foo property to the object to show you how to access properties of the object outside of those placed directly on the option element.
Also note that I simplified the code that generates the option elements as well. If you're going to use jQuery once in your project, you may as well use it everywhere.

Access the Return value of a Stored procedure

I am calling a stored procedure 'ujo_get_id' by following code
new sql.Request()
.input('id', sql.Int, 0)
.input('fld', sql.VarChar(10), fld)
.execute('ujo_get_id').then(function( recordsets) {
console.log(recordsets[0][0]);
}.catch(function(err) {
// ... execute error checks
});
output of the console shows this { ' ': "some value" }
I want to store that(some value) value in a variable how can I do it because key is empty
I'm guessing the stored procedure has a select statement without an alias. If you can modify the stored procedure, add an alias and it shouldn't return an empty string for a key.
Something like this:
SELECT somefield
Should be changed to this:
SELECT somefield as someAliasName
If you don't have access to the stored procedure, try grabbing the key like this:
recordsets[0][0]['']
Did you try this?
console.log(recordsets[0][0][" "])
Or maybe another way if you know for sure that the stored procedure will give you only one result is converting the object into an array and checking first element:
var raw = recordsets[0][0]
var result = Object.keys(raw).map(k => raw[k])[0]
console.log(result)

How to reliably post multiple values set in a single hidden field

I end up with an array filled with values like this:
var results = ['This is result 1',
'This is result 2. It could have a comma, semicolon or anything;',
'This is result 3'
];
All of the results will be stored in a single hidden field and then parsed on the server, but I feel like this could be problematic:
$('#hidden_results').val(results.join(','));
What would be a more elegant approach to doing something like this? I need to avoid potential parsing issues when this field is processed on the server.
Thanks!
Serialize the array using JSON.
$('#hidden_results').val(JSON.stringify(results));
To deserialize the value on the client side you can do this:
var results = JSON.parse($('#hidden_results').val());
To deserialize the value in PHP, use json_decode.
You could also do this :
results = '"' + results.map(function (v) {
return v.replace(/,/g, ',,');
}).join('","') + '"';
Then you can deserialize like this :
results = results.slice(1, -1).split('","').map(function (v) {
return v.replace(/,,/g, ',');
});
You can easily find PHP equivalents to Javascript functions.

Array displays zero length and no value with each()

I am more familiar with PHP than with JQuery and kind of stuck on arrays. I have read just about all the posts on the forum on this subject but can't get it to work.
I have what I believe to be an array.
Something that would look like this in php
myArr = ['option-4' => '3','option-1' => '8', 'option-3' => '0' ];
In JQuery I can retrieve the values by use of the command
var x = myArr['option-1'];
This all works fine but what I need to do is make a string of the values. So I need to loop through the elements and add the value of the element to the string. The problem is the loop.
When I check the length of the array
alert("Elements in array "+myArr.length);
it always returns zero.
When I try something like
$.each(myArr , function(i, val) {
alert(myArr[i]);
});
Nothing shows.
I am missing something obviously, my PHP knowledge must be blocking things.
Can anyone please help?
That is not a valid JavaScript array. You want to use an object:
var myArr = {'option-4': '3', 'option-1': '8', 'option-3': '0' };
You can then iterate over all keys using a for .. in:
for (var key in myArr) {
alert(myArr[key]);
}
This is equivalent to a associative array in PHP. Note that you need to use the explicit key to access an element, you cannot use an index, eg myArr[0].
If you want to use jQuery:
$.each(myArr , function(key, val) {
alert(key + ": " + val);
});

Categories