0

I'm having an issue posting data. First, I tried using the shorthand $.post and got a 415 response. Some other posts on this site recommended using the $.ajax method instead and setting some headers. I did that and when I use the $.ajax method, the data seems to not pass to the server because the method on the backend breaks and says there is no data with that id, which is not true. Below you can see both methods. The shorthand post is currently commented out.

$(".Set_set").click(function () {

        let setID = $(this).attr("data-id");
        $.ajax({
            method: "POST",
            url: "https://localhost:44327/workout/addRep",
            data: { id: setID },
            dataType: "json",
            headers: {
                "Content-Type": "application/json",
            },
            success: function (data, status, jqxhr) {
                console.log(data);
                console.log(status);
            }
            })


           /* 
            $.post("https://localhost:44327/workout/addRep", 
              { id: setID }, function (data) {
                console.log(data)
            })

 */

    }
    )

})

When I use the $.ajax method, the headers section in the browser will say 'id=3' under the 'Request Payload" subsection.

When I use the $.post method, the 'Request Payload' section is not there. Instead there is a "Form Data" section and it will show "id: 3"

Here is the backend code if it helps:

[HttpPost]
    public IActionResult addRep([FromBody]int id)
    {
        //id is the setid

        ExerciseSet exerciseSet = context.Exercise_Sets.Where(c => c.ID == id).Single();



        return Ok(exerciseSet);
    }
QHafeez
  • 197
  • 1
  • 4
  • 14

1 Answers1

0

$.ajax({
            method: "POST",
            url: "https://localhost:44327/workout/addRep",
            data:JSON.stringify({ id: setID }) ,
            dataType: "json",
            success: function (data, status, jqxhr) {
                console.log(data);
                console.log(status);
            }
            })
            
    //OR  
    
    $.ajax({
            method: "POST",
            url: "https://localhost:44327/workout/addRep?id="+setID,
            dataType: "json",
            success: function (data, status, jqxhr) {
                console.log(data);
                console.log(status);
            }
            })
            
            
Nijin P J
  • 1,302
  • 1
  • 9
  • 15