How to insert data, in key value pairs, into HTML - javascript

I have returned a form with some key value pairs populated. Depending on user interaction I want to insert some of them into my HTML. I have found some answers using AJAX but could not workout how to access the key value pairs via javascript. I do not want to use jquery yet as I want understand how javascript and the DOM works first. Below is an idea of what I want to do
<script>
function changeanchor(urlitem) {
document.getElementById("urlanchor").innerHTML = "";
while ($urls as $url) {
if (urlitem == $url->item) {
document.getElementById("urlanchor").innerHTML .= $url->urlanchor;
}
}
</script>
I know "$urls as $url" etc is PHP but I thought it was the easiest way to explain what I need to do.
I use PHP to generate the function call but I am unable to get it to display here it (pieces of code do not display)

Like so?
<script>
function changeanchor(urlitem) {
document.getElementById("urlanchor").innerHTML = "";
for (i in urls) {
var url = urls[i];
if (urlitem == url.item) {
document.getElementById("urlanchor").innerHTML += url.urlanchor;
}
}
</script>
urls was never defined so this code won't execute unless urls stores a bunch of url objects with those properties.
In order to create a url object that acts like the one you try to use, either use JSON to pipe it to the JavaScript or make an object:
var urls = [
{
'item': 100,
'urlanchor': 'foo'
}, {
'item': 200,
'urlanchor': 'bar'
}
];

are you asking about the setting key value pair data in a dome object then,
$('body').data('foo', 52);
link for help:-
http://api.jquery.com/data/

Related

Search value in JSON and return to console

I am trying to search a value in a JSON file using a input field from the user through the browser.
A sample JSON object from the array of objects looks like this:
I have an event listener to wait for click from the user. After the user clicks the function will go to the api json site and retrieve all the data.
Next I would like to search through that JSON data for what the user typed in.
Example:
user input: "Cannonball"
expected output: 196 (buy_average)
However I am unable to figure out how to search through the object array.
Here's what I got:
the parameter "data" is the JSON objects that was retrieved from API. I know that works properly because I'm able to display it in the console.
function renderHTML(data) {
var searchVal = document.getElementById("search").value;
console.log(searchVal);
for (i=0; i<data.length; i++) {
if (data["i"].name == searchVal) {
console.log(data["i"].buy_average);
}
}
};
As of right now I'm just trying to figure how to look through an object array after retrieving it from the web and display it to the console.
When I click on the button nothing in the console appears to be happening except for the user's input. How can I fix this?
Try not using i as a string - use it as an integer instead:
if (data[i].name == searchVal) {
console.log(data[i].buy_average);
}
If data is an object, the length property will give you undefined. You can get the values using Object.values() and then iterate over the properties.
let data = {
0:{ id:0,name:"aa" },
1:{ id:1,name:"Cannonball"},
2:{ id:2,name:"xx" },
};
let searchVal = "Cannonball";
Object.values(data).forEach(e=>{
if(e.name === searchVal){
console.log("This is the object: ");
console.log(e);
}
});

How to store data in an array that is stored in a variable?

Following is my problem:
I am testing a system now, that has multiple ID's in every request. There are 2 ID's I want to store in an array and let them run again a response later.
Following is the Body I recieve
{
"id" = 1234;
"Name" = "Meier"
}
So, I store the ID normally with
var body = JSON.parse(responseBody);
postman.setEnvironmentVariable("ID", body.id);
with that I can store 1 ID in the variable, but can't put a second one in it. For that I would have to duplicate the request, set a second variable, change code everytime the needed cases are changed.
What I want to know now is: How can I store multiple ID's in a Environment Variable to compare them with a response at the end of the collection?
I'm not entirely familiar with postman, but if I'm understanding correctly and you want to store up the Id's from the response then you could use something like -
var body = JSON.parse(responseBody);
var storedIds = postman.getEnvironmentVariable("ID");
if(storedIds) {
storedIds.push(body.id)
} else {
storedIds = [body.id]
}
postman.setEnvironmentVariable("ID", storedIds);
Edit
From my own googling, it appears you cannot store arrays in environment variables in postman. Therefore you could try doing something like this -
var body = JSON.parse(responseBody);
var storedIds = postman.getEnvironmentVariable("ID");
if (storedIds) {
storedIds = storedIds.concat(',' + body.id)
} else {
storedIds = body.id
}
postman.setEnvironmentVariable("ID", storedIds);
Then when you want to read it back out to loop over it or whatever you want to do you can use
var idsArray = postman.getEnvironmentVariable("ID").split(',')
which will split the string up to give you an array.

How to get to request parameters in Postman?

I'm writing tests for Postman which in general works pretty easily. However, I now want to access some of the data of the request, a query parameter to be exact.
You can access the request URL through the "request.url" object which returns a String. Is there an easy way in Postman to parse this URL string to access the query parameter(s)?
The pm.request.url.query.all() array holds all query params as objects.
To get the parameters as a dictionary you can use:
var query = {};
pm.request.url.query.all().forEach((param) => { query[param.key] = param.value});
I have been looking to access the request params for writing tests (in POSTMAN). I ended up parsing the request.url which is available in POSTMAN.
const paramsString = request.url.split('?')[1];
const eachParamArray = paramsString.split('&');
let params = {};
eachParamArray.forEach((param) => {
const key = param.split('=')[0];
const value = param.split('=')[1];
Object.assign(params, {[key]: value});
});
console.log(params); // this is object with request params as key value pairs
edit: Added Github Gist
If you want to extract the query string in URL encoded format without parsing it. Here is how to do it:
pm.request.url.getQueryString() // example output: foo=1&bar=2&baz=3
pm.request.url.query returns PropertyList of QueryParam objects. You can get one parameter pm.request.url.query.get() or all pm.request.url.query.all() for example. See PropertyList methods.
It's pretty simple - to access YOUR_PARAM value use
pm.request.url.query.toObject().YOUR_PARAM
Below one for postman 8.7 & up
var ref = pm.request.url.query.get('your-param-name');
I don't think there's any out of box property available in Postman request object for query parameter(s).
Currently four properties are associated with 'Request' object:
data {object} - this is a dictionary of form data for the request. (request.data[“key”]==”value”) headers {object} - this is a dictionary of headers for the request (request.headers[“key”]==”value”) method {string} - GET/POST/PUT etc.
url {string} - the url for the request.
Source: https://www.getpostman.com/docs/sandbox
Bit late to the party here, but I've been using the following to get an array of url query params, looping over them and building a key/value pair with those that are
// the message is made up of the order/filter etc params
// params need to be put into alphabetical order
var current_message = '';
var query_params = postman.__execution.request.url.query;
var struct_params = {};
// make a simple struct of key/value pairs
query_params.each(function(param){
// check if the key is not disabled
if( !param.disabled ) {
struct_params[ param.key ] = param.value;
}
});
so if my url is example.com then the array is empty and the structure has nothing, {}
if the url is example.com?foo=bar then the array contains
{
description: {},
disabled:false
key:"foo"
value:"bar"
}
and my structure ends up being { foo: 'bar' }
Toggling the checkbox next to the property updates the disabled property:
have a look in the console doing :
console.log(request);
it'll show you all you can get from request. Then you shall access the different parameters using request., ie. request.name if you want the test name.
If you want a particular element in the url, I'm afraid you'll have to use some coding to obtain it (sorry I'm a beginner in javascript)
Hope this helps
Alexandre
Older post, but I've gotten this to work:
For some reason the debugger sees pm.request.url.query as an array with the items you want, but as soon as you try to get an item from it, its always null. I.e. pm.request.url.query[0] (or .get(0)) will return null, despite the debugger showing it has something at 0.
I have no idea why, but for some reason, it is not at index 0, despite the debugger claiming it is. Instead, you need to filter the query first. Such as this:
var getParamFromQuery = function (key)
{
var x = pm.request.url.query;
var newArr = x.filter(function(item){
return item != null && item.key == key;
});
return newArr[0];
};
var getValueFromQuery = function (key)
{
return getParamFromQuery(key).value;
};
var paxid = getValueFromQuery("paxid");
getParamFromQuery returns the parameter with the fields for key, value and disabled. getValueFromQuery returns just the value.

object has no method push in node js

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

Passing an array of ints with node-soap

I'm using node-soap with a service and everything works but I need to send an array of ints and I find that I can only send the first one because I can't find the correct way to build a JS object to represent this array.
I've been looking at similar questions but I couldn't find the answer to my question.
I need to generate a XML property like the following one:
<ns1:ArrayOfInts>
<!--Zero or more repetitions:-->
<arr:int>2904</arr:int>
<arr:int>3089</arr:int>
<arr:int>4531</arr:int>
</ns1:ArrayOfInts>
by passing an object that contains the array:
soapObject = {
somefields,
"ns1:ArrayOfInts": {
Something goes here
},
};
Any idea how to create the JS object?
I had the same problem and used $xml property to add raw XML to the request and attributes to set the arr namespace:
var fields = [2904, 3089, 4531];
soapObject.arrayOfInts = {
attributes: {
'xmlns:arr': 'http://schemas.microsoft.com/2003/10/Serialization/Arrays'
},
$xml: fields.map(function(value) {
return '<arr:int>' + value + '</arr:int>';
}).join('')
};
This code will generate the following request:
<ns1:arrayOfInts xmlns:arr="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<arr:int>2904</arr:int>
<arr:int>3089</arr:int>
<arr:int>4531</arr:int>
</ns1:arrayOfInts>

Categories

Resources