0

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?


3
  • Pass the data as key value pair like so - var data = {param:$("#editTaskDescription").val()} . After you've built your object pass it into the ajax request. Jquery will serialize this object for you. you can escape any special characters using encodeURIComponent() OR encodeURI() - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 15, 2020 at 17:27
  • @JoeZ, Thank you for your comments. It worked, but now it only takes the digits as input, but not letters. If I try to add letters it gives me an error "Json syntax error". Have and idea what to do with that?. Correction: Everything works just fine. Thanks a lot Commented Sep 15, 2020 at 19:46
  • glad you got it working! I have transferred this to the answers section to bring more clarity to this and make sure it will be visible as a solution to anybody else having a similar problem. If my answer worked for you please accept it. Commented Sep 15, 2020 at 19:55

2 Answers 2

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()}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.