Put XMLHttprequest results into one string - javascript

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>

Related

getting data from file.txt and returning it with an array

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>

Passing URL query strings into HTML form fields using Javascript

I have always used PHP for passing query strings into forms, but I am looking to move to a static site scenario and need the query data from a URL to populate the form fields.
I have the code with no console errors, but the data is not passing into the form fields. Does anyone know how this can be done that works across all modern and legacy browsers?
function getQueryString() {
var result = {};
if(!window.location.search.length) return result;
var qs = window.location.search.slice(1);
var parts = qs.split("&");
for(var i=0, len=parts.length; i<len; i++) {
var tokens = parts[i].split("=");
result[tokens[0]] = decodeURIComponent(tokens[1]);
}
return result;
}
$(document).ready(function() {
$("#theForm").submit(function(e) {
//var that = this;
var qs = getQueryString();
for(var key in qs) {
var field = $(document.createElement("input"));
field.attr("name", key).attr("type","hidden");
field.val(qs[key]);
$(this).append(field);
}
});
});
https://formpopulate.netlify.com/index.html?name=john&email=john#aol.com
https://formpopulate.netlify.com/
You should use URL seachParams:
var params = (new URL("https://example.com/?name=Jonathan&age=18&test=a%20long%20string")).searchParams;
var name = params.get("name"); console.log(name); // is the string "Jonathan"
var age = parseInt(params.get("age")); console.log(age);// is the number 18
var test = params.get("test"); console.log(test); // is a long string

Accessing array inside object in node js - undefined?

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

jquery to use .get and retrieve variables from text file

I have a list of names in a text file
example:
user1 = Edwin Test //first line of text file
user2 = Test Edwin //second line of text file
I would like each lines data to be set to a variable:
user1 and user2 //so that after jquery loads I can user $user1 and it will give Edwin Test
Text file will be in the same folder as jquery file.
My code:
$.get('users.txt', function(data) {
alert(data);
var lines = data.split("\n");
$.each(lines, function() {
var line=perLine[i].split(' ');
});
});
When i load the page using mamp locally, I am able to see the contents on the file using the alert but when i type for example (user1) in the console it says that the variable is not set.
Here's what I think you want:
$.get('users.txt', function(data) {
var lines = data.split("\n");
$.each(lines, function(i) {
var line = lines[i].split(' = ');
window[line[0]] = line[1];
});
});
later on...
console.log(user1); // "Edwin Test"
var users = {};
var lines = data.split("\n");
$.each(lines, function (key, value) {
var prep = value.split(" = ");
users[prep[0]] = prep[1];
});
To output user1 You would call users.user1
JSFiddle
The code adds lots of variables to the global namespace. Also, it invites bugs because $.get is asynchronous and so code that depends on the variables existing needs to be called where shown in the comment to be guaranteed to work. This would be considered bad style by many, but here's how to do it:
$.get('users.txt', function(data) {
alert(data);
var lines = data.split("\n");
var i,l=lines.length,parts;
for(i=0;i<l;++i){
parts = lines[i].split('=');
if (parts.length == 2){
try {
// window is the global object. window['x']=y sets x as a global
window['$'+parts[0]] = parts[1]; // call the var $something
} catch(e) {}; // fail silently when parts are malformed
}
// put any code that relies on the variables existing HERE
}
});
Here's what you might do instead:
Put the data in an object. Pass the object to a function showVars(vars) that contains the next step.
$.get('users.txt', function(data) {
alert(data);
var lines = data.split("\n");
var i,l=lines.length,parts, vars = {};
for(i=0;i<l;++i){
parts = lines[i].split('=');
if (parts.length == 2){
try {
vars[parts[0]] = parts[1];
} catch(e) {}; // fail silently when parts are malformed
}
showVars(vars); // put any code that relies on the variables existing HERE
}
});
function showVars(vars){
// put whatever uses/displays the vars here
}
Yet another way to make this easier to change the data format. If you can store the data in this format, called JSON:
['Edwin Test','Test Edwin','Someone Else','Bug Tester']
Then the parser is either a one liner array = JSON.parse(jsonString) or sometimes is done for you by jQuery and put in data. JSON can store all kinds of data, and there is support for it in other languages libraries besides Javascript, such as PHP, python, perl, java, etc.
$.get('users.txt', function(data) {
alert(data);
var lines = data.split("\n");
for(var i = 0 ; i < lines.length; i++){
var line=lines[i].split(' ');
});
});
I think you are missing the i in the loop.
I guess you could also do
$.each(lines, function(i) {
var line=lines[i].split(' ');
});
In any event, I would probably recommend that you do this string splitting on the server instead and deliver it to the client in the correct/ready form.

Code not adding object to an array

I'm trying to add a set of objects that have been retrieved from a JSON file into an array. I've tried using push but the result is the same. The length value of the array remains 0. What am I doing wrong? The JSON parses fine as I can get the values during the loop.
<script type="text/javascript">
//my array
var myArray = new Array();
function performSearch(){
var url = "http://myjsonurl...";
var counter = 0;
$.getJSON(url, function(response){
$.each(response.data.people, function() {
//p is the the object to add to the array
var p = new person(this.name, this.age);
//tried using myArray.push instead of having a counter, but
//I get the same length of 0.
myArray[counter] = p;
counter++;
});
});
//always returns 0
alert(myArray.length);
}
...
</script>
getJSON() is an asynchronous function. It only starts to fetch the data when you call it, and it calls the given function only after it has loaded it. So you call the alert before anything is fetched. You should have the alert right after the .each() function.
Ajax is asynchronous. Whatever depends on the JSON needs to happen in the callback.
function performSearch()
{
var url = "http://myjsonurl...";
$.getJSON(url, function(response)
{
var myArray = $.map(response.data.people, function()
{
return new person(this.name, this.age);
});
alert(myArray.length);
});
//always returns 0
alert(myArray.length);
// that's because this code executes before the $.getJSON callback does
}
You are returning the array before you put the objects in it.
The callback function used in the getJSON method doesn't run right away, it runs when the response arrives. As two methods can't run at the same time, you will always have exited your function before the callback function can run.
You can access the result inside the callback function:
<script type="text/javascript">
function performSearch(){
var url = "http://myjsonurl...";
$.getJSON(url, function(response){
var myArray = [];
$.each(response.data.people, function() {
var p = new person(this.name, this.age);
myArray.push(p);
});
alert(myArray.length);
});
}
</script>
<script type="text/javascript">
//my array
var myArray = new Array();
var counter = 0;
function performSearch(){
var url = "http://myjsonurl...";
$.getJSON(url, function(response){
$.each(response.data.people, function() {
//p is the the object to add to the array
var p = new person(this.name, this.age);
//tried using myArray.push instead of having a counter, but
//I get the same length of 0.
myArray[counter] = p;
counter++;
alert(myArray.length);
});
});
}
...
</script>

Categories