AJAX is the most Viable Rich Internet Application (RIA) technology ever. It is gaining tremendous industry speed and many tool kits and frameworks are coming out of it. But at the same time, AJAX has browser incompatibility and it is supported by JavaScript which is difficult to maintain and debug.
In the previous article, we have discussed the jQuery Ajax GET Example with Parameters, In this post, We will discuss How can I use JQuery to post JSON data.
How can I use JQuery to post JSON data?
For showing you I have created post rest for the testing purpose, below is the request and response of the service. I want to post JSON to the service and for that we can use below Ajax Code.
API Url: http://restapi.adequateshop.com/api/Tourist
Parameters
{
"tourist_name": "anuj",
"tourist_email": "anuj45@gmail.com",
"tourist_location": "Noida 63",
}
Response
{
"id": 17546,
"tourist_name": "anuj",
"tourist_email": "anuj45@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "Noida 63",
"createdat": "2022-01-30T05:04:13.1664327Z"
}
Ajax Post API Calling:
So now let’s look at an example of using Jquery Ajax function with the post. Specify the URL to which you want to make a request, then you use this URL option. Specify whether you want to issue a GET or a POST request.you want to issue a get request, you specify GET. If it is POST, then specify POST. For calling a function when the request completes successfully, we have a successful option in the Ajax method. If any error occurred in the request, then we have the error option.
Ajax function has two overloads, The first overload is one in which you can specify URL parameters separately, and then all the options that you want to include in the ajax request.
And then we have another overload version of the ajax request in which you just pass the JavaScript object and specify all the options, including the URL.
//getting values from control
var txtName = $("#txttourist_name").val();
var txtEmail = $("#txttourist_email").val();
var txtaddress = $("#txttourist_location").val();
var postobj = {};
postobj.tourist_name = txtName;
postobj.tourist_email = txtEmail;
postobj.tourist_location = txtaddress;
$.ajax({
url: 'http://restapi.adequateshop.com/api/Tourist',
method: 'POST', //HTTP POST
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(postobj), //sending data to the sever
success: function (data) {
debugger;
//getting response from server
alert("Saved successfully");
//Binding the newly created row into the database
var tablerow = "<tr>"
+ "<td>" + data.id + "</td>"
+ "<td>" + "<img style='width:20px;border-radius:50px' src=" + data.tourist_profilepicture + ">" + data.tourist_name + "</td>"
+ "<td>" + data.tourist_email + "</td>"
+ "<td>" + data.tourist_location + "</td>"
+ "</tr>";
$("#tblbody").append(tablerow);
$("#txttourist_name").val('');
$("#txttourist_email").val('');
$("#txttourist_location").val('');
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
})
In our example we use the second overloaded version, we are going to pass a JavaScript object, and specify all the options.
So the first parameter is the URL to which we want to issue a POST request I’m going to use the URL option of ajax request for that.
After that we need to specify the type of HTTP request i.e we want to issue a get or a post request, and to do that, I’m going to use the method option of the ajax function. as we want to issue a POST request I have specified it POST.
And then we want to specify the data that we want to pass to the rest API server. For that, I’m going to use the data option of the Ajax method.
we also need to specify the type of data that we are going to get back from the server response when calling success.
Now to specify we are using the datatype option, I have set datatype to JSON i.e we are specifying that we get JSON data back from the server.
Now, once the request is completed successfully, we want to handle that response and then want to display that information in the HTML.
that means on the success of the ajax request, we will populate the HTML table.
So we have specified the URL, specified the JSON data that we want to post to the server also mention HTTP request type i.e we want to issue a get a post request. As we know that in this post ,we are taking about ajax post so we are using the post method.
Thank you for reading and have a great day if you have a question please comment.
jQuery Ajax Post json Example
Now let’s take and real-time example of ajax post request.I have created a form for making the entry in the database table.
On button click, I’m calling the POST api using ajax for creating the entry in the database. On successful call of the Api, we are appending the newly added row in the table
<!DOCTYPE html>
<html>
<head>
<title> Ajax POST request with parameters example </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h1> Ajax POST request with parameters example </h1>
<form id="addcustomerform">
<div class="form-group">
<label>Name:</label>
<input type="text" name="txttourist_name" id="txttourist_name" class="form-control" value="" required="">
</div>
<div class="form-group">
<label>Email:</label>
<input type="email" name="txttourist_email" id="txttourist_email" class="form-control" value="" required="">
</div>
<div class="form-group">
<label>Location:</label>
<textarea class="form-control" name="txttourist_location" id="txttourist_location"></textarea>
</div>
<button type="submit" id="btnaddtraveler" class="btn btn-primary save-btn">add Traveler</button>
<fieldset>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>TouristName</th>
<th>TouristEmail</th>
<th>Location</th>
</tr>
</thead>
<tbody id="tblbody"></tbody>
</table>
</fieldset>
</form>
<br />
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
GetallTourist()
});
//add traveler
$("#btnaddtraveler").on("click", function (e) {
e.preventDefault();//prevent default form submission on button click
//getting values from control
var txtName = $("#txttourist_name").val();
var txtEmail = $("#txttourist_email").val();
var txtaddress = $("#txttourist_location").val();
var postobj = {};
postobj.tourist_name = txtName;
postobj.tourist_email = txtEmail;
postobj.tourist_location = txtaddress;
$.ajax({
url: 'http://restapi.adequateshop.com/api/Tourist',
method: 'POST', //HTTP POST
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(postobj), //sending data to the sever
success: function (data) {
debugger;
//getting response from server
alert("Saved successfully");
//Binding the newly created row into the database
var tablerow = "<tr>"
+ "<td>" + data.id + "</td>"
+ "<td>" + "<img style='width:20px;border-radius:50px' src=" + data.tourist_profilepicture + ">" + data.tourist_name + "</td>"
+ "<td>" + data.tourist_email + "</td>"
+ "<td>" + data.tourist_location + "</td>"
+ "</tr>";
$("#tblbody").append(tablerow);
$("#txttourist_name").val('');
$("#txttourist_email").val('');
$("#txttourist_location").val('');
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
})
});
//Get All allTourist
function GetallTourist() {
$.ajax({
url: 'http://restapi.adequateshop.com/api/Tourist',
method: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
debugger;
if (result != null && result.data) {
for (var i = 0; i < result.data.length; i++) {
var tablerow = "<tr>"
+ "<td>" + result.data[i].id + "</td>"
+ "<td>" + "<img style='width:20px;border-radius:50px' src=" + result.data[i].tourist_profilepicture + ">" + result.data[i].tourist_name + "</td>"
+ "<td>" + result.data[i].tourist_email + "</td>"
+ "<td>" + result.data[i].tourist_location + "</td>"
+ "</tr>";
$("#tblbody").append(tablerow);
}
}
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
})
}
</script>
*Thank you so much if you have a question please comment
Asynchronous web pages
In a traditional web model, when a web browser requests a web page and the web server responds to it as the requested web page. As soon as the page is loaded in your browser, the connection between the web browser and the webserver gets terminated.
and then a request is made for another page and the same process is followed back.
Whenever a request is sent by the user for a page, the existing page has to be reloaded to show the new information, only after the page is reloaded, new information or a new page will be shown. Sometimes this process is annoying for the user experience.
If you are making a big web application like youtube, then there will be a lot of web elements in it. In such a situation, if the page is reloaded repeatedly while interacting with every small element, then your web application will create a bad user experience.
For example, you are watching a video on youtube, you like this video and you click on the like button to like it, then if you click on the like button, the whole page is reloaded so that you do not want to like |
Asynchronous web pages are such web pages, some elements of which do not require the entire page to be loaded to be updated or loaded. The new content is dynamically loaded on the web page. Processing in such pages is done in the background.
User does not interface with this processing, how this happens, you will be told further in the Working of AJAX section.
The post How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example appeared first on Software Development | Programming Tutorials.
Read More Articles
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- Remove last TD before append to element in dynamic content
- Retrieving value using get() with coffeescript and Ruby on Rails
- jQuery implementation with Cargo Collective site
- setting checked state using attr() vs using prop()
- Copy to Clipboard element's text value using jQuery
- jquery css dock menu not working in ASP.NET masterpage
- How to programmatically block/execute javascript blocks?
- Adding changing text onclick to JavaScript gallery
- what is means of "this.get = function(aUrl, aCallback) {" in js?
- jQuery - catch <input type="button" onclick location based on class
- targeting a link with a class inside of an <li> with jquery
- Question on Javascript function calling
- Jquery ReferenceError: invalid assignment left-hand side
- how to use the $ char in sublimetext snippets?
- Reloading Google Map on Form Submit
- Return single number of divs not just their total
- How to reset scrollTop() div positioning when scrolling back up?
- JQuery Client Failing outside localhost
- Generate unique numbers
- Centering a floating div with jQuery
- Where is the jQuery API on `$.`?
- sending div content per mail
- Internet Explorer Showing Old Values For Local Storage
- Stop jQuery toggle from sliding content in
- Jquery animation happening on multiple divs
- e.keycode is undefined in firefox 19.0.2 ,chrome 25.0.1364.172 m,IE 8
- Can browsers react to Set-Cookie specified in headers in an XSS jquery.getJSON() request?
- Empty text box validation jQuery
- Placed unnecessary repetitive reference code for Jquery/JavaScript files in order to make jquery Validation plugin work
- How to check if coords are within a radius in km?
- While using flexbox, how can i make 3 buttons which are in flex column slide out left into view on hover?
- Reading JSON data from Google Geocoding API with jQuery
- Updating Html.Dropdownlists using JQuery
- Javascript function not reaching other function?
- Animation trigged in any Iphone browser when its not supposed to be
- Uncaught SyntaxError: Unexpected token ILLEGAL and SyntaxError: unterminated string literal
- Clone row and remove elements then re-add
- Running jQuery once body has loaded
- Set top.location and open new tab?
- Remember if user closed div
- Resize an image after cropping
- Pass GET variables and go to jQuery tab
- jQuery contains from input text
- Kendo Editor - Javascript function call on dynamically generated HTML elements
- Toggle class/background on current selection (jquery)
- Jquery detect element type in if
- Uncaught RangeError: Maximum call stack size exceeded - can't find recursion
- Remove null elements from array jquery
- share the same php function if `all years` option is selected
- jQuery, stopping clicking during animations
- Jquery ajax when
- jQuery: how to put a mouseover event on tag select generated by ajax
- Prevent jquery fadeIn many times
- how i can count the element who have the class "goo"
- Javascript write to local file from local file
- Dynamically synchronize scolling between two divs using jQuery draggable
- Center on viewport - a fixed height a width div VERTICALLY using either js or CSS method
- using jquery to select an option in a select based on a user-defined variable
- How to set a function to work only if i have not click Delete Button.?
- Setting the mouseup event inside a class
- javascript jquery response HTML into a div do not retrieve all HTML
- jQuery find inside selector
- @Html.RenderPartial vs jQuery.load()
- What is the jQuery syntax for saying "any element"?
- How to separate json array and put it on a html table?
- jquery accordion not working with contents received from AJAX
- Counting paragraphs with pagination
- Looking for a better way to show/hide an element
- Passing JavaScript to Session variable
- How to select children from the list of matched elements?
- renderDataTable Select all cells containing value > 10 and highlight
- Reading language from source
- Isotope not displaying items in firefox 4
- jquery single click not working properly
- How does Javascript differentiate between Json Objects and String?
- How to get text that uses special characters in textarea?
- javascript on page can i store to allow javascript in a cookie
- Way too much extra padding on bottom of page
- How to replace part of string with array items in jQuery?
- change background color by iterating through array
- How do you create an array from a delimited string?
- jquery change textarea to read write based on select
- Doesn't search attribute on JQuery
- Add text to '.foo' if parent container also contains '.foo2'
- Return false does not stop form submit
- Time Interval seconds run fast on tab changed Javascript
- Stopping people from getting around my form validation by navigating elsewhere
- Twitter bootstrap carousel with one big item and 5 small thumbnails inside it
- Sweet Alert and ajax calls based on id on php while loop
- jQuery Toggle function conflicts with Mouseup
- jQuery AJAX solution inside each() loop
- PhoneGap / Cordova "click" working in browser, but not working on Developer App?
- jQuery Datepicker how to dynamically add IDs to input field
- I can't access all the elements in an array inside an object
- JQuery slide up and down
- bind a jquery plugin to ajax loaded content
- On click should not work on child
- pause/resume jquery .animate()?
- Jquery $.ajax not working for the second time
- Stopping unnecessary button form submits html js
- Increment and Decrement by 1 value when click on + and - button
- Adding metatags by javascript cant be seen in source code
- Need these AJAX calls to happen after the previous one is finished
- How to run a jQuery Function in smaller width?
- splitting a dynamic string to store in separate variable
- unable to apply for an array of <a> link
- AngularJS Data Driven dropdown with ng-repeat
- jQuery 1.3.2 append() fails in IE7 and IE8
- Prevent jQuery animation from queueing
- Two different POST requests being made to the same route at the same time
- Display tags in CSS interrupting with Jquery hide/show
- Flex vs HTML/jQuery
- How can I get a data-variable from each element with a class?
- Updating session using AJAX
- Get value from input
- How to set an object param name with a string in JavaScript?
- What is the most semantically correct way to listen for a click event using jQuery
- Alternating between single and double quotes indefinitely
- Get all values from td of a row if checkbox is checked
- How to get specific value from iTunes API using Javascript
- jquery - a href link clickable in javascript based bootstrap table
- blueimg file upload plugin response codes
- jQuery Selectors - selecting the right <h4> tag
- jQuery mouseout doesn't count link as part of the DIV?
- Issue with jQuery and Telerik?
- Detect scroll in mobile Chrome
- Javascript tabbed data, reveal on click
- Why is a class not being added to my element?
- StickorStay JQuery function, error
- jQuery multiple events occuring at the same time
- jQuery - Bold all the words in a query
- Passing variable values from Php to Javascript
- Dynamic result set having problems with jQuery tablesorter
- Access text of a span in div via jQuery
- Custom jQuery Tooltip: How to position it?
- How make data bind with angularJS using img element
- Bootstrap Tooltip showing at top left of page
- How can I get a value from MySQL using jQuery on Frontend
- Using <td> instead of <tr> to show/hide a row
- Problems with Directions API in Google Maps V3 and jQuery
- How to find any string in a page using jQuery
- How to make a <td> element look like a nested <tr>
- How to push name value objects into an array?
- How to rename similarly-named variables in a for loop
- Jquery save html with value in file
- jQuery toggleSlide: show/hide block
- jquery ui slider pips change percentage steps
- Generate bottom scroll on a live chat using jquery or js
- height and width of background picture adapt to each screen size
- How to function fire up again?