Hello stackoverflow community, I need help with my JavaScript. How can I transfer array with id of kasce?
When I'm printing array in ajax_import.php file, it prints nothing. So probably my array is empty.
Here is my code:
function SubmitImp() {
var import_tasken = document.getElementById("import_tasken");
//import_tasken.style.display = "none";
var kasce = document.getElementsByName("impTaskCh");
var array = "";
for (i = 0; i < kasce.length; i++) {
array[i] = kasce[i].getAttribute('id');
}
$.ajax({
type: "POST",
url: 'modules/projects/ajax/ajax_import.php',
data: {
data: array,
},
success: function(data)
{
alert("Viskas ok!");
}
});
}
A couple of problems there.
First, you're not sending an array, you're sending a blank string.. Here, you put a string in array:
var array = "";
Later, you do this:
array[i] = kasce[i].getAttribute('id');
...which is trying to assign a new value to a single character of the string. You can't do that, strings are immutable in JavaScript; the line ends up not changing the string at all.
array[i] is a single character in the string. You're trying to assign a string to it.
To make array an array, use:
var array = [];
Next, and this may not be a problem, here:
data: {
data: array,
}
...you're telling jQuery to send a URI-encoded parameter called data with the value array. jQuery will call toString on array, which with a true array ends up being Array#join. That may well be what you want, you'll get something like this:
firstId,secondId,thirdId
Your PHP should look for it as $_POST['data'].
Side note: You're falling prey to The Horror of Implicit Globals because you never declare your i variable. You want to declare it.
Related
In JavaScript I have the following code:
for (i = 1; i<3; i++)
{
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
}
// get ready for transport to server and display result of string
var data = JSON.stringify(tempObj);
console.info("info: " + data);
// post string to server
$.ajax
({
type: 'POST',
url: 'out.php',
data: {data: data},
success: function(msg)
{
alert(msg);
}
});
In out.php I try to determine the result back from the server. The code is as follows:
<?php
if (ISSET($_POST['data']))
{
echo "TRUE";
}
ELSE
{
echo "False";
}
var_dump($_POST['data']);
?>
I am getting this message, AJAX alert (msg) :
**True** string(42) ""question, [object Object], [object Object]""
Apparently this message is describing the string array being passed.
What I now need to do, if the format is correct, is to be able to access the string array - maybe with JSON_decode and identify properties of the array so that I can make insertions into a MySQL database.
Thanks for any AND all help...
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
First of all. If you just test this part in the console you will see that if you concatenate JS object and the string ',' you get the string "[object Object],[object Object]". You need to first stringify the JS object before concatenating it with strings.
Second I can really seem to understand your code but looping that code will just override those variables because they are declared in the loop so that doesn't seem correct. Probably you want to get the declarations out of the loop.
Otherwise it's kind of like this - you stringify the Js object and pass it as data to the ajax.
No. To build JSON, first build a valid structure, then use JSON.stringify on the result; don't convert to string while building the structure. connectJSON + passObj will force passObj to string, resulting in "[object Object]".
Instead:
var array = []; // <== An empty array
for (i = 1; i<3; i++)
{
// Push entries into the array
array.push({id:i, ask:check_a, description:check_b});
}
// Convert to JSON
var data = JSON.stringify(array);
Side note: The code in your question didn't declare i anywhere. If your real code doesn't, it's falling prey to The Horror of Implicit Globals.* Be sure to declare your variables. :-)
* (that's a post on my anemic little blog)
The issue is here var tempObj = tempObj + connectJSON + passObj;. You are concatinating objects and strings. In that case JavaScript will use Object.prototype.toString() first and then do the concatination. and Object.prototype.toString() in case of objects will produce [object Object]. To fix this you have to create an array like below.
var tempObj = [];
for (i = 1; i < 3; i++) {
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {
id: i,
ask: check_a,
description: check_b
};
tempObj.push(passObj);
}
Also, you can skip JSON.stringify() and directly submit the JS object.
I'm trying to understand how is this deceleration :
var tempObj = tempObj + etc...;
possible ?
you cant set the value of something you just declared,
to the same thing you just declared .
I have a database server that will be running a script to generate this given file daily:
{"data": [
{"variable":"var1","value": "123"},
{"variable":"var2","value": "456"},
{"variable":"var3","value": "789"}]}
I am trying to parse this file to set three javascript variables for a HTML canvas element.
So far, I'm thinking I'll parse the JSON file
var JSONfile = './file.json';
var getData = JSON.parse(JSONfile);
Then a for loop to assign the variables
for (i = 0; i < getData.length; i++) {
var getData.variable=getData.Value;
}
And I'm hoping to get results of:
var var1 = 123;
var var2 = 456;
var var3 = 789;
But var getData.variable=getData.Value; breaks. What am I missing?
JSON.parse() expects a JSON string, when you are passing it a file.
The first thing you need to do is use AJAX to get the contents of the file into a variable. Either use a library like jQuery (see http://api.jquery.com/jquery.getjson/) or from scratch in JavaScript. But don't waste your time on the "from scratch" version unless you have to.
Use jQuery to get the contents of the file into an object, and pass the inner data (an array) to a function called doSomething():
$(function () {
$.getJSON("./file.json", function (data) {
}).success(function (data) {
myArr = data.data;
doSomething(data.data);
});
});
Here, you iterate through the passed array, which contains elements that have a .variable and a .value property. This writes both properties of each element to the console, for your viewing pleasure:
function doSomething(arr) {
for (i = 0; i < arr.length; i++) {
console.log(arr[i].variable + ': ' + arr[i].value);
}
}
You can also access the properties directly by the index as follows:
alert(jsonFromFile.data[2].variable); // Will alert "var3"
alert(jsonFromFile.data[2].value); // Will alert "789"
The sample code below currently gets an HTML page, and tries to read it into an array. The AJAX is working perfectly, and I can get a nodelist object successfully. Is it possible to somehow read this page into an array and not one singular object? Eventually I need to pull out every single member of this array individually as I am attempting in the for loop below:
$.ajax({
url: "/thePageToScrape.html",
dataType: 'text',
success: function(data) {
var elements = $("<div>").html(data)[0].getElementsByTagName("body");
for(var i = 0; i < elements.length; i++) {
var theText = elements.firstChild.nodeValue;
// Do something here
}
}
});
If all you want, like you stated in your comment, is to turn the NodeList into an array:
elements = Array.prototype.slice.apply(elements);
That's all, really.
If you are using JQuery, you can get a list of each node immediately below the body with
var elements = $(data).children("body").children();
or every node with
var elements = $(data).children("body *");
you can then loop over them with
$.each(elements, function(index, value) {
var text = this.text()
//..do something with text
});
Looks like $.parseHTML() method do exactly what you want:
Description: Parses a string into an array of DOM nodes.
var arrElements = $.parseHTML(data);
Currently I tried to reform my JSON data to a dictionary to store only needed data in an array with key and value.
* Edit to put my full code. *
This is how I do:
var myData = [];
var urlPath = "https://tipjira.pgdev.abcd.com/rest/api/2/search?jql=project=GRIFR14%2Band%2BfixVersion=15018";
var jiraMapping = [];
$.ajax({
url : "http://frparwself22.dhcp.par.abcd.com:8080/jiraproxy/jira?url=" + urlPath,
dataType : 'json',
type: 'GET',
success : function(data) {
for (var i=0; i<data.issues.length; i++) {
var obj = {};
obj[data.issues[i].key] = data.issues[i].self;
jiraMapping.push(obj);
alert(jiraMapping.length);
}
},
error : function() {
alert("Error!")
}
});
alert(jiraMapping.length);
My original data is {issues:[{...,"self":"/rest/api/2/issue/175074","key":"GRIFR14-36",...}, {...,"self":"/rest/api/2/issue/175075","key":"GRIFR14-37",...}, ...]}. And I want to reform to have the array with key and value which are key and self.
So the data in my jiraMapping should be something like [{k1:v1}, {k2,v2}, ...].
But when I tired to print the length of jiraMapping, the length is 0.
I tried to put alert to check key and value that I add to the array and the values exist.
I don't know where is the problem exactly. Please help...
Without knowing exactly what information you're passing in, it's hard to say what's going wrong. That being said, my first guess is that data/myData isn't formatted the way you think. For instance, if myData.issues.length is 0, nothing in the loop will get executed.
There's also a chance that you're never actually running the success function. Could you post some more code?
The problem lies in the data that you are receiving or you have a typo somewhere later when checking length. This all looks fine, and I tried to replicate your problem like this:
var jiraMapping = [];
var myData = [{"A":"a"},{"B":"b"}];
for (var i=0; i<myData.length; i++) {
var obj = {};
obj[myData[i]] = myData[i];
jiraMapping.push(obj);
}
console.log(jiraMapping);
but this works fine, fiddle here: http://jsfiddle.net/GWpBs/2/
So I'll jump right to it...
I am a test automation engineer, and I am making a "keyword driven" testing system that is powered with JSON, which tie in with Selenium tests to run on a web browser.
The "keywords" are stored as XML files, and I have a JavaScript function which loads these keywords into an array, and also stores the Index of that keyword. to paf.keywordIndex
Example
$.get("getSteps.php", function(keywords) {
paf.keywords = eval(keywords); // stores into an array...
paf.keywordIndex = -1;
for ( var i = 0 ; i < paf.keywords.length ; i++ ) {
// for each path...
/* alert(paf.keywords[i]); */
$.ajax({url: "./_keywords/" + paf.keywords[i], success: function(xml) {
paf.xml = xml;
paf.keywordIndex++;
var title = $(xml).find("keyword").attr("title");
//var name = $(xml).find("keyword").attr("name");
paf.buffer += ("<option value=\"./_keywords/"+paf.keywords[paf.keywordIndex]+"\">"+title+"</option>");
},
async: false
//cache: false
});
}
$(stepSelectionLocator).html(paf.buffer);
});
getSteps.php is a php service that returns all the xml keywords in a json array. e.g.
["Login.xml","EndSession.xml", "SelectResult.xml", etc...]
Now this function works, but the only problem is, it's not sorted in ANY way. So the output would be -
Login (Login.xml)
Select a result (SelectResult.xml)
End a session (EndSession.xml)
To solve this issue, I added an extra attribute to my <keyword> so now it's <keyword area="basic"> to indicate that this is a basic step. and now my function is -
$.get("getSteps.php", function(keywords) {
paf.keywords = eval(keywords); // stores into an array...
paf.keywordIndex = -1;
for ( var i = 0 ; i < paf.keywords.length ; i++ ) {
// for each path...
/* alert(paf.keywords[i]); */
$.ajax({url: "./_keywords/" + paf.keywords[i], success: function(xml) {
paf.xml = xml;
paf.keywordIndex++;
var title = $(xml).find("keyword").attr("title");
var area = $(xml).find("keyword").attr("area");
//var name = $(xml).find("keyword").attr("name");
paf.buffer.push(area.toUpperCase() + ": " + title);
},
async: false
//cache: false
});
}
paf.buffer.sort(); // array is sorted...
paf.buffer2 = "";
paf.keywordIndex = -1;
for ( var a in paf.buffer ) {
paf.keywordIndex++;
paf.buffer2 += "<option value=\"./_keywords/"+paf.keywords[paf.keywordIndex]+"\">"+ paf.buffer[a] + "</option>";
}
$(stepSelectionLocator).html(paf.buffer2.toString().replace(",", ""));
});
Now the output is
BASIC: End the session (Login.xml)
BASIC: Login (SelectResult.xml)
RESULTS: Select a result (EndSession.xml)
So I've already determined that the index is the issue. However, I cannot figure out a way to fix this..
I am open to alternatives, so if you find a simpler way to index this, please let me know!
First of all, it'd be nice to know exactly the data you get from your initial request.
$.get("getSteps.php", function (keywords) {
paf.keywords = JSON.parse(keywords); // eval is bad! Use JSON.parse instead.
console.log(paf.keywords); // what does it output in the console?
...
Secondly, you can refer to the current index by using just the i variable. If you don't use paf.keywordIndex elsewhere, you can remove it because it's redundant.
Thirdly, are you absolutely, definitely, 100% sure that your ajax requests are *S*ynchronous? If they are not - the responses will arrive at random and the whole thing will require a different approach.
Finally, if you want to apply sorting to your keywords after you got them all, I would recommend pushing them into the buffer array as objects:
buffer.push({
keyword: keywordName, // this is the keyword name
keywordIndex: i, // this is the initial index
keywordArea: areaObtainedFromXML // this is the area you get from xml
});
By using the above approach you will be able to sort your buffer in many ways while retaining the initial order.
Please take a look at a contrived example at this jsfiddle.