mercredi 6 mai 2020

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

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();
        })
    }

}```

Aucun commentaire:

Enregistrer un commentaire