I have user_feedback in repeatable component in user table, how can I upload image to the newly added user feedback in strapi v3.
What currently I am doing
const data = await strapi.services["users"].update(
{ id: id },
{
...updatedData,
}
);
const newFeedback =
data.feedback_prototype_phase[data.feedback_prototype_phase.length - 1];
await strapi.entityService.uploadFiles(data, files, {
id: data.id,
model: "user.user_feedback",
field: "image",
});
Edited this answer, Its best to
Upload the image to Media-Folder, via http://localhost:1337/api/upload
Then use the same URL http://localhost:1337/api/upload and include this in your request as the doc says in https://docs.strapi.io/developer-docs/latest/plugins/upload.html#examples
<form>
<!-- Can be multiple files if you setup "collection" instead of "model" -->
<input type="file" name="files" />
<input type="text" name="ref" value="api::restaurant.restaurant" />
<input type="text" name="refId" value="5c126648c7415f0c0ef1bccd" />
<input type="text" name="field" value="cover" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
const form = document.querySelector('form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
await fetch('/api/upload', {
method: 'post',
body: new FormData(e.target)
});
});
</script>```
Your ref-id will be the ID of your entry, by entry It means the ID of your table's row or in no-sql you would say your document id.
Your ref is your service name as it suggests, your table name per say
Your field is the name of the field of the entry you want to upload the media too
Your files is simple the files that you want to upload
I would highly recommend you to use the template code given on docs then modify it, Instead of working on it directly. Thats what I did.
Related
I'm building a simple recipe collections app, and I'm running into a really weird scenario where when I edit a recipe item, the new data gets appended to my localhost:3000/ url. For example my original recipe item data was:
"Title: test",
"Ingredients: test",
"Cooking Directions: test"
But then after I edited the data, the new data also appended to my localhost:3000/ url. data appended to localhost url screenshot. My goal is not append this data to my url and stay at localhost:3000. Thanks and any help would be appreciated.
Here is my put request code:
updateRecipe = (e) => {
console.log(this.props.uniqueID);
const recipe = {
title: this.state.title,
ingredients: this.state.ingredients,
summary: this.state.summary
}
const url = `http://localhost:5000/recipes/${this.props.uniqueID}`;
axios.put(url, recipe)
.then(res => this.setState({
recipes: [...this.state.recipes, res.data],
},
() => console.log('recipe edited: ', res.data)
));
}
<form className="form-container" onSubmit={this.updateRecipe}>
<TextField
style={inputStyle}
className="form-input-title"
type="text"
onChange={this.onChangeHandler}
name="title"
id="standard-basic"
label="Title"
value={this.state.title}
/>
<TextField
style={inputStyle}
className="form-input-ingredients"
type="text"
onChange={this.onChangeHandler}
name="ingredients"
id="standard-basic"
label="Ingredients"
value={this.state.ingredients}
/>
<TextField
id="outlined-multiline-static"
label="Directions"
multiline
rows={6}
variant="outlined"
onChange={this.onChangeHandler}
name="summary"
className="form-input-directions"
style={inputStyle}
value={this.state.summary}
/>
<Fab style={style} className="add-recipe-button" color="primary" aria-label="add" type="submit">
<AddIcon />
</Fab>
</form>
This is the default behaviour if you use onSubmit handler for form.If this is not what you are looking for dont use onSubmit handler on the form instead use onClick handler for the submit button to call for updateRecipe functionality.Then Url is not modified.
I want to push form data with keys and values into JSON format from click on the submit button.
I don't want to create JSON manually. Please help me to short out this problem.
Use reactive forms from Angular.
Follow the steps below.
Create a Form Group and define the variables you need.
export class ProfileEditorComponent {
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
});
onSubmit() {
console.warn(this.profileForm.value);
}
}
Create your html file like below.
<form [formGroup]="profileForm">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<button type="submit" >Submit</button>
Please find the guide for the same.
https://angular.io/guide/reactive-forms
Play framework 2.4.x. A button is pressed on my home page that executes some code via Ajax, and returns its results beneath the button without loading a new page. The results wait for a user to input some text in a field and press "submit". Those results Look like this:
<li class="item">
<div>
<h3>Email: </h3>
<a>#email.tail.init</a>
<h3>Name: </h3>
<a>#name</a>
</div>
<div>
<h3>Linkedin: </h3>
<form class="linkedinForm" action="#routes.Application.createLinkedin" method="POST">
<input type="number" class="id" name="id" value="#id" readonly>
<input type="text" class="email" name="email" value="#email" />
<input type="text" class="emailsecondary" name="emailsecondary" value="" />
<input type="text" class="name" name="email" value="#name" />
<input type="text" class="linkedin" name="linkedin" value="" />
<input type="submit" value="submit" class="hideme"/>
</form>
</div>
<div>
<form action="#routes.Application.delete(id)" method="POST">
<input type="submit" value="delete" />
</form>
</div>
</li>
Along with some jquery that slides up a li after submission:
$(document).ready(function(){
$(".hideme").click(function(){
$(this).closest('li.item').slideUp();
});
});
However, since a form POST goes inside an Action that must a return an Ok(...) or Redirect(...) I can't get the page to not reload or redirect. Right now my Action looks like this (which doesn't compile):
newLinkedinForm.bindFromRequest.fold(
errors => {
Ok("didnt work" +errors)
},
linkedin => {
addLinkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
if (checkURL(linkedin.url)) {
linkedinParse ! Linkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
Ok(views.html.index)
}else{
Ok(views.html.index)
}
}
)
Is it possible to return Ok(...) without redirecting or reloading? If not how would you do a form POST while staying on the same page?
EDIT: Here is my attempt at handling form submission with jquery so far:
$(document).ready(function(){
$(".linkedinForm").submit(function( event ) {
var formData = {
'id' : $('input[name=id]').val(),
'name' : $('input[name=name]').val(),
'email' : $('input[name=email']).val(),
'emailsecondary' : $('input[name=emailsecondary]').val(),
'url' : $('input[name=url]').val()
};
jsRoutes.controllers.Application.createLinkedin.ajax({
type :'POST',
data : formData
})
.done(function(data) {
console.log(data);
});
.fail(function(data) {
console.log(data);
});
event.preventDefault();
};
});
This is an issue with the browser's behavior on form submission, not any of Play's doing. You can get around it by changing the behavior of the form when the user clicks submit.
You will first want to attach a listener to the form's submission. You can use jQuery for this. Then, in that handler, post the data yourself and call .preventDefault() on the event. Since your javascript is now in charge of the POST, you can process the data yourself and update your page's HTML rather than reloading the page.
What you need is use ajax to submit a form, check this: Submitting HTML form using Jquery AJAX
In your case, you can get the form object via var form = $(this), and then start a ajax with data from the form by form.serialize()
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
In order to accomplish this task, i had to use play's javascriptRouting
This question's answer helped a lot.
I'm not experienced with jquery so writing that correctly was difficult. For those that find this, here is my final jquery that worked:
$(document).ready(function(){
$("div#results").on("click", ".hideme", function(event) {
var $form = $(this).closest("form");
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
var email = $form.find("input[name='email']").val();
var emailsecondary = $form.find("input[name='emailsecondary']").val();
var url = $form.find("input[name='url']").val();
$.ajax(jsRoutes.controllers.Application.createLinkedin(id, name, email, emailsecondary, url))
.done(function(data) {
console.log(data);
$form.closest('li.item').slideUp()
})
.fail(function(data) {
console.log(data);
});
});
});
Note that my submit button was class="hideme", the div that gets filled with results from the DB was div#results and the forms were contained within li's that were class="item". So what this jquery is doing is attaching a listener to the static div that is always there:
<div id="results">
It waits for an element with class="hideme" to get clicked. When it gets clicked it grabs the data from the closest form element then sends that data to my controller via ajax. If the send is successful, it takes that form, looks for the closest li and does a .slideUp()
Hope this helps
I want to improve my website and figured out a good way to do it was by submitting forms via AJAX. But, I have so many forms that it would be inpractical to do $('#formx').submit(). I was wondering if there was a way to do this automatically by making an universal markup like;
<form class="ajax_form" meta-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
</form>
And have this submit to ajax/pagename.php, where it automatically includes inputx and inputy?
This would not only save me a lot of time but also a lot of lines of code to be written.
First question so I hope it's not a stupid one :)
Something like this should work for all forms. It uses jQuery - is this available in your project? This specific code chunk hasn't been tested per say, but I use this method all the time. It is a wonderful time saver. Notice I changed meta-submit to data-submit so that its value can be fetched using $('.elemenet_class').data('submit');
HTML
<!-- NOTE: All Form items must have a unique 'name' attribute -->
<form action="javascript:void(0);" class="ajax_form" data-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
<input type="submit" value="go" />
</form>
JavaScript
$('.ajax_form').submit(function(e){
var path = $(this).attr('data-submit'); //Path to Action
var data = $(this).serialize(); //Form Data
$.post(path, {data:data}, function(obj){
});
return false;
})
PHP
//DEBUGGING CODE
//var_dump($_POST);
//die(null);
$data = $_POST['data'];
$inputx = $data['inputx'];
$inputy = $data['inputy'];
you can create ajax fot text boxes so that it can update to database whenever change the focus from it.
<form id="ajax_form1">
<fieldset>
<input type="text" id="inputx" value="x_value" />
<input type="text" id="inputy" value="y_value" />
</fieldset>
</form>
<script>
$(document).ready(function()
{
$("form#ajax_form1").find(":input").change(function()
{
var field_name=$(this).attr("id");
var field_val=$(this).val();
var params ={ param1:field_name, param2:field_val };
$.ajax({ url: "ajax/pagename.php",
dataType: "json",
data: params,
success: setResult
});
});
});
</script>
Can anyone tell me why this is not working or give me another way into doing what I want.
I have a form on a page when click submit I want it to process into add.php and for it to open up in a DIV called right.
Form page
<script>
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
</script>
</head>
<body>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload">
</form>
</body>
Now if I add action to form to direct it to add.php all works fine so other script is ok yet when i do it this way,nothing happens it does not load add.php into the 'right' div like I want it to.
Anyone got any suggestions?
Your $("#Submit") selector does not match anything (the submit button has no id and is defined after that bind attempt), so the function is not bound to any event, thus never executed.
Instead the form acts the way it should: upon submit it posts its content to the url specified in the 'action' attribute. This is what happens, that div is never touched.
you have to go back to understand how jquery selectors work. How to bind a function to an event.
Is this your exact code? There are a few issues:
$("#Submit").click should be wrapped in a document ready
handler so it doesnt run before the page has actually loaded.
There is no button that matches #Submit
There is no div that matches #right
Try
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
</head>
<body>
<div id="right">
</div>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload" id="Submit">
</form>
you have to create on div in body tag which id will be right and
<input id="submit" type="submit" name="upload" >
add new div in body tag like this
<div id="right"></div>