Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a Post request with request body from HTML form

I am working on a html page which is supposed to submit a post request with request body to my server like below

<html>
    <head>Customer app</head>
    <body>
         <div> 
             <table> 
                 <tr>
                     <td>Customer Id :</td> 
                     <td>
                         <form name="submitform" method="post">
                             <input type="text" id="customerId" name="customerId"/>
                             <input type="submit" value="Submit">
                         </form>
                     </td>
                 </tr>
             </table>
        </div>
    </body>

    <script>
    $(document).ready(function(){
        $("#submitform").click(function(e)
        {
            var MyForm = JSON.stringify($("#customerId").serializeJSON());
            console.log(MyForm);
            $.ajax({
                url : "http://localhost:7777/ola-drive/customer/ride",
                type: "POST",
                data : MyForm,

            });
            e.preventDefault(); //STOP default action

        });
    });
    </script>
</html>

It does not work as expected throwing 404 Not Found getting redirected to http://localhost:7777/customerapp.html. But form data corresponding to the request submission seems to be correct.

Can someone help me fix the issue with my html code submit POST request redirection ?

like image 540
Aarish Ramesh Avatar asked Aug 12 '26 23:08

Aarish Ramesh


1 Answers

Your issue is in this line:

$("#submitform").click(function(e)

Your form does not have an id but a name, so you can write:

$('[name="submitform"]').click(function(e)

That is the reason because your form is giving you a redirection error.

$('[name="submitform"]').click(function (e) {
    e.preventDefault(); 
    $.ajax({
        url: "http://localhost:7777/ola-drive/customer/ride",
        type: "POST",
        data: {"customerId": $("#customerId").val()},
        success: function (result) {
            //do somthing here
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div>
    <table>
        <tr>
            <td>Customer Id :</td>
            <td>
                <form name="submitform" method="post">
                    <input type="text" id="customerId" name="customerId"/>
                    <input type="submit" value="Submit">
                </form>
            </td></tr>
    </table>
</div>
like image 66
gaetanoM Avatar answered Aug 14 '26 12:08

gaetanoM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!