How can I create a JavaScript global variable? - xmlhttprequest

This is the part of my .html file, where I use an xmlhttp request, and then try to access the JSON object outside of a function.
''''
<html>
<head>
<title>make_activities_table.html</title>
</head>
<body>
<script>
var act_obj_array;
// Get file activities.json and create JSON object
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if ( this.readyState == 4 && this.status == 200 ) {
act_obj_array = JSON.parse( this.responseText);
}
console.log(this.responseText);
console.log('Inside function = ' + act_obj_array);
};
xmlhttp.open( "GET", "activities.json", true);
xmlhttp.send();
console.log( 'Outside function = ' + act_obj_array);
</script>
</body>
''''
I'm trying to access the JSON object 'act_obj_array' outside of the xmlhttp.onreadystatechange function. From what I read, in JavaScript, to make a variable global, you define it outside of any function, which, clearly I have done here. But when I console.log 'act_obj_array, outside the function, I get undefined.
activities.json, is a file, that exist in the same directory of my web hosting's server. It is a JSON formatted file. I can see the information in the file quite clearly when I console.log( this.responseText );
What do I need to do to create a JSON object from an xmlhttp request, and then be able to access the JSON object from the rest of my code?

Well, since no one wanted to answer, I came up with a solution, and, I want to work on a second solution.
The solution I have now, I added a function after the line, inside a function:
act_obj_array = JSON.parse( this.responseText);
which is a function, that builds my table from my JSON object. At first, I just added the script in the body of the document, but, then, I defined the function in an external JavaScript sheet. This looked much cleaner.
The other solution, and one I haven't played with yet, is to use the 'fetch' method to read in my JSON file. That way, I may not have to use a function to create my JSON object.

Related

How to add an uploaded file to a list of already uploaded files in Vue?

I currently have a file uploader that accepts a single CSV file. Then with axios I POST such file to the server and everything works just fine. What I'm not being able to achieve is being able to upload another CSV that will get added to the list of CSVs uploaded. I'm not talking about uploading various files at once, I'm taking about uploading different files at different points in time.
This is the method that is used to select a CSV file in the .vue file.
staticCampaignCSVSelected: function (file) {
console.log('campaign-detail.vue#staticCampaignCSVSelected', file)
let vc = this
vc.selectedHeuristicId = -1
Campaign.uploadStaticCSV(vc.campaign, file[0])
.then(
function (data) {
alert('CSV cargado con exito')
}
)
.catch(
function (err, data) {
console.log("campaign-detail#staticCampaignCSVSelected - catch", err.response)
alert(err.response.data.error)
}
)
},
This is the function that I have in some other JS file to POST to the API:
function uploadStaticCSV (campaign, csv) {
console.log('Campaign#uploadStaticCSV', campaign, csv)
//long list of assertions
let formData = new FormData()
formData.append('csv', csv)
return axios.post(API.campaignUploadStaticCSV(campaign.id), formData)
}
And this is the function I have in my endpoints.js file:
campaignUploadStaticCSV: function (id) { return this.campaign(id) + '' + '/csv' },
I haven't found a way to properly pass a[file] array as a parameter to the functions, which is what I believe I need to somehow do.
Any help would be appreciated :)
As far as i understood your question you need a way to pass a file from browser interface to your staticCampaignCSVSelected(file) method. If so why not to use an input model or a simple event or a watcher. E.g.
<input type="file" #input="staticCampaignCSVSelected($event.target.files[0])" />
But also i see a mistake in your code. You should append .then().catch() callbacks to axios.post() itself but not to Campaign.uploadStaticCSV() method.
And
return axios.post()
will not return a server response. You have to handle it in
axios.post().then(response => {})
callback

Can I retrieve a variable from a express function into a script of a pug template?

I have a express function that retrieves one variable(array) from mongoDB
app.get('/route',function(req,res,next){
User.find()
.exec(function(err,result){
if(err) throw err
var outputMessage=result[0].message.split(/\\n/g)
var myBooks=[]
for(var i=0;i<outputMessage.length;i++){
myBooks.push(outputMessage[i])
}
res.render('index',{books: myBooks})
})
}
And a pug template index.pug:
html
head
script(type='text/javascript')
for book in books /*books coming from the express function in res.render('index',{books: myBooks}) */
data.addRows([book,1]) /*data.addRows are object and method from Google Charts*/
Is it posible to use a variable from the express function within a script of the pug template (and within the head)
You can store books array into a javascript variable and then iterate over it using javascript foreach:
html
head
script(type='text/javascript').
var books = !{JSON.stringify(books)};
books.forEach( function (book) {
data.addRow([book,1]);
});
Do not forget dot . after script(type='text/javascript') that tells pug not interpreting the next code

Pass arguments to contact.php

How can I pass variable to contact.php that I can echo on form. I can pass through the form to the email recipient, but, I'm at wits end trying to print to form.
For example, I'd like to set $somevariable="This will be my default Subject", pass the variable through the contact.js and be able in the contact.php receive the variable and use the for the value="#somevaraible" for the subject on the form.
Thanks!
I think you are looking for something like ajax, which will allow you to communicate directly from javascript to PHP scripts. The easiest is probably jquery's implementation of ajax. You are able to pass parameters to your PHP application. https://api.jquery.com/jQuery.ajax/
For example, I can pass any param I want to map.php. With GET this would be the equivalent of calling "map.php?param1=strvalue1&param2=strvalue2" (in the example) I can then capture these values in PHP by using something like $param1 = $_GET['param1']; In the example, whatever the PHP file displays in response to this is then written to an element with the ID of write. All of what I just mentioned can occur after a page has loaded.
You can call the javascript below as many times as you like with whatever javascript functions you see fit. Just keep in mind it will continue to replace whatever is in ID of write, you just need to update that snipplet of code to update the value of your field.
You need to make sure you include Jquery's library when using this like:
<script class="include" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var request = $.ajax({
url: "map.php",
type: "GET",
data:{ param1 : "strvalue1",
param2: "strvalue2"
},
dataType: "html"
});
request.done(function( msg ) {
$( "#write" ).html( msg );
});
</script>

I have an issue with fwrite not properly overwriting a file

For some reason, when I use fwrite to overwrite the contents of my file, it erases the data, but fails to write the new contents to it until fwrite is invoked a second time. Is there any way I can get around this?
My script uses HttpRequest to send a FormData object to an external script as if I had invoked a form submit, then the script saves the form data to a file on the server, and then uses another HttpRequest to get the responseText of the file on the server and apply it to the value of another element:
PHP.php
data = $_POST["name"];
fopen(filename, w);
fwrite(file, data);
fclose(file);
CORE.html
<script>
function functionName() {
obj = new XMLHttpRequest;
form = new FormData;
form.append("name", object.getElementById(elementId).value);
obj.open(POST, PHP.php, false);
obj.send(form);
obj2 = new XMLHttpRequest;
obj2.onreadystatechange = function() { if (obj2.readyState == 4 && obj2.status == 200) document.getElementById(elementId2).value = obj2.responseText };
obj2.open(POST, OUTPUT.txt, false);
obj2.send();
}
</script>
<textarea id=elementId onkeypress=functionName()>
</textarea>
<br>
<textarea id=elementId2>
</textarea>
OUTPUT.text
epty text document
Use fflush()
http://php.net/manual/en/function.fflush.php
This function forces a write of all buffered output to the resource pointed to by the file handle.
I figured it out myself.
For some reason, using the onkeypress event, the event was being triggered and the function called before any characters were inserted into the TextArea, resulting in the file being written with an empty string.
The reason for the successful writes on subsequent attempts was that on subsequent key presses, characters were then present within the TextArea, and were successfuly written to the file.
I simply used another method to call the function after characters were present.

How to receive variables in a js file when I create it with Element script from another JS file?

I have "file1.js" with the following code where I create a element script to call another js file named test.js
var property = 'email';
var NewScript=document.createElement('script');
NewScript.src="/js/test.js?property="+property;
document.body.appendChild(NewScript);
The code work fine because call (or insert) the file "test.js" my problem is that I also want to send a variable to "test.js" to use it there, I dont know how to send/receive this variable in that way, any help ?
This is what I should have in "test.js"
alert(property);
but how do I receive this variable?
No you can't pass a querystring parameter to a javascript file like that. What I've seen done is to set the variable in script before you create your new javascript file reference. Which is kind of what you are doing above, but you need to declare your property variable outside whatever function you have this code in. So for example if you have this code in a jQuery document ready function it would look something like this:
var property = 'email';
$(document).ready(function () {
var NewScript = document.createElement('script');
NewScript.src = "/js/test.js";
document.body.appendChild(NewScript);
});
This will allow your property variable to stay in scope for your external file. HTML JavaScript Include File Variable Scope