If you're tired of constantly writing out the $.ajax syntax for ajax calls, this code snippet could be just what you need.
Remember: It's crucial to understand how JavaScript works asynchronously, as the code you currently have might not function properly.
This code offers some additional functionality:
1) Set URL and methods dynamically
2) Perform various actions like GET, POST, PUT, PATCH, and DELETE using the getData() function
The getData() function requires two parameters, with an optional third parameter if you need to send data to the server.
getData(URL, Method, Data if applicable)
$(document).ready(async () => {
function getData(url, method, data = {}) {
return $.ajax({
method,
url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
});
}
// getData(URL, Method, Data)
// await getData('https://jsonplaceholder.typicode.com/posts/1', 'PATCH', {title: "new post"})
// await getData('https://jsonplaceholder.typicode.com/posts/1', 'DELETE')
// await getData('https://jsonplaceholder.typicode.com/posts', 'POST', {
// userId: Math.floor(Math.random() * 1000),
// title: "New Post",
// body: "This is my new post"
// })
var getapidata = await getData('https://jsonplaceholder.typicode.com/posts/1', 'GET')
console.log(getapidata)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Thank you for listening!