Using uploadcare within formspree without using the widget - javascript

I'm trying to send emails with a generated pdf, i can use uploadcare for the user to specify which file but i want this to be done automatically, i.e. the file uploaded is the pdf. At the moment the form is sending but the my_file part is missing
<form id="contactform" method="POST">
<input type="text" name="name" placeholder="Your name">
<input type="email" name="_replyto" placeholder="Your email">
<input type="hidden" name="_subject" value="Website contact" />
<textarea name="message" placeholder="Your message"></textarea>
<input type="hidden" name="my_file" data-public-key="key_here" />
<input type="text" name="_gotcha" style="display:none" />
<input type="submit" value="Send">
</form>
js
const filetostore = fetch()
console.log(filetostore)
async function fetch(){
const itemToStore = document.getElementsByClassName("itemName");
const itemQty = document.getElementsByClassName("quoteQty");
const itemPrices = document.getElementsByClassName("quotePrice");
const itemTotal = document.getElementsByClassName("quoteTotal");
const totalCost = "Total Cost" + ":" + document.getElementById("quoteTotalCost").innerText;
await fn(itemToStore, itemQty, itemPrices, itemTotal, totalCost)
}
var my_file = uploadcare.fileFrom('input', filetostore);
$('input[name="my_file"]').val(myfile)
console.log(my_file)
var contactform = document.getElementById('contactform');
contactform.setAttribute('action', '//formspree.io/' + 'yy92' + '#' + 'gmail' + '.' + 'com');

The uploadcare.fileFrom method returns a promise-based uploadcare file instance. If you want to add a file URL in the form, you need to get it first.
var my_file = uploadcare.fileFrom('input', filetostore);
my_file.done(function(fileInfo) {
$('input[name="my_file"]').val(fileInfo.cdnUrl);
});
Also, the filetostore argument should be a HTMLInputElement containing a file to upload. It's not clear from the code snippet what the fetch() function returns.

Related

Fetch API Get request not recognizing values from input form

I am trying to get values from a fetch request using input from a form with player first and last name. The return json has a total size of 0 but when I hard code the value of the names I do get the correct info. I've tried switching the fetch request many different ways but I can't get the response I am looking for.
The API Docs says:
If you’re using a single search term i.e. using ‘cespedes’ instead of ‘yoenis cespedes’, you’ll need to append a ‘%25’ character to your search term. Without it, the request will return 500.
<body>
<div>
<form action="">
<label for="fname">First name:</label><br />
<input type="text" id="fname" name="fname" value="" /><br />
<label for="lname">Last name:</label><br />
<input type="text" id="lname" name="lname" value="" /><br /><br />
<input type="submit" value="Submit" />
</form>
</div>
<script>
fetch(
'http://lookup-service-prod.mlb.com/json/named.search_player_all.bam?sport_code=%27mlb%27&active_sw=%27Y%27&name_part=%27' +
'fname' +
'_' +
'lname' +
'%27'
)
.then(function test(res) {
return res.json();
})
.then(function test1(data) {
console.log('data', data);
});
</script>
</body>
When i use this fetch with the name included, it returns the correct json.
http://lookup-service-prod.mlb.com/json/named.search_player_all.bam?sport_code=%27mlb%27&active_sw=%27Y%27&name_part=%27francisco_lindor%25%27
When creating your fetch url, you have to actually include the form values.
You current code
'http://...&name_part=%27' + 'fname' + '_' + 'lname' + '%27'
will always result in
"http://...&name_part='fname_lname'"
regardless of the form inputs because you are just concatenating string literals here. You can check that by logging the urls you create before sending them.
You have to get the form values in javascript to send them.
For example, you could get the values of the inputs and keep them in variables like this:
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
Then you can use those values to create your url:
var url = 'http://...&name_part=%27' + fname + '_' + lname + '%27';
Keep an eye on the fname and lname. There are no quotes around them so javascript will use the variables.
Your current fetch sends fname and lname as strings instead of using their actual values. This should work just fine:
const form = document.querySelector('form');
const fname = document.getElementById('fname');
const lname = document.getElementById('lname');
form.addEventListener('submit', e => {
e.preventDefault();
fetch(`http://lookup-service-prod.mlb.com/json/named.search_player_all.bam?sport_code=%27mlb%27&active_sw=%27Y%27&name_part=%27${fname.value}_${lname.value}%27`)
.then(res => res.json())
.then(data => console.log(data));
})
<div>
<form>
<label for="fname">First name:</label><br />
<input type="text" id="fname" name="fname" value="Aaron" /><br />
<label for="lname">Last name:</label><br />
<input type="text" id="lname" name="lname" value="Judge" /><br /><br />
<input type="submit" value="Submit" />
</form>
</div>

Getting HTML form values with JavaScript and saving them into JSON key and value pairs

Objective
FrameWork used : ElectronJS
I want to take the user submitted form, and use the NodeJS script to generate a JSON file on client PC. The json file will have key and value pairs.
Please see below for expected output.
HTML
<form id="form" method="POST" action="#">
<div class="form-group col-auto">
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Username" value="">
</div>
<div class="form-group col-auto">
<input type="text" class="form-control" id="account" name="account" placeholder="Enter Account" value="">
</div>
<button type="submit" id="save" class = "btn text-white mb-0"> Save </button>
</form>
JS
document.getElementById("save").addEventListener('click', saveJSON(e))
async function saveJSON(e){
e.preventDefault()
var userData = document.getElementById('username').value
var acctData = document.getElementById('account').value
var formData = userData + acctData;
console.log(formData);
await writer.jsonWriter(formData);
//Error - Uncaught TypeError: Cannot read property 'value' of undefined.
Error
Here is the error I am facing
NodeJS Script
async function jsonWriter(data){
let element = JSON.stringify(data);
fs.writeFileSync(__dirname + '\\data\\auth.json', element)
}
module.exports.jsonWriter = jsonWriter;
Required Output
// auth.json
{"username":"Stack","account":"Overflow"}
I believe there was an issue with how you were passing your event into your function and trying to call preventDefault(). I put your function directly on the event listener method with async keyword.
As previously mentioned, document.querySelector() uses CSS selectors unlike document.getElementById(). In your case I would stick with getting the input elements by their ID.
Like Paul said in his answer, you need a JavaScript object for JSON.stringify() to work properly.
document.getElementById("save").addEventListener('click', async function(e) {
e.preventDefault()
var userData = document.getElementById('username').value
var acctData = document.getElementById('account').value
var formData = {
username: userData,
account: acctData
}; // create JS object
console.log(JSON.stringify(formData));
});
<form id="form" method="POST" action="#">
<input type="text" id="username" name="username" placeholder="Enter Username">
<input type="text" id="account" name="account" placeholder="Enter Account">
<button type="submit" id="save">Save</button>
</form>
Okay I think that I can see your mistake.
In the Javascript you can change this part :
var formData = userData + acctData;
console.log(formData);
await writer.jsonWriter(formData);
To this part :
Try to assign it to a javascript object like that :
var formData = {username: userData, account: acctData};
console.log(formData);
await writer.jsonWriter(formData);
it will stringify your object and write an appropriate output.
I think.

How can I get a value from a form in page 1 to another page by using JavaScript?

I have only learned HTML, CSS, JavaScript and jQuery and I want to get a value from my form to my index page, which is located in different files, using the languages I know. So this is my form :
<form action="../index/index.html" method="GET">
<label for="name">Name :</label>
<input type="text" name="name" id="name" required>
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="eg.yourname#gmail.com" required>
<input type="submit" name="submit" id="submit">
</form>
I want the value that a user submits in the #name input in my index's div tag when the submit button is pressed (this div has the class sing-in).
Both pages have their own JavaScript and CSS so if I would import the JavaScript of the page where the form is to my index pages it will mess up both pages I guess. Therefore, I want to do this without importing the JavaScript and just by taking the value from another page into my index page. Thank you.
When you submit your form and get redrected to your index page the values of the form will be put at the end of the url as GET parameters.
Example url: localhost:80/index/index.html?name=Eddie&email=eddie#gmail.com
To read the GET parameters you can use this code:
var urlString = window.location.href
var url = new URL(urlString);
var name = url.searchParams.get("name");
var email = url.searchParams.get("email");
//Check if name and email are set
Make sure to check if name and email have actually been set in index.html
You can get the values from for like this:
if this is the form
<form action="../index/index.html" method="GET">
<label for="name">Name :</label>
<input type="text" name="name" id="name" required>
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="eg.yourname#gmail.com" required>
<input type="submit" name="submit" id="submit">
</form>
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
or in jquery
var name = $('#name').val();
var email = $('#email').val();
have a look:
https://www.w3schools.com/jsref/prop_text_value.asp
this might help you

Get value from a textbox and pass to the next text box as suggestion

$partOne = strtok($filename, '.');I have a text box suppose to be url:
<label>URL:</label>
<input name="url" type="text" id="url" size="20" />
And I want to get the last name of that url to display on the second text box when user click there to type:
<label>NAME:</label>
<input name="name" type="text" id="name" size="20" />
What I tried:
<script type="text/javascript">
function myFunction() {
var url = document.getElementById('url').value;
var name = <?php $path = parse_url($_GET['url'], PHP_URL_PATH); $filename = basename($path);$partOne = strtok($filename, '.'); echo $partOne; ?>;
document.getElementById('name').value = name;
}
</script>
and make a button to test it:
<button onclick="myFunction()">Test Button!</button>
But it looks like the java script has something wrong, suspecting it is php in java script part.
How can I archive my purpose (final solution is without clicking on test button; user click to the second box and there is a text there that they can edit).
You need an ajax call at that point. The behavior you expect cannot be done the above way. Once the page is displayed on the browser, there is no more PHP, there is just HTML and JS. This is because PHP is a server side language.
You have two options to make the form work as you want, either do your Url processing step with Javascript or make Ajax fetch results from the server, behind the scene.
<label>URL:</label>
<input name="url" type="text" id="url" size="20" />
<label>NAME:</label>
<input name="name" type="text" id="name" size="20" />
<script>
$("#url").change(function()
{
$.ajax({
url:"parseurl.php?key="+$("#url").val(),
}).done(function(data)
{
$("#name").val(data);
});
});
</script>
where parseurl.php is
<?php
$path = parse_url($_GET['key'], PHP_URL_PATH);
$filename = basename($path);$partOne = strtok($filename, '.');
echo $partOne;
?>
I've tried this:
$('input[name=url]').focusout(function(){
var url = $('input[name=url]').val();
if(url.indexOf('/') != -1) // If there is a slash in the url.. 'google.at/test.html'
{
var urlarray = url.split('/'); // Split the url into an array..
var urlerg = urlarray[urlarray.length-1]; // Take the last item of the array
$('#dlist').append('<option value="'+ urlerg+ '">'+urlerg +'</option>');
}
else
{
$('#dlist').append('<option value="'+url+'">'+url+'</option>');
}
});
And this is the input/datalist item:
<label>URL:</label>
<input name="url" type="text" id="url" size="20" />
<label>NAME:</label>
<input name="name" type="text" list="dlist" id="name" size="20" />
<datalist id="dlist">
</datalist>
So when i write in the URL-Input "www.google.at/test.html" i get in the NAME-Input as suggestion "test.html". And if i only wrote a dokument name without an "/" i get only the dokument name.
FIDDLE LINK TRY THE DEMO
Greetings

Pass an input box value through to a var in the js doc to be used

Is it possible to pass the value of an input from a form into a var to be used in a function.
for example:
<input type="text" id="userID" name="userID" placeholder="Enter user ID" style="width:200px;" />
<input type="submit" value="search" />
So the userID would be passed into :
var userId = null;
I am looking to use this as a way for a user to input their userID in to the flickr api call.
$.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.search&getSizes&api_key=feb7e93d9a90e9a734787bea9be81440&user_id='+userID+'&has_geo=1&extras=geo&format=json&jsoncallback=?', mapImages);
I had a look around and came across
var userId = document.getElementById("userID").value;
This does not seem to be working though.
I have tried:
<form type="post" onsubmit="loadImages(); return false;">
<input type="text" id="userID" name="userID" placeholder="Load user images" />
<input type="submit" value="Get Flickr images!" />
</form>
Using the function:
function loadImages()
{
var userId = document.getElementById("userID").value;
}
Is this along the right track or totally off?
getElementById is case-sensitive.
In your HTML you use "userID" and in your JavaScript "userId".

Categories