Delete in the front end UI and prepopulate forms

Adil Ali
Adil Ali used Ask the Experts™
on
I want to prepopualate my forms

Snapshot_19-05-08_10-59-40.png
Snapshot_19-05-08_11-00-41.png
Above I have two screen shots The first screen shot is a prepopulated form and the second screen shot shows the
rest of the movies listed from 7-20 by id number. I wanted to know how I can prepopulate the rest of the fields because when I click on
the field that starts with 7 or 20 for example the same information shows up for the movie name that begins with 5

<html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
    <link href="mystyle.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
      <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
    <script src="mycrud.js"></script>
    </head>
    <body>
    <title>My Movies</title>
    <header>
        <h1>Movies</h1>
    </header>
    <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 Movie</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 id="newForm">
                        <div class="form-group row">
                            <label for="idmovielist" class="col-sm-2 col-form-label">ID</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="intNum" autocomplete="on">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="name" class="col-sm-2 col-form-label">name</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="name" autocomplete="on">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="thumnail_path" class="col-sm-2 col-form-label">thumnail path</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="thumnail_path" autocomplete="on">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="description" class="col-sm-2 col-form-label">description</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="description" autocomplete="on">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="year_released" class="col-sm-2 col-form-label">year released</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="year_released" autocomplete="on">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="language_released" class="col-sm-2 col-form-label">language released</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="language_released"
                                       autocomplete="on">
                            </div>
                        </div>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button id="movieAdded" type="button" class="btn btn-primary" data-toggle="modal"
                                data-target=#exampleModal>Add
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="exampleModal2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel2"
         aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel2">Updated Movie</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 id="updateForm">
                        <div class="form-group row">
                            <div class="col-sm-10">
                                <input type="hidden" class="form-control" id="movieId">
                            </div>
                        </div>

                        <label for="idmovielist" class="col-sm-2 col-form-label">ID</label>
                        <div class="col-sm-10">
                            <input value ="5" type="text" class="form-control" id="intNum">
                        </div>
                        <div class="form-group row">
                            <label for="name" class="col-sm-2 col-form-label">name</label>
                            <div class="col-sm-10">
                                <input value = "Jumanji" type="text" class="form-control" id="name">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="thumnail_path" class="col-sm-2 col-form-label">thumnail path</label>
                            <div class="col-sm-10">
                                <input value = "bilbibimfig" type="text" class="form-control" id="thumnail_path">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="description" class="col-sm-2 col-form-label">description</label>
                            <div class="col-sm-10">
                                <input  value = "action comdedy" type="text" class="form-control" id="description">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="year_released" class="col-sm-2 col-form-label">year released</label>
                            <div class="col-sm-10">
                                <input value = "1996" type="text" class="form-control" id="year_released">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="language_released" class="col-sm-2 col-form-label">language released</label>
                            <div class="col-sm-10">
                                <input  value="urdu" type="text" class="form-control" id="language_released">
                            </div>

                        </div>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button id="updateMovie" type="button" class="btn btn-primary" data-toggle="modal"
                                data-target=#exampleModal2>Update
                        </button>
                        <button id = "deleteMovie" type="buton" class="btn btn-primary" data-toggle="modal"
                        data-target=#exampleModal2>Delete
                      </button>
                    </form>

                </div>
            </div>
        </div>
    </div>
    <button id="movieAdded" type="button" class="btn btn-primary" data-toggle="modal" data-target=#exampleModal>Add</button>
    <table class="table table-bordered table-hover" width="100%">
        <thead style="background-color:#ddd;" class="table-borderless">
        <tr>
            <th>idmovielist</th>
            <th>name</th>
            <th>thumnail path</th>
            <th>description</th>
            <th>year released</th>
            <th>language released</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody id="movies">
        </tbody>
    </table>
    </body>
    </html>

Open in new window


Above is my html I tried to create a separate form modal pop up but it did not work.
Also when executing my delete method I am having to go back into my delete ajax function and changing the id number and also I am having to
go back in my html update form to change the values how can I do that with out having to go back and changes values from my html and java script file front end
$(function() {
  //Fill the list when the page loaded
  renderMovieList('movies');

  $("#movieAdded").click(function(a) {
      a.preventDefault();
    let mydata = {
      idmovielist: $($("#newForm")[0].intNum).val(),
      name: $($("#newForm")[0].name).val(),
      thumnail_path: $($("#newForm")[0].thumnail_path).val(),
      description: $($("#newForm")[0].description).val(),
      year_released: $($("#newForm")[0].year_released).val(),
      language_released: $($("#newForm")[0].language_released).val(),
    }

    $("#newForm").trigger("reset");
    $("#newForm").toggle();
    $.ajax({
      method: "POST",
      url: "http://localhost:3000/movielist/addMovie",
      dataType: "json",
      data: mydata,
  }).always(function(data){
        console.log('always',data);
        renderMovieList();
    });
  });

  $("#updateMovie").on("click", function(a) {
      a.preventDefault();
    let updatedata = {
      idmovielist: $($("#updateForm")[0].intNum).val(),
      name: $($("#updateForm")[0].name).val(),
      thumnail_path: $($("#updateForm")[0].thumnail_path).val(),
      description: $($("#updateForm")[0].description).val(),
      year_released: $($("#updateForm")[0].year_released).val(),
      language_released: $($("#updateForm")[0].language_released).val(),
    }

    $("#updateForm").trigger("reset");
    $("#updateForm").toggle();

    $.ajax({
      url: "http://localhost:3000/movielist/updateMovie/18",
      method: 'PUT',
      dataType: 'json',
      data: updatedata,
    }).always(function(data){
          console.log(data);
          renderMovieList();
  });
});
  $('#deleteMovie').on('click',function(){
    //a.preventDefault;
    let deletedata = {
      idmovielist: $($("#updateForm")[0].intNum).val(),
      name: $($("#updateForm")[0].name).val(),
      thumnail_path: $($("#updateForm")[0].thumnail_path).val(),
      description: $($("#updateForm")[0].description).val(),
      year_released: $($("#updateForm")[0].year_released).val(),
      language_released: $($("#updateForm")[0].language_released).val(),
    }

    //$("#updateForm").trigger("reset");
    //$("#updateForm").toggle();

    $.ajax({
      url: "http://localhost:3000/movielist/5",
      method: 'DELETE',
      dataType: 'json',
      data: deletedata,
    }).always(function(data){
          console.log(data);
          renderMovieList();
  });
  });

  });

     $("body").on('click', '.editMovie', function(a) {
       a.preventDefault();

       renderMovieList($($(this)[0]).data("movieId"));
     });

     $("body").on('click', '.deleteMovie', function(a) {
       a.preventDefault();

       renderMovieList($($(this)[0]).data("movieId"));
     });
//FUNCTIONS PART----------------------------------------------

function renderMovieList() {
  $.ajax({
    method: "GET",
    url: "http://localhost:3000/movielist",
    dataType: "json",
    success: function(response) {
      $('#movies').empty();
      $.each(response, function(i, movie) {
        const rowText = "<tr>" +
          "<td>" + movie.idmovielist + "</td>" +
          "<td>" + movie.name + "</td>" +
          "<td>" + movie.thumnail_path + "</td>" +
          "<td>" + movie.description + "</td>" +
          "<td>" + movie.year_released + "</td>" +
          "<td>" + movie.language_released + "</td>" +
          "<td>" + "<button button id = \"deleteMovie\" type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal2\">Delete</button>" + "</td>" +
          "<td>" + "<button button id = \"editMovie\" type=\"button\"  class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal2\">Edit</button>" + "</td>";
        $("#movies").append(rowText);
      });
    }
  });
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
OK. I'll give you a general overview on how you normally do this. There are a couple of ways to do it.

With the code you currenty have, the easiest way is to make an AJAX request back to the server to get a new copy of the pre-populated form. On each of your Movie rows, you have Edit and Delete button. When you click on the Edit button, you would make an AJAX request to the server to grab the edit form content. You would need to pass in the ID of the record you want to edit. The easiest way to do that would be to drop the ID into a data attribute on the button itself. In your renderMovieList method, add in the data attribute. FYI - in your renderMovieList you are creating the Edit and Delete buttons with an ID. This will mean that every button has the same ID which is not valid HTML. Use a class instead:

 "<td><button type='button' class='btn btn-danger edit-movie' data-toggle='modal' data-target='#exampleModal2' data-movieid=" + movie.idmovielist + ">Edit</button></td>";

Now you can hook into that data attribute:

$('.edit-movie').click(function(e) {
    var movieId = $(this).data('movieid'); // get the Movie ID from the Edit button
    $( "#exampleModal2 .modal-body" ).load( "getMovie.php", { id: moveId }, function() {
        // now show your modal popup.
    });
});

Open in new window

The getMovie.php script will receive the movieid in the $_GET['id'] variable so you can use that to query your database and generate the <form id="updateForm"> code. Once the AJAX request is finished it will drop that content into the popup so when you display it, it will contain the correct info.

Author

Commented:
but this project is not runned on php

Author

Commented:
also what do I put for //show modal pop up
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Ah right. Sorry, I just assumed that your server would be running PHP scripts. Regardless, you still need to create a server-side script that generates your HTML form (http://localhost:3000/movielist/editMovieForm for example). Make sure that script takes in the Movie ID. Previously I said that it would be in the GET request. That's wrong - it's passed in the POST request.

And to show your modal manually, you just use $('#exampleModal2').modal()

Author

Commented:
how do I do that in node js

Author

Commented:
const express = require('express');
const app = express();
const mysql = require('mysql');
const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
const mysqlConnection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'Adil@123',
  database: 'movies'

});
mysqlConnection.connect(err=>{
  if (err) {
    console.log('It was not successful \n Error:' + JSON.stringify(err,undefined,2));
  } else {
    console.log('Its a success');
  }
  });
 //  Collecting all the movies from the movielist
  app.get('/movielist',(req,res)=> {
    mysqlConnection.query("SELECT * FROM movielist", (err, rows,fields)=> {
      if (!err) {
        res.send(rows);
      } else {
        console.log(err);
      }
    });
  });
 // Finding a movie based on the `idmovielist` number
   app.get('/movielist',(req,res) => {
    mysqlConnection.query("SELECT * FROM movielist WHERE idmovielist = ?",[req.params.id],(err, rows,fields) =>{
    if (!err) {
      res.send(rows);
    } else {
    console.log(err);
    }
    });
  });

  // Delting a movie
   app.delete('/movielist/:id',(req,res) => {
    mysqlConnection.query("DELETE FROM movielist WHERE idmovielist = ?",[req.params.id],(err,rows,fields) =>{
      if (!err) {
        res.send("Movie is deleted");
      } else {
      console.log(err);
    }
    });
  });
  // Inserting a movie
  app.post('/movielist/addMovie',(req, res) => {
    //console.log("movielist/addMovie : ",req.body);
   mysqlConnection.query("INSERT INTO movielist (`idmovielist`,`name`,`thumnail_path`,`description`,`language_released`,`year_released`) VALUES ('"+req.body.idmovielist+"', '"+req.body.name+"','"+req.body.thumnail_path+"', '"+req.body.description+"', '"+req.body.year_released+"', '"+req.body.language_released+"')",
   (err,rows) => {
     if (!err) {
       res.send("Movie is added");
     } else {
       console.log(err);
     }
  });
});

app.put('/movielist/updateMovie/:id',(req,res) =>{
  let update = req.body;
  mysqlConnection.query("UPDATE movielist SET name = '"+update.name+"', thumnail_path = '"+update.thumnail_path+"', description = '"+update.description+"', year_released = '"+update.year_released+"', language_released = '"+update.language_released+"' WHERE idmovielist = '"+update.idmovielist+"'",
 /*update.name,update.thumnail_path,update.description,update.year_released,update.language_released,*/req.params.id,function (err, results) {
    if (!err) {
      res.send("Movie list is updated" + update);
    } else {
      console.log(err);
    }
  });
});

// localhost:3000
app.listen(3000,() => {
  console.log('We got it running');
});
module.exports = app;

Open in new window

this is my backend code in node js
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
I have no idea !!

If you need help with Node, then I would suggest you edit your question and add it to the NodeJS zones.

Author

Commented:
so your saying I need to add something in my back end

Author

Commented:
Chris Staton

app.post('/movielist/editMovieForm/:id', (req, res) => {
  mysqlConnection.query("INSERT INTO movielist (`idmovielist`,`name`,`thumnail_path`,`description`,`language_released`,`year_released`) VALUES ('"+req.body.idmovielist+"', '"+req.body.name+"','"+req.body.thumnail_path+"', '"+req.body.description+"', '"+req.body.year_released+"', '"+req.body.language_released+"')",
  (err,rows) => {
    if (!err) {
      res.send("Movie is added to the form");
    } else {
      console.log(err);
    }
 });
});

Open in new window

is this what you were looking for in the back end
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Hi Adil,

No ... not quite. When you click on the Edit button for each movie, you will need to send the Movie ID to the back-end, and the back-end script will need to query your database and then build the Edit Form. It will populate that form on the back end and then return that to the front-end to be dropped into the modal.

So, for each movie in your list, you will have an Edit button that looks something like this:

<button class='btn btn-danger editMovie' data-movieid=1>Edit</button>

You will also have a Modal form on your page that looks something like this:

<div class="modal fade" id="editMovieModal" tabindex="-1" role="dialog" aria-labelledby="editMovieModal" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel2">Updated Movie</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- the dynamic form content will go hee -->
            </div>
        </div>
    </div>
</div>

Open in new window

You'll notice that the modal has no content in it.

You will then have an AJAX call that looks something like this:

$('#movies').on('click', '.editMovie', function() {
    $( "#editMovieModal .modal-body" ).load( "youServerSideScriptAddress", { id: $(this).data('movieid') }, function() {
        $('#editMovieModal').modal();
    });
});

Open in new window

So, a user clicks on your Edit button, and the AJAX call above passes the ID to your server-side script. That script will query the database and generate the HTML for the edit form (<input type="text" name="???" value="???"> etc). It then returns that HTML to your page, and the popup modal-body is populated with the HTML. Then the Modal popup is shown with the populated form.

Author

Commented:
So basically I have to add the modal content with the Ajax

Author

Commented:
<div class="modal fade" id="exampleModal2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel2"
         aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel2">Updated Movie</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 id="updateForm">
                        <div class="form-group row">
                            <div class="col-sm-10">
                                <input type="hidden" class="form-control" id="movieId">
                            </div>
                        </div>

                        <label for="idmovielist" class="col-sm-2 col-form-label">ID</label>
                        <div class="col-sm-10">
                            <input value ="5" type="text" class="form-control" id="intNum">
                        </div>
                        <div class="form-group row">
                            <label for="name" class="col-sm-2 col-form-label">name</label>
                            <div class="col-sm-10">
                                <input value = "Jumanji" type="text" class="form-control" id="name">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="thumnail_path" class="col-sm-2 col-form-label">thumnail path</label>
                            <div class="col-sm-10">
                                <input value = "bilbibimfig" type="text" class="form-control" id="thumnail_path">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="description" class="col-sm-2 col-form-label">description</label>
                            <div class="col-sm-10">
                                <input  value = "action comdedy" type="text" class="form-control" id="description">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="year_released" class="col-sm-2 col-form-label">year released</label>
                            <div class="col-sm-10">
                                <input value = "1996" type="text" class="form-control" id="year_released">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="language_released" class="col-sm-2 col-form-label">language released</label>
                            <div class="col-sm-10">
                                <input  value="urdu" type="text" class="form-control" id="language_released">
                            </div>

                        </div>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button id="updateMovie" type="button" class="btn btn-primary" data-toggle="modal"
                                data-target=#exampleModal2>Update
                        </button>
                        <button id = "deleteMovie" type="buton" class="btn btn-primary" data-toggle="modal"
                        data-target=#exampleModal2>Delete
                      </button>
                    </form>

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

Open in new window

I have created an updated form alredy what do I do with this
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
In your HTML page, the modal does not need the edit form. It just needs to be empty, as per my previous code example:

<div class="modal-body">
    <!-- the dynamic form content will go here -->
</div>

When you click on the Edit button, your server needs to generate the edit form, so that it can be injected into the modal-body. The server will be passed the Movie ID, so you can query your Database using that (to get the correct info from the DB). When you click on Edit, your server-side script will need to generate something like this:

<form id="updateForm">
    <div class="form-group row">
        <div class="col-sm-10">
            <input type="hidden" class="form-control" id="movieId" value="value from DB">
        </div>
    </div>
    <div class="form-group row">
        <label for="name" class="col-sm-2 col-form-label">name</label>
        <div class="col-sm-10">
            <input value = "The value from your Database" type="text" class="form-control" id="name">
        </div>
    </div>
    ...

Open in new window

And that will be injected into the modal-body so that when you show your modal popup, it will contain the form with the correct information in it.

Author

Commented:
But what bout my update button
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
That's part of the form, so your server needs to generate that form ... all of it ... including the update button !

Click on the Edit button.
Make an AJAX POST request to the server (sending the ID)
The server generates the HTML form needed to edit the movie (the <form> tag, the <input> fields populate with values, the <button> elements)
That HTML gets put into the Modal
The Modal gets shown.

Author

Commented:
 $("#updateMovie").on("click", function(a) {
      a.preventDefault();
    let updatedata = {
      idmovielist: $($("#updateForm")[0].intNum).val(),
      name: $($("#updateForm")[0].name).val(),
      thumnail_path: $($("#updateForm")[0].thumnail_path).val(),
      description: $($("#updateForm")[0].description).val(),
      year_released: $($("#updateForm")[0].year_released).val(),
      language_released: $($("#updateForm")[0].language_released).val(),
    }

    $("#updateForm").trigger("reset");
    $("#updateForm").toggle();

    $.ajax({
      url: "http://localhost:3000/movielist/updateMovie/18",
      method: 'PUT',
      dataType: 'json',
      data: updatedata,
    }).always(function(data){
          console.log(data);
          renderMovieList();
  });
});

Open in new window

This button function above is used to execute the put method what do I do with this do I have to get rid of this
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
No. You still need that code to run the update (although it probably needs cleaning up a lot)

However, because you're now loading the Edit Form dynamically, you'll need to change the event binding. Currently you have this:

$("#updateMovie").on("click", function(a) {

If you've coded your page like I've shown you, then you'll need to do this instead:

$("#editMovieModal").on("click", "#updateMovie", function() {

I take it you've now got the form loading up into your modal popup. If not, I'd suggest you take a step back and get each part working properly before moving on to the next part. If you try and do everything at once, you'll end up getting confused and frustrated!

Author

Commented:
let updatedata = {
      idmovielist: $($("#updateForm")[0].intNum).val(),
      name: $($("#updateForm")[0].name).val(),
      thumnail_path: $($("#updateForm")[0].thumnail_path).val(),
      description: $($("#updateForm")[0].description).val(),
      year_released: $($("#updateForm")[0].year_released).val(),
      language_released: $($("#updateForm")[0].language_released).val(),
    }

    $("#updateForm").trigger("reset");
    $("#updateForm").toggle();

    $.ajax({
      url: "http://localhost:3000/movielist/updateMovie/18",
      method: 'PUT',
      dataType: 'json',
      data: updatedata,
    }).always(function(data){
          console.log(data);
          renderMovieList();
  });
});

Open in new window

is this what I put inside that function you gave me
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Yes, but like I said ... get the other part working first and then we can come back to the update bit. There's no point in looking at this if your form isn't even loading yet

Author

Commented:
$('#editMovieModal2').on('click','#updateMovie',function() {
    var movieId = $(this).data('movieid'); // get the Movie ID from the Edit button
    $( "#exampleModal2 .modal-body" ).load( "http://localhost:3000/movielist/updateMovie/7", { id: moveId }, function() {
        // now show your modal popup.
       $('#exampleModal2').modal()
       renderMovieList();
    });
});

Open in new window

this is what I got so far

Author

Commented:
yet when I click on edit no information is present on the forms
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
OK. We're clearly struggling trying to get the Edit Form from the server, so we'll take a slightly different, hopefully clearer approach. We'll keep the NodeJS app running as a clean RESTful API, and we'll handle the forms at the front end. Your NodeJS app will just need to serve the 5 API endpoints needed for your RESTful server. Those are:

GET /movies - Get a list of all movies
GET /movies/x - Get a single movie with an ID of x
PUT /movies/x - Update a single movie with an ID of x
POST /movies/x - Create a new movie
DELETE /movies/x - Delete a single movie with an ID of x

Here's a quick code sample of the NodeJS RESTful server. You'll notice that I've named the endpoints slightly differently to you. This gives it a more standard RESTful naming convention.

const express = require('express')
const mysql = require('mysql')
const bodyparser = require('body-parser')
const app = express()
const port = 3000

// Set up the Server
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({ extended: true }))

app.listen(port, () => {
  console.log('Web server listening on port ' + port)
})

// Connect to the DB
const conn = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'xxxxxx',
    database : 'movies',
})
 
conn.connect( (err) => {
    if (err) {
        console.error('Error connecting to DB: ' + err.stack)
        return;
    }

    console.log('Connected to DB');
})


// API v1
// Get a list of all Movies
app.get('/api/v1/movies/', (req, res) => {
    conn.query("SELECT id, name, description FROM movielist", (err, rows, fields) => {
        if (!err) {
            res.status(200).json({
                success: true,
                movies: rows,
            })
        } else {
            console.log(err)
        }
    });
});


// Get a single Movie
app.get('/api/v1/movies/:id', (req, res) => {
    const id = parseInt(req.params.id, 10);
    conn.query("SELECT id, name, description FROM movielist WHERE id = ? LIMIT 1", id, (err, rows, fields) => {
        if (!err) {
            res.status(200).json({
                success: true,
                movie: rows[0],
            })
        } else {
            console.log(err)
        }
    })
})


// Add a new Movie
app.post('/api/v1/movies/:id', (req, res) => {
    conn.query("INSERT INTO movielist (name, description) VALUES (?, ?)", [req.body.name, req.body.description], (err, rows, fields) => {
        if (!err) {
            res.status(200).json({
                success: true,
            })
        } else {
            console.log(err)
        }
    })
})


// Update an existing Movie
app.put('/api/v1/movies/:id', (req, res) => {
    const id = parseInt(req.params.id, 10);
    conn.query("UPDATE movielist SET name = ?, description = ? WHERE id = ? LIMIT 1", [req.body.name, req.body.description, id], (err, rows, fields) => {
        if (!err) {
            res.status(200).json({
                success: true,
            })
        } else {
            console.log(err)
        }
    })
})


// Delete an existing Movie
app.delete('/api/v1/movies/:id', (req, res) => {
    const id = parseInt(req.params.id, 10);
    conn.query("DELETE FROM movielist WHERE id = ? LIMIT 1", id, (err, rows, fields) => {
        if (!err) {
            res.status(200).json({
                success: true,
            })
        } else {
            console.log(err)
        }
    })
})

Open in new window

That's a simple RESTful server and you can fire that up and then fully test it using something like the POSTMAN software. In the example above, I'm just using a couple of fields for the database: id, name, description. I suggest you do the same to start with as it will make your likfe easier. You can always go back in and add more fields once you know everything is working OK.

Right, now that the server is working fine, we need to create the HTML for the front end. This page needs to contain a table to hold the full movie list. It also needs a Modal Popup with a form to allow you to Add/Edit a movie and a second Modal Popup to confirm a deletion. Take a look at the following. Again, for now it only contains a few fields to match the RESTful server - id, name, description.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>Chris Stanyon // EE - 29145242</title>

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
        <script src="movies.js"></script>    
    </head>
    <body>

        <div class="container">
            <div class="row">
                <div class="col">
                    <header><h1>Movies</h1></header>
                    <button id="addMovie" class="btn btn-primary">Add Movie</button>
                </div>
            </div>
            <div class="row mt-3">
                <div class="col">
                    <table class="table table-bordered table-hover">
                        <thead class="table-borderless">
                            <tr>
                                <th>ID</th><th>Name</th><th>Desc</th><th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="movies"></tbody>
                    </table>
                </div>
            </div>
        </div>



        <!-- Modal Popup for Editing / Adding a Movie -->
        <div class="modal fade" id="editMovieModal" tabindex="-1" role="dialog" aria-labelledby="editMovieModal" aria-hidden="true">
            <div class="modal-dialog" role="document">
               <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel2">Edit Movie</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 id="updateForm">
                            <div class="form-group row">
                                <label for="editMovieName" class="col-sm-2 col-form-label">Name</label>
                                <div class="col-sm-10">
                                    <input value="" type="text" class="form-control" name="name" id="editMovieName">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="editMovieDescription" class="col-sm-2 col-form-label">Description</label>
                                <div class="col-sm-10">
                                    <input value="" type="text" class="form-control" name="description" id="editMovieDescription">
                                </div>
                            </div>

                            <button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-success" id="updateMovie">Update</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal Popup for Deleting a Movie -->
        <div class="modal fade" id="deleteMovieModal" tabindex="-1" role="dialog" aria-labelledby="deleteMovieModal" aria-hidden="true">
            <div class="modal-dialog" role="document">
               <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel2">Delete Movie</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <p>Are you sure you want to delete this Movie?</p>
                        <button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-danger" id="deleteMovie">Delete</button>
                    </div>
                </div>
            </div>
        </div>

    </body>
</html>

Open in new window

You'll see that it's just simple HTML - a container for the movie data and 2 bootstrap modals - one for editing / adding a movie and one for confirming the deletion of a movie. You'll also see in the <head> element that I'm including a movies.js file. This is where all the Javascript will go that interacts with your HTML page and the the server. That movies.js file looks like this:

$(function() {
    RenderMovieList();

    // Show the Edit Movie popup
    $('#movies').on('click', '.editMovie', function() {
        $.get('http://localhost:3000/api/v1/movies/' + $(this).closest('tr').data('movieid'), function(data) {
            $('#updateMovie').data('movieid', data.movie.id);
            $('#editMovieName').val(data.movie.name);
            $('#editMovieDescription').val(data.movie.description);
            $('#editMovieModal').modal('show');
        });
    });

    // Show the Add Movie popup
    $('#addMovie').on('click', function() {
        $('#updateForm').trigger('reset');
        $('#updateMovie').data('movieid', 0);
        $('#editMovieModal').modal('show');
    });

    // Submit the Edit/Add Movie popup
    $('#updateMovie').click(function() {
        const method = $(this).data('movieid') === 0 ? 'post' : 'put';
        $.ajax({
            url : 'http://localhost:3000/api/v1/movies/' + $(this).data('movieid'),
            method : method,
            data : $('#updateForm').serialize(),
        })
        .done(function(data) {
            $('#editMovieModal').modal('hide');
            RenderMovieList();
        });
    });

    // Show the Delete Movie popup
    $('#movies').on('click', '.deleteMovie', function() {
        $('#deleteMovie').data('movieid', $(this).closest('tr').data('movieid'));
        $('#deleteMovieModal').modal('show');
    });

    // Delete the Movie
    $('#deleteMovie').click(function() {
        $.ajax({
            url : 'http://localhost:3000/api/v1/movies/' + $(this).data('movieid'),
            method : 'delete',
        }).done(function(data) {
            $('#deleteMovieModal').modal('hide');
            RenderMovieList();
        })
    });
});

function RenderMovieList() {
    $.get( "http://localhost:3000/api/v1/movies/", function( data ) {
        $('#movies').empty();
        $.each(data.movies, function(i, movie) {
            let rowText = `
            <tr data-movieid=${movie.id}>
                <td>${movie.id}</td>
                <td>${movie.name}</td>
                <td>${movie.description}</td>
                <td><button class='btn btn-danger deleteMovie'>Delete</button> <button class='btn btn-info editMovie'>Edit</button></td>
            </tr>`;
            $('#movies').append(rowText);
        });
    });
}

Open in new window

And that's it. You have 3 parts to your app - the NodeJS server (the RESTful API), the HTML page that the user sees, and the movies.js file that handles all the interaction.

I would strongly suggest you have a read through those files and try them out exactly as they are. It's important that you understand all the moving parts, and once you do, you can edit them to add more fields and functionality to your app.

Hope that makes more sense :)

Author

Commented:
would it be possible if you can use my code for an example because when I tried yours I did not see anything that pops up
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Not really. Your code is a little too messy to try and fix cleanly. That's why I provided you with a clean, concise working example.

Which part of my code is not working? I've tested it all and it works fine, so something else is going on. Did you try running it EXACTLY as I posted, or have you tried to edit it?

Make sure you run and test the Node server first. Fire it up and then make the API calls to it using something ilke POSTMAN. This will tell you straight away whether or not the Node REST API is working or not. If it is, move on to check the HTML. If it's not, fix that before moving on.

You need to take a logical approach to development. Trying to get everything working all at once will cause you problems.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial