Fetch API Get request not recognizing values from input form - javascript

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>

Related

Using uploadcare within formspree without using the widget

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.

Accessing event data in JavaScript via a string to dictate which input forms to be captured

I'm currently creating a feature for an application which allows users to create custom forms. This renders fine, however my issue lies in capturing the information after the form is submitted.
For the sake of this question let's say I have an array of input names (as strings).
['firstName', 'lastName', 'emailAddress']
Upon submission I need to loop through the array and use the strings to determine the target elements to grab the values from.
e.target.'array string'.value;
How can I do it?
Forms have an elements collection which is an HTMLFormControlsCollection keyed by name. So assuming e.target is the form (e.g., this is a submit event);
e.target.elements[someVariable].value;
Live example:
document.querySelector("form").addEventListener("submit", function(e) {
e.preventDefault();
var elements = e.target.elements;
['firstName', 'lastName', 'emailAddress'].forEach(function(name) {
console.log(name + ": " + elements[name].value);
});
});
<form>
<input type="text" name="firstName" value="The first name">
<input type="text" name="lastName" value="The last name">
<input type="email" name="emailAddress" value="email#example.com">
<br>
<input type="submit" value="Submit">
</form>
Alternately, the more general solution is querySelector:
e.target.querySelector('[name="' + someVariable + '"]').value;
Live example:
document.querySelector("form").addEventListener("submit", function(e) {
e.preventDefault();
var form = e.target;
['firstName', 'lastName', 'emailAddress'].forEach(function(name) {
console.log(name + ": " + form.querySelector('[name="' + name + '"]').value);
});
});
<form>
<input type="text" name="firstName" value="The first name">
<input type="text" name="lastName" value="The last name">
<input type="email" name="emailAddress" value="email#example.com">
<br>
<input type="submit" value="Submit">
</form>

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".

Add post variable to form with jQuery

I have the below code which adds the value of the parameter to my form by default. This works well but if you set the form to post then it no longer works. What is the best approach to setting this value?
var request = {};
var pairs = location.search.substring(1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[pair[0]] = pair[1];
}
var getfirstname = document.getElementById('firstname');
var firstname = request['firstname'];
getfirstname.setAttribute('value', firstname);
<form method="get" action="search">
<input type="text" name="firstname" id="firstname" />
<input type="submit" alt="Go" value="Go" border="0" />
</form>
www.example.com?firstname=john
<form method="get" action="search">
<input type="text" name="firstname" id="firstname" value="John" />
<input type="submit" alt="Go" value="Go" border="0" />
</form>
The answers you've gotten so far probably don't address your issue correctly. If you are setting the value of an input from a form that is submitted with the method set to "GET" then the parameters are available in the querystring and accessible by the browser - that's why this works:
var pairs = location.search.substring(1).split('&');
But when you change the method to "POST", the posted data is no longer available to the browser (client-side). You need to retrieve the posted data on the server-side. If you are using PHP you would do something like this (very very simplified version):
<?php
$firstname = (isset($_POST['firstname'])) ? $_POST['firstname']:'NA';
?>
<form method="get" action="search">
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname; ?>" />
<input type="submit" alt="Go" value="Go" border="0" />
</form>
Hope that helps. If you can explain a little more about what you are trying to do I could add something to address an ajax via jQuery option.
If you want to set the value of a field set the value property not the value attribute
getfirstname.value = firstname;
Instead of setting the value attribute, set the actual value:
getfirstname.val(firstname);

Jquery get form field value

I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this
<div id ="DynamicValueAssignedHere">
<div class="something">Hello world</div>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="FirstName" />
<input type="submit" value="Submit" />
</form>
</div>
</div>
I would like to use Jquery to process the form on submit. I would also like to revert the form values to their previous values if something should go wrong. My question is
How can I get the value of input box using Jquery? For example, I can get the value of the div with class "something" by doing
var something = $(#DynamicValueAssignedHere).children(".something").html();
In a similar fashion, I want to be able to retrieve the value of the textbox. Right now, I tried
var text = $(#DynamicValueAssignedHere).children(".formdiv").findnext('input[name="FirstName"]').val();
but it doesn't seem to be working
You have to use value attribute to get its value
<input type="text" name="FirstName" value="First Name" />
try -
var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
It can be much simpler than what you are doing.
HTML:
<input id="myField" type="text" name="email"/>
JavaScript:
// getting the value
var email = $("#myField").val();
// setting the value
$("#myField").val( "new value here" );
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
$("form").submit(function(event) {
var firstfield_value = event.currentTarget[0].value;
var secondfield_value = event.currentTarget[1].value;
alert(firstfield_value);
alert(secondfield_value);
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" >
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
</form>
if you know the id of the inputs you only need to use this:
var value = $("#inputID").val();
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form
$('form[name=form1] input[type=text]')
Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
You can get any input field value by
$('input[fieldAttribute=value]').val()
here is an example
displayValue = () => {
// you can get the value by name attribute like this
console.log('value of firstname : ' + $('input[name=firstName]').val());
// if there is the id as lastname
console.log('value of lastname by id : ' + $('#lastName').val());
// get value of carType from placeholder
console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="firstName" placeholder='first name'/>
<input type="text" name="lastName" id='lastName' placeholder='last name'/>
<input type="text" placeholder="carType" />
<input type="button" value="display value" onclick='displayValue()'/>
</form>
</div>

Categories