To use the $.post() shorthand method for AJAX POST requests in jQuery, follow these steps:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
function postData() {
var data = {
name: "John Doe",
email: "[email protected]"
};
$.post("https://example.com/api/endpoint", data, function(response) {
console.log(response);
// Do something with the response
});
}
In the example above, we created an object data
containing the data to be sent in the POST request. We then call the $.post() method with three parameters:
"https://example.com/api/endpoint"
in this case).response
parameter in the callback function contains the response from the server.Call the postData()
function whenever you want to initiate the POST request. For example, you can bind it to a button click event:
<button onclick="postData()">Send POST Request</button>
That's it! Now, when the button is clicked, the postData()
function will be called and the AJAX POST request will be made using the $.post() shorthand method in jQuery. The response from the server will be logged to the console, and you can modify the callback function to handle the response as needed.