I am building an application where I need to get the value return from the API and bind it to my variable. I have been stuck on this for days, and I couldn't go any further.
Here is my code:
<script>
let address = "";
async function addExample() {
const response = await fetch(
"https://api",
{
method: "PUT",
headers: {
"api-key":
"api-key",
},
body: JSON.stringify({
address: address,
}),
}
);
}
</script>
<svelte:head>
<script
src="https://maps.googleapis.com/maps/api/js?key=my-key&libraries=places&callback=initAutocomplete"
async
defer
>
</script>
<script>
let autocomplete;
function initAutocomplete() {
const input = document.getElementById("autocomplete");
const options = {
componentRestrictions: { country: "au" },
strictBounds: false,
};
const autocomplete = new google.maps.places.Autocomplete(
input,
options
);
}
autocomplete.addListener("place_changed", onPlaceChanged);
function onPlaceChanged() {
address = autocomplete.getPlace();
}
</script>
</svelte:head>
<input
id="autocomplete"
placeholder="address"
type="text"
bind:value={address}
/><br />
I tried to add my tag svelte:head inisde the script tag but it didn't work, among others tries. And due my lack of experience, I want if I'm doind this on the right way instead of waste more time on this. PS: I don't need to create a map or anything like that now. I just want to bind the value of autocomplete to my variable, so I will be able to fetch data into DB.
I have tried eveything I could find googling but none of them worked. I am newbie with all this, and I don't know what else to think/try.
Related
I have a form on my website that submits its data to a Google App Script which then does some stuff and returns a status back to the web page. For some reason, when it reads in the submitted data, it is converting each value to an array containing just the value. For example:
{
fname: "danny",
lanme: "tester"
}
is being converted to
{
fname[]: ["danny"],
lanme[]: ["tester"]
}
** also not the [] being appended to the property name;
Here's a simple example:
HTML
<form>
<input type="text" name="fname"> <input type="text" name="lname">
<submit>
</form>
JavaScript
var payload = {
fname: $('[name="fname"]').val(),
lname: $('[name="lname"]').val()
}
$('form').submit(function() {
$.ajax({
url: 'https://script.google.com/macros/s/SCRIPT_ID/exec',
data: payload
method: 'GET"',
dataType: 'jsonp',
success: function(data) {
console.log(JSON.parse(data.body));
}
});
});
Google Apps Script
function doGet(e) {
var data = e.parameters;
return ContentService
.createTextOutput(JSON.stringify(data))
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
When run, the following is written to the console:
{fname: Array(1), lname: Array(1)}
and expanding it produces
fname: ["danny"]
lanme: ["tester"]
It's easy enough to convert in the Google Apps Script, but it would be nice to know why this is happening. Any ideas?
That is the way that the parameters property works.
You might change your doGet function by replacing
var data = e.parameters;
by
var data = {
fname:e.parameter.fname,
lname:e.parameter.lname
};
or by
var data = {};
Object.keys(e.parameter).forEach(key => data[key] = e.parameter[key]);
Resources
https://developers.google.com/apps-script/guides/web
To begin with, I'm making a simple social media application. I'm trying to submit a form which has text, images, and videos. My frontend where the form is submitted is made with React and server is ran with node.js mounted on nginx. I was trying to append the inputted files into FormData with code below:
handleSubmit = function (e) {
e.preventDefault();
const formData = new FormData();
formData.append("textBody", this.state.textBody)
for (let i = 0; i < this.state.imgInput.length; i++) {
formData.append("imgInput", this.state.imgInput.files[i], "img"+i.toString())
fetch("mywebsite.com/api/submitArticle", {
body: formData,
method: "POST",
credentials: 'include',
}).then((response) => console.log(response))
return false;
}.bind(this)
handleChange = function (e) {
e.preventDefault();
if (e.target.name === 'imgInput') {
this.setState({
imgInput: e.target.files,
showSpan: false
})
}
}.bind(this)
<form onSubmit={this.handleSubmit}>
<textarea id='textBody' name='textBody' onFocus={removeSpan} onBlur={checkSpanOn} onChange={this.handleChange}/>
<input type="file" id="imgInput" name="imgInput" accept="image/*" ref={this.imgRef} multiple={true} onChange={this.handleChange}/>
<input type="submit" id="submitButton" name="submitButton" formEncType="multipart/form-data" />
</form>
But React gave me this error upon submitting the form:
TypeError: Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'.
at "formData.append("imgInput", this.state.imgInput.files[i], "img"+i.toString())".
So when I console logged what e.target.files before setState in handleChange, I got normal FileList with all the image files listed. But when I console loggedd this.state.imgInput after setState in handleChange, I got String of C://fakepath/filename, not fileList. (Initially state.imgInput was null. When I saw other examples and codes, e.target.files was fileList so I'm puzzled elsewhere I made mistake.
I was spending half my day on this problem and I'm 5 sec before fainting so any advice would be appreciated :) Thank you for reading.
yes this happening because the event is gone you need to store the event.target in variable + the files will be in imgInput not imgInput.files so here it is:
handleSubmit = e => {
e.preventDefault();
const formData = new FormData();
formData.append("textBody", this.state.textBody);
for (let i = 0; i < this.state.imgInput.length; i++) {
formData.append("imgInput", this.state.imgInput[i], "img" + i.toString());
fetch("mywebsite.com/api/submitArticle", {
body: formData,
method: "POST",
credentials: "include"
}).then(response => console.log(response));
}
};
handleChange = e => {
e.preventDefault();
const target = e.target;
if (target.name === "imgInput") {
this.setState(current => ({
...current,
imgInput: target.files,
showSpan: false
}));
}
};
Basically I'm trying to pass the value of my dropbox to a get action.
The submit-button re-directs to the correct action , but what is the correct way to add the value of the dropbox with the re-direction?
My view:
#model TrackerModel
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Get, new { ???}))
{
<div>
<strong>#Html.LabelFor(m => m.CustomerName)</strong>
#Html.TextBoxFor(m => m.CustomerName, new { type = "hidden", #class = "customer-picker" })
</div>
<button class="styledbutton" onclick="window.location.href='/Tracker/Index'">Cancel</button>
<button type="submit" value="submit" id="selectCustomer-button" class="styledbutton">Submit</button>
}
[HttpGet]
public ActionResult MyAction(IPrincipal user, Tracker model)
Customer-picker
$(document).ready(function () {
CustomerPicker();
});
function CustomerPicker() {
$('.customer-picker').select2({
placeholder: 'Select customer',
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: '/JsonData/GetCustomers',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
query: term // search term
};
},
results: function (data) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return { results: data };
}
},
formatResult: function (data) {
return data;
},
formatSelection: function (data) {
return data;
}
});
}
I was expecting the value to be within my Tracker model parameter in the action, but this returns nulls. Also I'm not sure what to place in the "new" parameter in the form tag?
I also tried the following but all I get returning to the controller is text:"".
#Html.TextBoxFor(m => m.CustomerName, new { type = "hidden", #id = "selectedCustomer", #class = "customer-picker" })
<script type="text/javascript">
$(function () {
$("#Form1").submit(function (e) {
alert("boo");
e.preventDefault();
var selectCustValue = $("#selectedCustomer").val();
$.ajax({
url: '/CalibrationViewer/SentMultipleCalsToCustomer',
data: { text: selectCustValue }
});
});
});
OK got it,
var selectCustValue = $("#s2id_CustomerName span").text();
Found another piece of code the used the customer-picker and the javascript associated with view used the above.
I viewed the page source and it still show's both id and name as CustomerName, it has something to do with the "Select 2" helper.
I may get slated for marking this as the answer, considering I should have figured it out earlier, but there you have it !
I'm trying to learn some stuff with Knockout by following the examples.
I've followed the loading and saving data tutorial and read the docs on Loading and Saving JSON Data.
Using the code in these examples, I can't seem to overwrite the JSON file. I tried setting permissions to 777 to make sure that wasn't the problem.
On "success," it just seems to return the data in the file. I confirmed this by loading the HTML file, manually editing the JSON file, deleting tasks, and clicking save. The result I saw in my console was the data from the manual edit of the JSON file.
I have this hosted on my server right now: index.html, test.json.
For the sake of posterity, here is that code:
HTML
<!doctype html>
<html>
<body>
<h3>Tasks</h3>
<form data-bind="submit: addTask">
Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done?" />
<button type="submit">Add</button>
</form>
<ul data-bind="foreach: tasks, visible: tasks().length > 0">
<li>
<input type="checkbox" data-bind="checked: isDone" />
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> - it's beer time!</span>
<button data-bind="click: save">Save</button>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() && !task._destroy });
});
// Operations
self.addTask = function() {
self.tasks.push(new Task({ title: this.newTaskText() }));
self.newTaskText("");
};
self.removeTask = function(task) { self.tasks.destroy(task) };
self.save = function() {
var data = ko.toJSON({ tasks: self.tasks });
$.post('test.json', data, function(returnedData) {
console.info(returnedData);
});
/*
$.ajax("test.json", {
data: ko.toJSON({ tasks: self.tasks }),
type: "post", contentType: "application/json",
success: function(result) { console.info(result) }
});
*/
};
// Load initial state from server, convert it to Task instances, then populate self.tasks
$.getJSON("test.json", function(allData) {
var mappedTasks = $.map(allData, function(item) { return new Task(item) });
self.tasks(mappedTasks);
});
}
ko.applyBindings(new TaskListViewModel());
</script>
</body>
</html>
JSON
[{"title":"Wire the money to Panama","isDone":true},{"title":"Get hair dye, beard trimmer, dark glasses and \"passport\"","isDone":false},{"title":"Book taxi to airport","isDone":false},{"title":"Arrange for someone to look after the cat","isDone":false}]
The form is working properly, it's posting the correct JSON to the server (you can see this in the browser's dev tools). But because it's just a JSON file on the server, you're not able to overwrite it by simply posting to it. Instead, you'll need to create a web service endpoint on the server that you can post the data to, and the service will then save the file on the server's file system.
I have the following code and was wondering why my data isn't getting pulled into my model? I'm using a static json file and I'm guessing this might be my problem but can't seem to find any documentation about it.
var DataModel = Backbone.Model.extend({
initialize: function () {
console.log('initiliazed model')
},
url: "data/data.json"
});
var StructureView = Backbone.View.extend ({
initialize: function () {
console.log('initiliazed view')
_.bindAll(this);
this.model.fetch();
this.render();
this.model.on('change',this.render);
},
el : '#ev-wrapper',
render: function () {
$('#ev-wrapper').empty().append(Handlebars.compile($('#ev-template').html())(this.model.toJSON()));
$('.ev-asset-loader').fadeOut('slow');
}
});
var structureView = new StructureView({model: new DataModel()});
You need to call fetch. This will issue an AJAX request using url
var model = new DataModel();
model.fetch();
Open Firebug or your favorite browser's network console to see AJAX requests and check if it's OK