Page 1 of 1

Response to an array

Posted: Tue May 07, 2013 6:34 pm
by Michael Pierce5821971

Is there a way to just store all user id's that are returned in a response to an array so that I can randomly choose a user id on a button click event? Right now I have a service that works and returns all users, but I only need the user ids into an array so I can perform a function to just retrieve one random user id out of the array and then query back to retrieve the username.


Response to an array

Posted: Tue May 07, 2013 7:11 pm
by Sergey Kozyr

This could be done with JavaScript. You should add "Run JavaScript" action to "Success" event of your datasource on "Data" tab. Next you should write javascript code where "data" variable holds all response content. For example if you need some random element of an array you can write next code:
code
var randomIndex = Math.floor(Math.random() * data.length); //Generate random array index;
var randomUserId = data[randomIndex].id; //Get user ID from response array
localStorage.userId = randomUserId; //Store user ID in localStorage variable
/code


Response to an array

Posted: Wed May 08, 2013 11:35 am
by Michael Pierce5821971

Thanks!! But the big issue was trying to put the response into a local array variable.


Response to an array

Posted: Wed Aug 07, 2013 11:58 pm
by bahar.wadia

Yes, I have the same question. How do you create a local array and then access it. I'd like to do some math on the records received. It is not clear at all.


Response to an array

Posted: Wed Aug 07, 2013 11:58 pm
by bahar.wadia

Yes, I have the same question. How do you create a local array and then access it. I'd like to do some math on the records received. It is not clear at all.


Response to an array

Posted: Thu Aug 08, 2013 6:43 am
by Anton Artyukh5836028

Hello,

In Success event for service you can save "data" variable to "window.localSavedArrayFromResponse":

precodewindow.localSavedArrayFromResponse = data;/code/pre

So in any other JS-code on current screen you can access variable "window.localSavedArrayFromResponse". This variable is saved in global JS-scope for screen.

Please note, if you want to work with this data somewhere on other screen is better idea to use for saving data localStorage-object. So your code will be looks something like this:

precodelocalStorage.setItem( "localSavedArrayFromResponse", JSON.stringify( data ) );/code/pre

And on other screen you can access data as precodevar data = JSON.parse( localStorage.getItem( "localSavedArrayFromResponse" ) );/code/pre

In both cases you can rename variable.