Page reload on a form submit! Rails API backend Javascript frontend - javascript

I'm having trouble figuring out my javascript. The e.preventDefault() is not working. I've tried changing the submit input to a button as well. I know with a form and using rails that it has an automatic rage reload but I thought e.preventDefault was suppose to stop that. Is there some hidden feature in the backend that I need to turn off? I set my project up to be an api by using an api flag. It also has all the right info for cors. My server is showing my data correctly ...it's just the frontend I cant get up.
I'm going to post a sample code I followed.
<html lang="en" dir="ltr">
<head>
<title>Problems</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
<script type="application/javascript" src="src/user.js" charset="UTF-8"></script>
<script type="application/javascript" src="src/problem.js" charset="UTF-8"></script>
</head>
<body>
<div class="container" id="container">
<h1>Everyone Has Problems</h1>
<div id="new-user-and-new-problem-container">
<form id="new-user-form">
<label>Your name:</label>
<input type="text" id="new-user-body"/>
<input type="submit"/>
</form>
</div>
</div>
<div id="problems-container" class="problems-container">
</div>
</body>
</html>```
src/user.js
```document.addEventListener('DOMContentLoaded', function(){
User.createUser()
})
class User {
constructor(user){
this.id = user.id
this.name = user.name
this.problems = user.problems
}
static createUser(){
let newUserForm = document.getElementById('new-user-form')
newUserForm.addEventListener('submit', function(e){
e.preventDefault()
console.log(e);
fetch('http://localhost:3000/api/v1/users', {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(
{
user: {
name: e.target.children[1].value
}
})
})
.then(resp => {
return resp.json()
})
.then(user => {
let newUser = new User(user)
newUser.displayUser()
})
})
}
displayUser() {
let body = document.getElementById('container')
body.innerHTML = ''
let userGreeting = document.createElement('p')
userGreeting.setAttribute('data-id', this.id)
let id = userGreeting.dataset.id
userGreeting.innerHTML = `<h1>Hey, ${this.name}!</h1>`
body.append(userGreeting)
if (this.problems) {
this.problems.forEach(function(problem){
let newProblem = new Problem(problem)
newProblem.appendProblem()
})
}
Problem.newProblemForm(this.id)
}
}```
src/problem.js
```class Problem {
constructor(problem){
this.id = problem.id
this.name = problem.name
this.description = problem.description
}
static newProblemForm(user_id) {
let body = document.getElementById('container')
let form =
`
<form id="new-problem-form">
<label>What's your problem?:</label>
<input type="text" id="problem-name"/>
<label>Describe it:</label>
<input type="text" id="problem-description"/>
<input type="submit"/>
<h4>Your current problems:</h4>
</form>
`
body.insertAdjacentHTML('beforeend', form)
Problem.postProblem(user_id)
}
//is it appropriate for this to be a static method?
static postProblem(user_id) {
let newForm = document.getElementById('new-problem-form')
newForm.addEventListener('submit', function(e){
e.preventDefault()
fetch('http://localhost:3000/api/v1/problems', {
method: "POST",
headers:{
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(
{
problem: {
name: e.target.children[1].value,
description: e.target.children[3].value,
user_id: user_id
}
}
)
})
.then(resp => resp.json())
.then(json => {
let newProblem = new Problem(json)
newForm.reset()
newProblem.appendProblem()
})
})
}
appendProblem(){
let problems = document.getElementsByClassName('problems-container')
let li = document.createElement('li')
li.setAttribute('data-id', this.id)
li.setAttribute('style', "list-style-type:none")
li.innerHTML = `${this.name} ~~ ${this.description}`
let solveForm = `<button type="button" id="${this.id}" class="solve-problem"> Solve </button>`
li.insertAdjacentHTML('beforeend', solveForm)
problems[0].append(li)
let button = document.getElementById(`${this.id}`)
this.solve(button)
}
solve(button){
button.addEventListener('click', function(e){
e.preventDefault()
fetch(`http://localhost:3000/api/v1/problems/${e.target.parentNode.dataset.id}`, {
method: "DELETE"
})
e.target.parentElement.remove();
})
}
}```

Try not splitting the element up.
document.getElementById('new-problem-form').
addEventListener('submit', function(e){
e.preventDefault()
}
even Jquery
$('#new-problem-form').addEventListener('submit', function(e){
e.preventDefault()
});
The preventDefault is working on the event..
Take this for example:
$('#message').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});
This is preventing the enter key from defaulting the submit based on the keydown function. Is this option the actual 'default' you're trying to stop?

Related

Calling a javascript function with parameters in innerHTML

I'm trying to build my own comment system.
Here's the code that show a comment box when clicking on the "Reply" button:
function postComment(i, parentId) {
let content;
if (parentId === undefined) {
content = commentBox.value
} else {
content = eval("subCommentBox"+i).value
}
const body = JSON.stringify({
"post_slug": location.pathname.slice(1),
"username": "quantong",
"parent_id": parentId,
"content": content,
})
fetch("http://localhost:8080/comments", {
method: "post",
headers: { "Content-Type": "application/json" },
body: body
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
}
})
commentBox.value = "";
window.location.reload();
}
let allElements = document.body.getElementsByClassName("replybtn");
let addCommentField = function () {
for (let i = 0; i < allElements.length; i++) {
if (allElements[i] === this) {
if (document.getElementsByClassName("replyform")[i].innerHTML.length === 0) {
document.getElementsByClassName("replyform")[i].innerHTML = `
<div class="form-group">
<textarea class="form-control" id="subCommentBox`+i+`" rows="3"></textarea>
</div>
<div class="d-flex flex-row-reverse">
<button type="button" class="btn btn-success" onclick="postComment(` + i + `, ` + allElements[i].id + `)">Comment</button>
</div>
`
}
}
}
};
window.onload = function() {
for (let i = 0; i < allElements.length; i++) {
allElements[i].addEventListener('click', addCommentField, false)
}
}
It worked fine if I put in a .js file.
The thing is after user is logged in, I want to pass username and profile picture as a body to the backend side, so I moved it to App.svelte file:
let commentBox;
function postComment(i, parentId) {
let content;
if (parentId === undefined) {
content = commentBox
} else {
content = eval("subCommentBox"+i).value
}
const body = JSON.stringify({
"post_slug": location.pathname.slice(1),
"image_url": responsePayload.picture,
"username": responsePayload.name,
"parent_id": parentId,
"content": content},
)
fetch("http://localhost:8090/comments", {
method: "post",
headers: { "Content-Type": "application/json" },
body: body
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
}
})
commentBox = "";
window.location.reload();
}
If I leave the innerHTML text as it is, it caused:
Uncaught ReferenceError: postComment is not defined
If I change it from:
<button type="button" class="btn btn-success" onclick="postComment(` + i + `, ` + allElements[i].id + `)">Comment</button>
to:
<button type="button" class="btn btn-success" on:click={() => postComment(i, allElements[i].id)}>Comment</button>
it will be rendered as:
So, in a .svelte file, how can I call a javascript function with parameters in innerHTML?
If you want to make this in Svelte you should try doing it the 'Svelte' way as well, that means dropping all this constructing html in javascript and injecting it.
Instead consider your markup as a reflection of 'state' and also use components to make your life easier.
Your state would be for example an array of comments and if a user clicked 'reply'.
<!-- This will render a 'Comment' component for each item in the comments -->
{#each comment as comment}
<Comment {...comment} />
{/each}
<!-- Comment.svelte -->
<script>
export let id = "";
export let children = [];
export let text = "";
let isReplying = false;
let reply = ""
async function postComment() {
// Hide comment box
isReplying = false;
// Send to server, the inputted text is available in 'reply'
const res = await fetch(...).then(res => res.json();
// Append to children so it appears 'live'
children = [...children, res]
}
</script>
<!-- The post itself -->
<div>{text}</div>
<!-- Each child is a comment of it's own so render it with this component -->
{#each children as child}
<svelte:self {...child} />
{/each}
<!-- The reply button simply toggles a state -->
<button on:click={() => isReplying = !isReplying}>Reply</button>
<!-- Show this based on state -->
{#if isReplying}
<textarea bind:value={reply}>Blabla</textarea>
<button on:click={postComment}>Send</button>
{/if isReplying}
This should give you a fair idea of what direction to go in.
Remember that your UI is a reflection of your state. So just changed the state and Svelte will take care of the rest (inserting, removing, updating domelements)

Uncaught ReferenceError: updateIngredient is not defined at HTMLButtonElement.editIngredient

Not sure what I am doing wrong here but I am trying to create a simple update/edit function to be able to edit ingredients that exist with the dataset. I am getting the above error when doing so.
Here is my code:
deleteIngredient(){
const ingredientId = this.parentElement.dataset.id
fetch(`${recipeUrl}/${ingredientId}`, {
method: "DELETE"
})
this.parentElement.remove()
}
updateIngredient(){
var editForm = document.getElementById("ingredient-input")
console.log(editForm)
}
editIngredient(){
var editForm =
`<form id="edit-form">
<input type="text" id="edit-input">
<input type="submit" value="Edit Ingredient">
</form>`
this.parentElement.insertAdjacentHTML('beforeend', editForm)
console.log(this.parentElement)
document.getElementById('edit-form')
editForm.addEventListener("click", updateIngredient)
}
const editBtn = document.createElement('button')
editBtn.addEventListener("click", this.editIngredient)
editBtn.innerText = "Edit"
li.appendChild(editBtn)
ingredientList.appendChild(li)
What am I doing wrong here? This should at least not be throwing this error. Please Help!
Edit: Updated code using onclick got rid of the error!
const editForm =
`<form id="edit-form">
<input type="text" id="edit-input">
<input type="submit" value="Edit Ingredient" onclick="updateIngredient">
</form>`
this.parentElement.insertAdjacentHTML('beforeend', editForm)
console.log(this.parentElement)
document.getElementById('edit-form')
//editForm.addEventListener("click", updateIngredient)
}
updateIngredient(){
document.querySelector("data-id")
}
I could still use help with updateIngredient which will take the ingredient and edit it using the edit form. Any other advice would be so appreciated!
Edit 2: Still feeling a bit lost so here is my full Ingredient class and index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles/styles.css">
<title>Recipe App</title>
</head>
<body>
<h1>Easy Recipe and Ingredient Saver</h1>
<br>
<h2>Instructions:</h2>
<h3>Enter the name of your recipe below in the top form.</h3>
<h3>After creation add all the ingredients for that recipe separately and hit enter to save to the recipe.</h3>
<div id="container">
<h4>Create a Recipe:</h4>
<form id="recipe-form">
<input type="text" id="recipe-input">
<input type="submit" value="Create Recipe">
</form>
<ul id="recipe-list">
</ul>
</div>
<script src='./src/ingredient.js'></script>
<script src='./src/recipe.js'></script>
<script src='./src/index.js'></script>
</body>
</html>
class Ingredient {
constructor(ingredient) {
this.recipe_id = ingredient.recipe_id
this.name = ingredient.name
this.id = ingredient.id
}
static createIngredient(e){
e.preventDefault()
const ingredientInput = e.target.children[0].value
const ingredientList = e.target.nextElementSibling
const recipeId = e.target.parentElement.dataset.id
Ingredient.submitIngredient(ingredientInput, ingredientList, recipeId)
e.target.reset()
}
renderIngredient(ingredientList){
const li = document.createElement('li')
li.dataset.id = this.recipe_id
li.innerText = this.name
const deleteBtn = document.createElement('button')
deleteBtn.addEventListener("click", this.deleteIngredient)
deleteBtn.innerText = "X"
li.appendChild(deleteBtn)
ingredientList.appendChild(li)
const editBtn = document.createElement('button')
editBtn.addEventListener("click", this.editIngredient)
editBtn.innerText = "Edit"
li.appendChild(editBtn)
ingredientList.appendChild(li)
}
static submitIngredient(ingredient, ingredientList, recipeId){
fetch(ingredientUrl, {
method: "POST",
headers: {
"Content-type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({
name: ingredient,
recipe_id: recipeId
})
}).then(res => res.json())
.then(ingredient => {
let newIngredient = new Ingredient(ingredient)
newIngredient.renderIngredient(ingredientList)
})
}
deleteIngredient(){
const ingredientId = this.parentElement.dataset.id
fetch(`${recipeUrl}/${ingredientId}`, {
method: "DELETE"
})
this.parentElement.remove()
}
editIngredient(){
const editForm =
`<form id="edit-form">
<input type="text" id="edit-input">
<input type="submit" value="Edit Ingredient" onclick="updateIngredient">
</form>`
this.parentElement.insertAdjacentHTML('beforeend', editForm)
console.log(this.parentElement)
document.getElementById('edit-form')
//editForm.addEventListener("click", updateIngredient)
}
updateIngredient(){
const ingredientId = this.parentElement.dataset.id
ingredientId.innerText("")
}
}

Vue not working correctly with the html (refreshing when I press a button when it isn't supposed to)

I am having a problem where my vue doesn't work correctly.When I press the button it clears out the input(it shouldn't) and does nothing.The variables codigo and payload do not show anything in the screen. Even when I change them via console. It first was having the issue where the 'app' tag wasn't being found by the script even with it on the bottom. To solve it I had to add the line Vue.config.silent=true which made the warning disappear but the code still doesn't work. I am new to vue and web design so expect basic mistakes. I am running it in the 'node' docker image container.
<!DOCTYPE html>
<html>
<head>
<title>Vue test</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js" ></script >
<script>
Vue.config.silent = true;
</script>
<body>
<h2>Manipulador de Recursos</h2>
<br>
<div id='app'>
<form>
URL do Recurso: <input type="text" v-model="recurso" size=50><br><br>
Repr. do Recurso: <input type="text" v-model="repr" size=100><br><br>
Metodo HTTP:
<button v-on:click="doGet">GET</button>
<button v-on:click="doPost">POST</button>
<button v-on:click="doPut">PUT</button>
<button v-on:click="doDelete">DELETE</button> <br><br><br>
</form>
<b>Retorno:</b><br><br>
Codigo HTTP: <span v-bind:id="codigo"></span>
<br><br>
Payload: <span v-html="payload"></span>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script defer >
var myapp = new Vue({
el: "app",
data: {
"codigo":"",
"payload":"",
},
methods:{
// GET
"doGet" : function() {
console.log("GET")
this.clear();
var url = this.recurso;
axios
.get(url)
.then(function (response) {
this.codigo = response;
this.payload =response.data ;
console.log (response);
})
.catch(function (error){
this.codigo = error;
})
},
// POST
doPost : function() {
console.log("POST")
this.clear();
var url = this.recurso;
var data = this.repr;
axios
.post(url, data)
.then((response) => {
this.codigo = response;
this.payload =response.data ;
console.log(response)
})
.catch((error) => {
this.codigo = error;
})
},
//(...)
}
})
</script>
</html>
You don't want to prevent the click action, as suggested above, but the submit action of the form.
<form #submit.prevent="doGet()">
<!-- form stuff -->
</form>
At first, your methods must be inside methods property:
var myapp = new Vue({
//.......
data: {
codigo: "",
payload: ""
},
methods: {
doGet: function() { /*.......*/},
doPost: function() { /*.......*/}
}
})
and in this example your buttons can do default action (the form sending) so it may be necessary: v-on:click.prevent="doGet()".
This solved it Simple vue app doesn't show anything :
Because you didn't render anything in your root component.
In your index.html, render the app component:
<div id="app"> <app> <!-- html code, buttons etc--> </app> </div>
Adding the tags.
Along with this: adding type="button" to the buttons because since they where inside a forms they refreshed the page.
And finally I added:
document.addEventListener("DOMContentLoaded", function(event) {
Around my var myapp = new Vue({

Can't delete newly created list item without refreshing the page and trying again ES6

Some context: I'm trying to finish building out the delete functionality of my minimal note-taking app.
Every time I create a new note, it will appear at the end of my list of notes. However, if I try to delete the newly created note, it won't work. I have to refresh the page and try again for it to work.
I keep getting these two errors:
"Uncaught TypeError: Cannot read property 'parentNode' of null at HTMLUListElement."
"DELETE http://localhost:3000/api/v1/notes/undefined 404 (Not Found)"
Otherwise, I'm able to delete any other note with no problem.
Here is my js code:
// display list of notes on the side
const noteContainer = document.querySelector(".column is-one-quarter")
const noteList = document.querySelector(".menu-list")
fetch('http://localhost:3000/api/v1/notes')
.then(function(response) {
return response.json();
})
.then(function(notes) {
notes.forEach(function(note) {
noteList.innerHTML += `<li id="list-item" data-id=${note.id}><a id="note" data-id=${note.id} class="menu-item">${note.title}</a><i id="delete" data-id=${note.id} class="fas fa-minus-circle has-text-grey-light hvr-grow"></i></li>`
})
})
// display details of each note
const noteDetail = document.querySelector(".note-detail")
noteList.addEventListener('click', function(event) {
if (event.target.className === "menu-item") {
fetch(`http://localhost:3000/api/v1/notes/${event.target.dataset.id}`)
.then(function(response) {
return response.json()
})
.then(function(note) {
noteDetail.innerHTML = `<h1 contenteditable="true" id="title" data-id=${note.id} class="subtitle is-2">${note.title}</h1><p contenteditable="true" id="body" data-id=${note.id} class="subtitle is-6">${note.body}</p><a id="save" data-id=${note.id} class="button is-small">Save</a>`
})
}
})
// i should be able to edit the title and body of a note when i click
// on it and it should save when i click on the button.
noteDetail.addEventListener('click', function(event) {
if (event.target.id === "save") {
const noteId = event.target.dataset.id
const editTitleInput = document.querySelector(`h1[data-id="${noteId}"]`)
const editBodyInput = document.querySelector(`p[data-id="${noteId}"]`)
const singleNote = document.querySelector(`a[data-id="${noteId}"]`)
fetch(`http://localhost:3000/api/v1/notes/${noteId}`, {
method: "PATCH",
headers: {
'Content-Type': 'application/json',
'Accepts': 'application/json'
},
body: JSON.stringify({
title: editTitleInput.innerText,
body: editBodyInput.innerText
})
}).then(function(response) {
return response.json()
}).then(function(note) {
singleNote.innerText = editTitleInput.innerText
})
}
})
// when i click on the button, a form with a title and body input
// should display on the right.
const newNoteButton = document.querySelector("#create")
newNoteButton.addEventListener('click', function(event) {
fetch("http://localhost:3000/api/v1/notes")
.then(function(response) {
return response.json()
})
.then(function(note) {
noteDetail.innerHTML = `<input id="title" class="input subtitle is-5" type="text" placeholder="Title">
<textarea id="body" class="textarea subtitle is-5" placeholder="Body" rows="10"></textarea><a id="add" class="button has-text-black" style="margin-left: 594px;">Add Note</a>`
// when i click on 'add button', a new note with a title and body
// should be created and added to the list of notes.
const noteTitleInput = document.querySelector("#title")
const noteBodyInput = document.querySelector("#body")
const addNoteButton = document.querySelector("#add")
addNoteButton.addEventListener('click', function(event) {
// event.preventDefault()
fetch('http://localhost:3000/api/v1/notes', {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accepts': 'application/json'
},
body: JSON.stringify({
title: noteTitleInput.value,
body: noteBodyInput.value
})
}).then(function(response) {
return response.json()
}).then(function(note) {
noteList.innerHTML += `<li data-id=${note.id}><a id="note" data-id=${note.id} class="menu-item">${note.title}</a><i id="delete" class="fas fa-minus-circle has-text-grey-light hvr-grow"></i></li>`
})
})
})
})
// i should be able to delete a note when i click on the button.
noteList.addEventListener('click', function(event) {
// event.preventDefault()
if (event.target.id === "delete") {
const noteId = event.target.dataset.id
// const noteListItem = document.querySelector("#list-item")
const noteListItem = document.querySelector(`li[data-id="${noteId}"]`)
const singleNote = document.querySelector(`a[data-id="${noteId}"]`)
fetch(`http://localhost:3000/api/v1/notes/${noteId}`, {
method: "DELETE",
})
// debugger
// lastNote = noteList.lastElementChild
// noteList.removeChild(lastNote)
// singleNote.parentElement.remove()
noteListItem.parentNode.removeChild(noteListItem)
noteDetail.innerHTML = ""
}
})
Here is my html code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.css">
<link href="css/hover.css" rel="stylesheet" media="all">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<link rel="stylesheet" href="css/note.css">
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1 class="title is-1">Jot</h1>
<div class="columns">
<div class="column is-one-quarter">
<p class="menu-label" style="font-size:15px;">
Notes <i id="create" class="fas fa-plus-circle has-text-grey-light hvr-grow" style="margin-left: 10px; width: 20px; height: 30px; font-size: 24px;"></i>
</p>
<ul class="menu-list">
</ul>
</div>
<div class="column is-three-fifths">
<div class="note-detail">
</div>
</div>
<div class="column">
</div>
</div>
<script src="index.js"></script>
</body>
</html>
Any help would be greatly appreciated. :)
You're nesting strings on these two lines:
const noteListItem = document.querySelector(`li[data-id="${noteId}"]`)
const singleNote = document.querySelector(`a[data-id="${noteId}"]`)
Your template literal is creating a string and you're putting that inside of quotes. For example, if your noteId is say 12. your code is ending up like this:
const noteListItem = document.querySelector("li[data-id="'12'"]")
const singleNote = document.querySelector("a[data-id="'12'"]")
I'm not 100% sure that's your issue but it's the first thing that popped out to me.
You can check out MDN to brush up on your Template literals (Template strings).

How do I populate HTML form with database values when I click edit button?

I want to populate form fields with database values when I click the edit button. The form I want to populate is responsible for updating a diary entry's attributes (which comprise of title and body).
Currently when I click the edit button, I get an empty edit form. Therefore, if I want to retain some existing information on the entry (for example the body of the entry), I have to copy the body of the entry into the edit form before I update the entry which is a cumbersome task.
How do I go about implementing this?
Function for updating a diary entry
function edit_entry(entry_id){
// open modal to edit diary entry
var modal = document.getElementById('edit_modal');
modal.style.display = "block";
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
};
document.getElementById('edit_modal').addEventListener('submit', updateDetail);
function updateDetail(e){
e.preventDefault();
let title = document.getElementById('title').value;
let body = document.getElementById('body').value;
var statusCode;
fetch('http://localhost:5000/api/v1/entries/'+parseInt(entry_id),{
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + window.localStorage.getItem('token')
},
body: JSON.stringify({
"title": title,
"body": body,
})
})
.then((result) => {
statusCode = result.status;
return result.json();
})
.then((data) =>{
window.alert(data.message);
modal.style.display = "none";
redirect: window.location.replace('./viewAllEntries.html');
});
}
}
HTML form
<form action="" class ="add-content" id="edit_modal">
<h2>My Diary | Edit Entry <i class="fa fa-book" aria-hidden="true"></i></h2>
<div class="form-group">
<label></label>
<textarea id = "title" class ="input-control"></textarea>
</div>
<div class="form-group">
<label></label>
<textarea id = "body" class ="input-control"> </textarea>
</div>
<div class ="form-group">
<label>&nbsp</label>
<button type = "submit" class ="button button-block" />Save <i class="fa fa-floppy-o" aria-hidden="true"></i></button>
</div>
</form>
When you open the modal just grab the data for the entry from your API. Try something like the code below.
$yourUrlToFetchTheData should be the url of the api route to fetch the data you need.
fetch($yourUrlToFetchTheData, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + window.localStorage.getItem('token')
}
})
.then((result) => {
// TODO FILL THE TEXTAREAS WITH THE VALUES OF THE RESULT.
$("title").text(result.json.title);
$("body").text(result.json.body);
})
.then((data) => {
// TODO DO SOMETHING WITH THE ERROR.
});
Put this code after modal.style.display = "block"; and modify it a bit!

Categories

Resources