Home > other >  Ajax Post request body returns undefined
Ajax Post request body returns undefined

Time:04-20

I am trying to send some data to backend using ajax post request. Like this

    $.ajax({
    url: "/aa",
    dataType: 'text',
    type: 'post',
    contentType: 'application/x-www-form-urlencoded',
    data: input.value,
    success: function (result) {
        console.log("Success", input.value);
    },
    error: function (data) {
        console.log(data);
    }
});

but i when i want to print my bodys data like this i recieve undefined

console.log(requ.body.data);

i also use body parser in the backend

app.use(bodyParser.raw())

why it returns undefined?

CodePudding user response:

this works, please tell me if you want me to create a fiddle

Controller:

[HttpPost]
public string Index900(string theValue)
{
    try
    {
        throw new Exception("this is the Value"   theValue);
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

public ActionResult Index()
{
    return View();
}        

View:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
        $(function () {
            $("#theBtn").click(function () {
                var theValue = $("#theInput").val();
                $.ajax({
                    url: "/Home/Index900",                          //changed this
                    dataType: 'text',
                    type: 'post',
                    contentType: 'application/json',                //changed this
                    data: JSON.stringify({ theValue: theValue }),   //changed this
                    success: function (result) {
                        //console.log("Success", input.value);      //changed this
                        alert(result);
                    },
                    error: function (data) {                        //changed this
                        //console.log(data);                        //changed this
                        alert("error...")
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div>
        <input type="button" id="theBtn" value="Click to start ajax" />
        <input type="text" id="theInput" value="Some Value" />
    </div>
</body>
</html>

CodePudding user response:

I think you need to change, in the console log, input.value for result

  • Related