skip to Main Content

Good day

I am trying to send a Ajax post request with jquery.
For this purpose I use a bootstrap modal to grab data and send to PostgreSQL DB.
Data is referred to rendered section using EJS.
So in the end i get the undefined value of POST request data.


i tag to trigger the modal

  <span data-toggle="tooltip" data-placement="bottom" title="Edit task">
      <a data-toggle="modal" data-target="#editTaskModal">
        <i class="editTask fas fa-pencil-alt" data-id="<%= task.id%>" data-description="<%= task.description%>"></i>
      </a>
    </span>
  </span>

The modal

<div class="modal fade" id="editTaskModal" tabindex="-1" aria-labelledby="editTaskModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form class="" action="/edit" method="post">
        <input type="hidden" id="editTaskId" name="id" value="" />
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Edit Task</h5>
        </div>
        <div class="modal-body">
          <div class="input-group">
            <div class="input-group-prepend">
            </div>
            <input autocomplete="off" id="editTaskDescription" name="taskDescription" class="form-control" aria-label="With textarea"></input>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="confirmEditTask btn btn-primary">Edit Task</button>
        </div>
      </form>
    </div>
  </div>
</div>

Jquery script to process the data

I grab the value of previous record and place in the modal input form to edit. Copy the id of item as well in order to match with database item and update.

$(document).on("click", '.editTask', function() {
    $("#editTaskDescription").val($(this).attr('data-description'));
    $("#editTaskId").val($(this).attr("data-id"));
    var id = $(this).attr("data-id");
    var url = '/edit/' + id;
    $(".confirmEditTask").on("click", function(event) {
      const newDescription = $("#editTaskDescription").val()
      alert(newDescription)
      if (!null) {
        $.ajax({
          type: "POST",
          url: url,
          data: newDescription,
          success: function(result) {
            $("#editTaskModal").modal('hide')
            console.log("editing task");
            window.location.href = '/'
          },
          error: function(err) {
            console.log(err);
          }
        })
      }
    })
  })
})

SQL query
In order to check what is the req.params.newDescription I log it and see that it is "undefined".

// Edit task by ID
app.post('/edit/:id', function(req, res) {
  console.log(req.params.newDescription);
    pool.query("UPDATE tasks SET description=$1 WHERE id=$2", [req.params.newDescription, req.params.id]);
    res.sendStatus(200);
})

Please advise how the Jquery Ajax POST request should pass the DATA to the server. Data type of "description" column is character varying. Am i facing issue with data type non compatibility?


2

Answers


  1. The data you’re passing into your ajax request is wrong. Build your object into a key value pair and pass it into the request. Here is an example. You can use encodeURIComponent() OR encodeURI()to escape any special characters and can find the doc here –

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

    var data = {"newDescription": $("#editTaskDescription").val()}
    
    Login or Signup to reply.
  2. you so close the data must just be an object of like dictionary key and then value, where the key is always text…. see below

    assuming the accepting endpoints name for its param is "newDescription"

    e.g.

      [HttpPost("edit/{id}")]
      public ActionResult Edit([FromUrl]string id,[FromBody] string newDescription)
      {
                
      }
    
    $(document).on("click", '.editTask', function() {
        $("#editTaskDescription").val($(this).attr('data-description'));
        $("#editTaskId").val($(this).attr("data-id"));
        var id = $(this).attr("data-id");
        var url = '/edit/' + id;
    
        $(".confirmEditTask").on("click", function(event) {
    
          const newDescription = $("#editTaskDescription").val()
    
          if (!null) {
            $.ajax({
              type: "POST",
              url: url,
              data: {"newDescription": newDescription },
              success: function(result) {
               
              },
              error: function(err) {
                console.log(err);
              }
            })
          }
        })
      })
    })
    

    e.g.

      [HttpPost()]
      public ActionResult Edit(int id, string name)
      {
                
      }
    

    then data would be

    var data = {"id": 232, "name": "SomeFancyName" },
    
      $.ajax({
              type: "POST",
              url: url,
              data: data,
              success: function(result) {
               
              },
              error: function(err) {
                console.log(err);
              }
            })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search