При нажатии функция не работает с начальной загрузки - PullRequest
0 голосов
/ 24 января 2019

Вот моя функция при нажатии

$(".addPizza").on("click", function(event) {
  event.preventDefault();
  console.log("hello")
  let userId = $("#userId").attr("data-id");
  let pizzaRecipe = $('#pizza-recipe').val().trim();
  let ingredients = JSON.stringify(obj);
  let title = $("#pizza-title").val().trim();

  let newPizza = {
    userid: userId,
    recipe: pizzaRecipe,
    ingredients: ingredients,
    totalCal: calTotal,
    title: title
  };
  $.ajax('/api/pizza', {
    type: 'POST',
    data: newPizza
  }).then(() => {
    console.log('Created new pizza recipe');
    location.reload();
  });
  $.ajax('/', newPizza).then(() => {
    console.log('Created new pizza recipe');
    // location.reload();
  });
});

и вот мой модальный html

<button id="button" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@getbootstrap">Add a recipe</button>
<!-- end of button -->

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">New Recipe</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
      </div>
      <div class="modal-body">
        <form>

          <form class="recipe-form" action="/pizza" method="POST">
            <a id="userId" data-id=<%=user.id %></a>



            <input type="text" id="pizza-title" name="pizza-title" placeholder="title"><br>
            <input type="text" id="pizza-recipe" name="pizza-recipe" placeholder="recipe"><br>

            <label for="vegy1">Cucumber</label>
            <input type="number" class="quant" name="vegy1" data-name="cucumber" min="0" max="3" value="0">

            <label for="vegy2">Tomato</label>
            <input type="number" class="quant" name="vegy2" data-name="tomato" min="0" max="3" value="0">

            <label for="vegy3">Pineapple</label>
            <input type="number" class="quant" name="vegy3" data-name="pineapple" min="0" max="3" value="0">

            <label for="vegy4">Avocado</label>
            <input type="number" class="quant" name="vegy4" data-name="avocado" min="0" max="3" value="0"><br>

            <label for="vegy5">Eggplant</label>
            <input type="number" class="quant" name="vegy5" data-name="eggplant" min="0" max="3" value="0">

            <label for="vegy6">Olive</label>
            <input type="number" class="quant" name="vegy6" data-name="olive" min="0" max="3" value="0">

            <label for="vegy7">Onion</label>
            <input type="number" class="quant" name="vegy7" data-name="onion" min="0" max="3" value="0">

            <label for="vegy8">Mushroom</label>
            <input type="number" class="quant" name="vegy8" data-name="mushroom" min="0" max="3" value="0"><br>

            <label for="vegy9">Garlic</label>
            <input type="number" class="quant" name="vegy9" data-name="garlic" min="0" max="3" value="0">

            <label for="vegy10">Spinach</label>
            <input type="number" class="quant" name="vegy10" data-name="spinach" min="0" max="3" value="0">

            <label for="vegy11">Cilantro</label>
            <input type="number" class="quant" name="vegy11" data-name="cilantro" min="0" max="3" value="0">

            <label for="vegy12">Chicken</label>
            <input type="number" class="quant" name="vegy12" data-name="chicken" min="0" max="3" value="0"><br>

            <label for="vegy13">Anchovy</label>
            <input type="number" class="quant" name="vegy13" data-name="anchovy" min="0" max="3" value="0">

            <label for="vegy14">Bacon</label>
            <input type="number" class="quant" name="vegy14" data-name="bacon" min="0" max="3" value="0">

            <label for="vegy15">Sausage</label>
            <input type="number" class="quant" name="vegy15" data-name="sausage" min="0" max="3" value="0">

            <label for="vegy16">Beef</label>
            <input type="number" class="quant" name="vegy16" data-name="beef" min="0" max="3" value="0"><br>

            <label for="vegy17">Ham</label>
            <input type="number" class="quant" name="vegy17" data-name="ham" min="0" max="3" value="0">

            <label for="vegy18">Pepperoni</label>
            <input type="number" class="quant" name="vegy18" data-name="pepperoni" min="0" max="3" value="0">

            <label for="vegy19">Salami</label>
            <input type="number" class="quant" name="vegy19" data-name="salami" min="0" max="3" value="0">

            <label for="vegy20">Banana</label>
            <input type="number" class="quant" name="vegy20" data-name="banana" min="0" max="3" value="0"><br>

            <p id="totalCal"></p>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              <button type="submit" class="btn btn-primary addPizza">Add Recipe</button>
            </div>

          </form>
      </div>
    </div>
  </div>
</div>

let mysql = require("mysql");

let connection;

if (process.env.JAWSDB_URL) 
    // DB is JawsDB on Heroku
    connection = mysql.createConnection(process.env.JAWSDB_URL);
else 
    // DB is local on localhost
    connection = mysql.createConnection({
        port: 3306,
        host: 'localhost',
        user: 'root',
        password: 'pass',
        database: 'pizza_recipe_db'
    });

// Establish connection to MySQL
connection.connect((err) => {
    if (err) {
        console.error(`error connecting MySQL: ${err.stack} \n`);
        return;
    }
    console.log(`Connected to MySQL as id ${connection.threadId} \n`);
});

// Export connection
module.exports = connection;

Это также выдает мне эту ошибку, когда я нажимаю кнопку добавления рецепта GET http://localhost:3000/ net :: ERR_EMPTY_RESPONSTPOST http://localhost:3000/api/pizza net ::ERR_CONNECTION_REFUSED

POST http://localhost:3000/api/pizza net :: ERR_CONNECTION_REFUSED

Мне сказали, что я должен использовать "делегирование событий", хотя я не уверен, как это сделать.

Спасибо за вашу помощь.Если вам нужно больше кода, просто дайте мне знать.спасибо!

1 Ответ

0 голосов
/ 24 января 2019

Вы не закрыли тег привязки должным образом в HTML, и поэтому идентификатор пользователя неверен.Проверьте следующую строку

<a id="userId" data-id=<%=user.id %></a>

Это должно быть

<a id="userId" data-id=<%=user.id %>></a>

Поскольку он не был правильно закрыт, JS отправлял userid = 3 </a и в Mysql ваш столбец user_id не является текстом, Этоцелое число без знака.Вот почему ваш код вставки не смог вставить текстовое значение в целочисленный столбец, и возникла исключительная ситуация sql, и работа сервера была завершена.Вот почему у вас есть ошибка

http://localhost:3000/          net::ERR_EMPTY_RESPONSTPOST 
http://localhost:3000/api/pizza net::ERR_CONNECTION_REFUSED

Поскольку сервер закрыт, и он не работает.

Измените тег привязки, указанный выше, и ваш код будет работать отлично.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...