Jquery post a Array - javascript

I am having a Array which is generated by my Javascript in run time.
once that array is full with all the values I want to send it using POST to the server.
How can I do that ...
Pseudo code:
for(i=0;i<result.data.length;i++)
{
result.data[i].id
}
$.post("receiver.php", { xxxxx }, function(data){ console.log(data);});
How can I get that xxxx updated in the post
I checked the documentation in jquery but they are expecting to give all the values in POST.I do not want to do that.
Also, I want to send post only once so that traffic will be less.

EDIT
You can use join() to get all your array values converted to a string, using some char to separate it.
EDIT 2: As Kumar said he was using 2 arrays
var idsArray;
var namesArray;
for(i=0;i<result.data.length;i++)
{
idsArray[] = result.data[i].id;
namesArray[] = result.data[i].name;
}
var ids = idsArray.join(",");
var names = namesArray.join(",");
$.post("receiver.php", { ids:ids, names:names }, function(data){ console.log(data);});

similar to iBlue's comment, You can just send an object with post; you don't have to define the object in the post function, { } are simply the delimiters to define objects, which are similar to PHP associative arrays:
$.post('reciever.php', myData, function(data){ /*callback*/ });
The only thing is that you setup myData as an object like follows:
myData = {
0: 'info',
1: 'info'
}
//or even something like this
myData = {
someProp: 'info',
someProp2: {
anotherProp: 'moreInfo'
}
}
you can also use non-numerical indexes with objects, and easily add properties:
myData[2] = 'info';
or you can loop through it, just in a slightly different way:
for(i in myData){
myData[i]; //Do something with myArr[i]
}
the for in loop will also loop through non-numerical properties. And you can still get the length of myData by
myData.length;
EDIT:
Instead of sending a string:
IDs = {}
Names = {}
for(var i = 0; i < result.data.length; i++){
IDs[i] = result.data[i].id;
Names[i] = result.data[i].name;
}
$.post('reciever.php', {IDs: IDs, Names: Names}, function(data){});
In the PHP file you would access them like so
$_POST['IDs'][0] = "some id";
$_POST['Names'][0] = "some name";
EDIT:
Actaully I think the indexes are sent as strings, so might have to do
$_POST['IDs']['0']

Not sure, but it seems like you want to do this:
var sendObj = {};
for (var i=0; i<result.data.length; i++) {
var id = result.data[i].id,
name = result.data[i].name; // or some similiar computation
sendObj[name] = id;
}
$.post("receiver.php", sendObj, function(data){ console.log(data);});
This will send the result.data as name=id-value-pairs.

Related

how do i get values from multidimensionnal table in javascript?

i have an array of urls. I insert into it values like this :
var replacementArray=[];
function insert(arr,url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
This is an example of one such URL array:
replacementArray:{
[url:"tuto.com", shorturl:"xfm1")],
[url:"youtube.com", shorturl:"xfm2")],
[url:"google.com",shorturl:"xfm3"]}
I have to compare the shorturl of this array with a string. If the strings match then i retrieve the url. Here is my first attempt at doing this :
var chaine="xfm1";//this is an example
for(var j=0;j<replacementArray.length;j++)
if (replacementArray[j][shorturl]==chaine){
var url= replacementArray[url];
}
This seems to not be working. Why is that?
Associative arrays with arbitrary keys don't exist in javascript
You can have data that works as an associative array, but then you need to use an object to store the keys.
The example data you provided is not valid JS. It is an object of arrays instead of being an array of objects. For your function to work as expected, the data
needs to be in the following format:
[
{
url: 'tuto.com',
shorturl: 'xfm1'
},
{
url: 'youtube.com',
shorturl: 'xfm2'
},
// etc...
]
The [] is for creating an array, which will have numeric indexes only.
The {} creates objects that can store key-value pairs like an associative array in other languages.
So in your function you can loop through the array indexes by incrementing i and access the values associated with your keys using replacementArray[i].shorturl or replacementArray[i]['shorturl'] (notice the string) - the way you do it is up to your preference, they both work the same.
Hope this helps!
var arr=[];
function insert(arr,url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
insert(arr,"google.com", "xfm.io1");
insert(arr,"gogle.com", "xfm.io2");
insert(arr,"gole.com", "xfm.io3");
function getUrl(yourVariable){ //chaine
for(var j=0;j<arr.length;j++)
if (arr[j].shorturl == chaine){
return arr[j].url;
}
return null;//not found yourVariable
}
var chaine= "xfm.io1"; //your Short URL
console.log(getUrl(chaine)); //testing the function
First of all you given: (which is not an acceptable data structure)
replacementArray:{
[url:"tuto.com", shorturl:"xfm1")],
[url:"youtube.com", shorturl:"xfm2")],
[url:"google.com",shorturl:"xfm3"]}
which must be like this: (array of objects)
replacementArray:[
{url:"tuto.com", shorturl:"xfm1"},
{url:"youtube.com", shorturl:"xfm2"},
{url:"google.com",shorturl:"xfm3"}]
Then to get shortUrl code will be like
function getUrl(yourVariable){ //chaine
for(var j=0;j<replacementArray.length;j++)
if (replacementArray[j].shorturl == chaine){
return replacementArray[j].url;
}
return null;//not found yourVariable
}
Read over these corrections/suggestions:
As others have mentioned, you should create an array of objects, instead of an object with arrays
Reference the property 'shorturl' either using array syntax (i.e. replacementArray[j]['shorturl']) or dot notation (i.e. replacementArray[j].shorturl). If you use array syntax then the property needs to be in a string literal (unless you create a variable to represent the field - e.g. var shorturl = 'shorturl';).
var replacementArray = [];
function insert(arr, url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
//utilize the function declared above
insert(replacementArray ,"tuto.com", "xfm1");
insert(replacementArray, "youtube.com", "xfm2");
insert(replacementArray, "google.com", "xfm3");
var chaine = "xfm1"; //this is an example
var url; //declare url here so it won't be undefined if no url is found in the array
for (var j = 0; j < replacementArray.length; j++) {
if (replacementArray[j]['shorturl'] == chaine) {
//need to reference replacementArray[j] instead of replacementArray['url']
url = replacementArray[j]['url'];
}
}
console.log('url: ',url);
Consider using Array.prototype.find() or a similar functional-style method (e.g. filter() if you wanted to find multiple values) to determine the site with the matching shorturl value. That way you don't have to worry about creating and incrementing the iterator variable (i.e. j) and using it to reference elements in the array. For more information, try these exercises about functional programming in JS.
var replacementArray = [];
function insert(arr, url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
//utilize the function declared above
insert(replacementArray ,"tuto.com", "xfm1");
insert(replacementArray, "youtube.com", "xfm2");
insert(replacementArray, "google.com", "xfm3");
var chaine = "xfm1"; //this is an example
var foundSite = replacementArray.find(function(site) {
return (site.shorturl == chaine);
});
if (foundSite) { //if we did find a matching site
var url = foundSite.url;
console.log('url: ',url);
}
Try this in your 'for' loop:
if(replacementArray[j].shorturl == chaine){
// Do stuff here...
}
With [shorturl], you are accessing a property name based on the value of shorturl, which is not defined.

Looping through dynamic JSON data using javascript

I am trying to display JSON data but the key value is dynamic it varies from one POST request to another my data hierarchy is as shown in diagram:
This is the part of the code I am running,Can anyone suggest me how to display JSON data where key showed in redbox gonna change for every POST request
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'perfid': valueOne, 'hostname': $("#host").val(), 'iteration': valueThree},
success: function(data) {
$('#img1').hide();
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect.length;
for(var i = 0; i < k; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect.obj.avg_latency);
console.log(iscsi);
}
While running above snippet I am getting following error message :
data[$(....).val(...)].iscsi_lif.result.sectoutput.sect is undefined
You can use a "for in" loop to iterate over the keys of an object without having to specify the key names.
for( var key in myObject){
myValue = myObject[key];
// key will be your dynamically created keyname
}
So your code could be similar to the following:
...
success: function(data) {
$('#img1').hide();
var obj = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for(var key in obj) {
if(obj.hasOwnProperty(key)){
var iscsi = parseInt(obj[key].avg_latency);
console.log(iscsi);
}
}
}
Solution Suggestion:
for (var key in object) {
if (object.hasOwnProperty(key)) {
var element = object[key];
}
}
Yet, in your situation, maybe you'll have to do this multiple times, so I would try to extract a generic function to do this and "normalize" the processing result to an expected format that wouldn't change.
The function will only run when the expected keys exist and since the forin loop uses the object keys, every object is processed dynamically.
This should work:
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for (var i = 0; i < k.length; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
console.log(iscsi);
}
The variable should be put inside brackets.
Also, it seemed to me that k was simply defined as length of an array, I removed that and put it to the for loop.
Since you have obj defined as varible you should use [], so it will be [obj], e.g :
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
Hope this helps.

Merging JSON data from multiple URL's and sorting them based on a key

I need some help with Javascript. I have some data that I received from youtube APIs. The data is retrieved from the below URL's (I only showed 2 but I get from multiple other channels too)
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCpVm7bg6pXKo1Pr6k5kxG9A
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCLQZTXj_AnL7fDC8sLrTGMw
Every item in these json files has "publishedAt" value. Now I want to merge the data from both the JSON files and sort the list based on the "publishedAt" key i.e., the latest uploaded videos shown first.
Here is what I have currently which works perfectly for one file (I didn't do any magic, the URL itself sorts the items based on date)
$.getJSON(sourceUrl, function (data) {
//console.log(data);
//var you_data = JSON.stringify(data);
var videosCount = data.items.length;
console.log("The number of videos is: " + videosCount);
for ( i = 0 ; i < videosCount; i++) {
var title = data.items[i].snippet.title;
var url = "https://www.youtube.com/watch?v=" + data.items[0].id.videoId;
$("#reply").append(" " + title + "<br><br><br>");
//console.log(title);
//console.log(url);
};
});
How do I get this done?
EDITED (my thoughts):
Something that I can think of is using nested objects. I can create a new object that two looks something like:
grand_parent_object = { {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}, {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item2 as shown in the JSON file}}, etc}
here the parent_object is {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}
Maybe I should sort the parent_objects based on their 'publishedAt' values first and then that should do the job???? PS: 'publishedAt' in parent_object is the same as 'publishedAt' in the 'wholeItem' value.
Solution:
I used Ross's logic and it worked. I had issues with .getJson since it wouldn't update the global variable, wholearray. So I used .ajax and it worked. Here is my working code:
function getAjaxData(sourceUrl) {
$.ajax({
async:false,
url:sourceUrl,
success: function(data) {
var videosCount = data.items.length;
for ( var i = 0 ; i < videosCount; i++) {
var tempobject = {};
tempobject.published = data.items[i].snippet.publishedAt;
tempobject.wholeItem = data.items[i];
wholearray.push(tempobject);
}
}
});
}
One solution is to create a new array of object literals, then sort the array based on the key:
var array = [];
$.getJSON(url, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
$.getJSON(otherUrl, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
Have a listener that waits for both AJAX calls to finish, then you can sort:
array.sort(function(a,b) { return a.published - b.published; });
This question gives more info on sorting
This may not be the most efficient way, but it's the first that comes to mind and will work swell!

How to handle multiple fieldnames and values as variables using mongoose "where" method?

I am using the where method to pass the fieldname and the value to a Mongoose fineOne query.
Model.findOne().where(field1,value1).where(field2, value2).exec(function(err,callback) {
...
}
The above works find. However, my problem is that we have more fieldnames and values to be passed to the above statement. I don't know exactly the number of fieldname and the value to be used since it depends on the user's configuration. I like to use a for loop to dynamically build the where clause, but don't know how. Can someone help?
Assuming a values object that contains the values of the fields you want to save, and a fields array that contains the name of the fields to save, you could do it like this:
var values = {p_last_name: 'Smith', p_first_name: 'John', ... };
var fields ['p_last_name', 'p_first_name'];
var query = Model.findOne();
for (var i=0; i<fields.length; ++i) {
var field = fields[i];
query.where(field, values[field]);
}
query.exec(callback);
You can create a variable for the conditions:
var conditions = {};
for (i = 1; i < 3; i++) {
conditions['field' + i] = 'value' + i;
}
The conditions object will look like this:
console.log(conditions);
Object {field1: "value1", field2: "value2"}
This for loop is of course just an example, you can use kind of loop to build the object. Then you can execute the findOne() query this way:
Model.findOne(conditions, function(err, item) {
// ...
});

Creating a JSON dynamically with each input value using jquery

I got a situation where I would like to read some data off a JSON format through PHP, however I am having some issues understanding how I should construct the Javascript object to create the JSON format dynamically.
My scenario is as follows:
<input title="QA" type="text" class="email">
<input title="PROD" type="text" class="email">
<input title="DEV" type="text" class="email">
The Javascript code I have so far goes through each input grabs the data, I am however unable to understand how to process from here on.
var taskArray = {};
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
//how to create JSON?
});
I would like to get the following output if possible.
[{title: QA, email: 'a#a.com'}, {title: PROD, email: 'b#b.com'},{title: DEV, email: 'c#c.com'}]
Where the email is acquired by the input field value.
Like this:
function createJSON() {
jsonObj = [];
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
item = {}
item ["title"] = id;
item ["email"] = email;
jsonObj.push(item);
});
console.log(jsonObj);
}
Explanation
You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.
If you need a string, then do
jsonString = JSON.stringify(jsonObj);
Sample Output
[{"title":"QA","email":"a#b"},{"title":"PROD","email":"b#c"},{"title":"DEV","email":"c#d"}]
I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.
Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.
See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.
In your case:
var array = [];
$("input[class=email]").each(function() {
array.push({
title: $(this).attr("title"),
email: $(this).val()
});
});
// then to get the JSON string
var jsonString = JSON.stringify(array);
May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.
var obj = [];
var elems = $("input[class=email]");
for (i = 0; i < elems.length; i += 1) {
var id = this.getAttribute('title');
var email = this.value;
tmp = {
'title': id,
'email': email
};
obj.push(tmp);
}
same from above example - if you are just looking for json (not an array of object) just use
function getJsonDetails() {
item = {}
item ["token1"] = token1val;
item ["token2"] = token1val;
return item;
}
console.log(JSON.stringify(getJsonDetails()))
this output ll print as (a valid json)
{
"token1":"samplevalue1",
"token2":"samplevalue2"
}
I tried this:
// Sample JS object
var varobject = {
name: "Name",
Intern: "Test",
};
// Converting JS object to JSON string
JSON.stringify(varobject);

Categories

Resources