In javascript:
var post = {};
post.arr = ["hi", "hello"];
$.post("http://localhost:8000/test", post);
and in node:
var body = "";
request.on('data', function (data) {
body += data
});
request.on('end', function (data) {
var post = qs.parse(body);
console.log(post); // I see { 'arr[]': ['hi', 'hello'] };
console.log(post.arr); // undefined
}
Any idea what might have caused this?
Based on your comments, it looks like somehow the map key is literally arr[]. Try console.log(post['arr[]']);
jQuery will modify the name of arrays as #MikeC pointed out. More info here: https://stackoverflow.com/a/5888057/1861459
Related
i have file.txt
apple <--line 1
banana <--line 2
and this is my script
url = 'file.txt';
homelists = [];
$.get(url, function(data) {
var lines = data.split("\n"); <--i want to split it by line
$.each(lines, function(n ,urlRecord) {
homelists.push(urlRecord); <--add it to my homelists array
});
});
console.log(homelists); <-- returns array
console.log(homelists[0]); <--undefined
my problem is i cant get the inside value of homelists
how can i get homelists[0] or homelists[1]..(javascript or jquery(preferrable))
Javascript/Jquery ajax is an Async call meaning the code $.get and console.log on your example will be executed parallelly (immediate or the same times), so to parse the result of your file.txt, you need to do it inside the function (which will be executed after ajax called is done).
url = 'file.txt';
homelists = [];
$.get(url, function(data) {
var lines = data.split("\n");
$.each(lines, function(n ,urlRecord) {
homelists.push(urlRecord);
});
console.log(homelists);
console.log(homelists[0]);
});
I know this is too simple answer and may sound stupid to others but i have an idea!
why not store in the session the $.get data
url = 'file.txt';
$.get(url, function(data) {
localStorage['homelists'] = data;
});
then assign a variable to that session
homelists = localStorage['homelists'];
then make the session = null
localStorage['homelists'] = null
when you do console.log outside
console.log(homelists); <-returns string which you can manipulate to turn it into array
console.log(localStorage['homelists']); <-returns null
I dont know yet what could be the bad side/effect of this with my project.. any idea?
Since you are using jQuery, It would be better if you use AJAX. !
const ImportData = function(file){
let arrayData = undefined;
$.ajax({
url: file,
type: 'GET',
error: (err) => { throw new Error(err) },
success: ( data ) => {
arrayData = MakeArray( data );
//Do whatever you want here
console.log( arrayData );
}
});
}
const MakeArray = function(plaintext){
const array = [];
plaintext.split('\n').forEach( (line) => {
line = line.trim();
array.push( line );
} );
return array;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
const file = "https://www.w3.org/TR/PNG/iso_8859-1.txt";
document.addEventListener('DOMContentLoaded', function(){
ImportData( file );
});
</script>
I am working on edit post page and want to submit data if the post field are modify.
var req = {
'apikey': apidata.apikey,
'partyId': boardID,
}
Now I just want to add property which is edited in form.
'name':'userName',
'postDetail':'<p>This is detail</p>'
What is the best approch to handel this. I looked to the other post but I found
var req = {name: 'firstName'};
// data from form
var data = {'age':45, 'city':'london'};
function extend(objectToExtend, data) {
for (var i in data) {
if (data.hasOwnProperty(i)) {
objectToExtend[i] = data[i];
}
}
}
extend(req, data);
I think there is more space of improvement in this approch.
Just add the new properties using the square bracket notation.
var req = {
'apikey': apidata.apikey,
'partyId': boardID
};
req['name'] = 'userName';
req['postDetail'] = '<p>This is detail</p>';
I'm trying to get my array of URL's to run through a JQuery .get function to get the site's source code into one string outside of the function. My code is below.
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var get = $.get(fetch, function(sourcecode) {
sourcecode = fetch;
}
I need the sourcecode variable to be the combination of source code on all of the URLs in the array.
You need to put a variable outside of the function, something like this data variable below and append to it with +=:
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var data = null;
var get = $.get(fetch, function(sourcecode) {
data += fetch;
}
}
Try this like,
var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
var data='';
$.ajax({
url:fetch,
async:false,
success : function(d){
data=d;
}
});
return data;
}).get();
Since you're using jQuery, I suppose that jQuery.each() may be a better way to iterate over the array.
var URL = ["http://website.org", "http://anothersite.com"];
var str = [];
$.each(URL, function(index, fetch) {
$.get(fetch, function(sourcecode) {
str.push(sourcecode); // if you want an array
})
});
str.join(''); // if you want a string
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I got this piece of code. Problem is that PUSH wont add anything to the array WORDS or if I try assign value to property. Data in collection that it iterates trough isn't null I tested it and calling other functions from that place in code work for example alert etc.
Thanks for your help.
Here is my piece of code
var uri = 'GetTickerData';
var words = [];
var string;
$.getJSON(uri)
.done(function (data) {
$.each(data, function (key, item) {
words.push('Some text'); //dont work
string = 'Another text'; // also dont work
});
});
I've not tested this, you'll have to let me know if this works for you
function getReturnedData(callback) {
var uri = 'GetTickerData';
var string;
$.getJSON(uri, function (data) {
var words = [];
$.each(data, function (i) {
words.push(data[i]);
});
callback(words);
});
}
getReturnedData(function(returnValue) {
console.log(returnValue);
});
from controller Json is returned and in function i get an object which contains
{
"readyState":4,
"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{
"Success":0,
"Failed":0
},
"status":200,
"statusText":"OK"
}
How can I take Success and Failed values?
data.Successand JSON.parse(data) is not working
You dont need to parse that because that IS already an object:
var obj = {"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}","responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"};
var failed = obj.responseJSON.Failed;
var success = obj.responseJSON.Success;
var json_data = '{"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"}';
var obj = JSON.parse(json_data);
alert(obj.responseJSON.Success); // for success that in responseJSON
alert(obj.responseJSON.Failed);
Thanks :)