If you are working with Restful API’s and you must need to send a JSON input response via web project, especially for Node projects. This post helps you to create a JSON input string using JavaScript. It's very useful, converting Data objects to JSON data format implemented with $.toJSON Jquery plugin.
Download Script Live Demo
JavaScript
Contains javascipt code. $("#form").submit(function(){}- delete_button is the ID name of form tag. Using element.val() calling form text input values.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="jquery.json-2.2.js"></script>
<script src="GetPostAjax.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#form").submit(function(e){
e.preventDefault();
var username,email,password,gender;
username=$("#username").val();
email=$("#email").val();
password=$("#username").val();
gender=$("#gender").val();
if(username.length>0 && email.length>0 && password.length>0 && gender.length>0)
{
//Creating Objects
var request = new Object();
var userDetails = new Object();
var user = new Object();
var websites=new Array();
user.name=username;
user.email=email;
user.password=password;
user.gender=gender;
//Array Push
if(website1.length>0)
websites.push(website1);
if(website2.length>0)
websites.push(website2);
if(website3.length>0)
websites.push(website3);
user.websites=websites;
userDetails.user = user;
request.userDetails = userDetails;
var jsonfy = $.toJSON(request);
// Encodes special characters
var encodedata = 'jsondata='+encodeURIComponent(jsonfy);
//Ajax Call
var url='website API URL';
post_data(url,encodedata, function(data) {
alert("Success");
});
}
});
});
</script">
<script src="jquery.json-2.2.js"></script>
<script src="GetPostAjax.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#form").submit(function(e){
e.preventDefault();
var username,email,password,gender;
username=$("#username").val();
email=$("#email").val();
password=$("#username").val();
gender=$("#gender").val();
if(username.length>0 && email.length>0 && password.length>0 && gender.length>0)
{
//Creating Objects
var request = new Object();
var userDetails = new Object();
var user = new Object();
var websites=new Array();
user.name=username;
user.email=email;
user.password=password;
user.gender=gender;
//Array Push
if(website1.length>0)
websites.push(website1);
if(website2.length>0)
websites.push(website2);
if(website3.length>0)
websites.push(website3);
user.websites=websites;
userDetails.user = user;
request.userDetails = userDetails;
var jsonfy = $.toJSON(request);
// Encodes special characters
var encodedata = 'jsondata='+encodeURIComponent(jsonfy);
//Ajax Call
var url='website API URL';
post_data(url,encodedata, function(data) {
alert("Success");
});
}
});
});
</script">
HTML Code
<form method='post' action='' id='form'>
Name
<input type='text' name='username' id='username' />
Email
<input type='text' name='email' id='email' />
Password
<input type='text' name='password' id='password' />
Gender
<select name='gender' id='gender'><option value='male'>Male</option><option value='female'>Female</option></select>
Websites
<input type='text' id='website1' />
<input type='text' id='website2' />
<input type='text' id='website3' />
<input type='submit' id='submit'/>
</form>
Name
<input type='text' name='username' id='username' />
<input type='text' name='email' id='email' />
Password
<input type='text' name='password' id='password' />
Gender
<select name='gender' id='gender'><option value='male'>Male</option><option value='female'>Female</option></select>
Websites
<input type='text' id='website1' />
<input type='text' id='website2' />
<input type='text' id='website3' />
<input type='submit' id='submit'/>
</form>
JSON Output
{
"userDetails":{
"user":{
"name":"Srinivas Tamada",
"email":"[email protected]",
"password":"Srinivas Tamada",
"gender":"male",
"websites":["www.9lessons.info","www.egglabs.in","www.oauthlogin.com"]
}
}
}
"userDetails":{
"user":{
"name":"Srinivas Tamada",
"email":"[email protected]",
"password":"Srinivas Tamada",
"gender":"male",
"websites":["www.9lessons.info","www.egglabs.in","www.oauthlogin.com"]
}
}
}
JSON Encoded
Encodes special characters. it encodes the following characters: , / ? : @ & = + $ #
jsondata=%7B%22userDetails%22%3A%7B%22user%22%3A%7B%22name%22%3A%22Srinivas%20Tamada%22%2C%22email%22%3A%22srinivas%409lessons.info%22%2C%22password%22%3A%22Srinivas%20Tamada%22%2C%22gender%22%3A%22male%22%2C%22websites%22%3A%5B%22www.9lessons.info%22%2C%22www.egglabs.in%22%2C%22www.oauthlogin.com%22%5D%7D%7D%7D
GetPostAjax.js
Jquery ajax method.
function post_data(url,encodedata, success){
$.ajax({
type:"POST",
url:url,
data :encodedata,
dataType:"json",
restful:true,
contentType: 'application/json',
cache:false,
timeout:20000,
async:true,
beforeSend :function(data) { },
success:function(data){
success.call(this, data);
},
error:function(data){
alert("Error In Connecting");
}
});
}
$.ajax({
type:"POST",
url:url,
data :encodedata,
dataType:"json",
restful:true,
contentType: 'application/json',
cache:false,
timeout:20000,
async:true,
beforeSend :function(data) { },
success:function(data){
success.call(this, data);
},
error:function(data){
alert("Error In Connecting");
}
});
}
I;m so loving this
ReplyDeleteGreat! for object creation as you can see object
ReplyDeletevar user = new Object(); instead of this you can also use direct method as var user= {} ;
Very nice post! Thanks!!
ReplyDeleteGood Article :)
ReplyDeletegreat script
ReplyDeletethks
ReplyDeleteNice one ;)
ReplyDeleteNice post! Thank you :)
ReplyDeletevery nice, too much helpful for us..:)
ReplyDeletegood point :)
ReplyDeletegood one, it is very helpful, :)
ReplyDeletelove it this tutorial... thank you for sharing..
ReplyDeleteVery clear tutorial , great!
ReplyDeleteGood one Bro..
ReplyDeleteThanks Man! Keep it up.GOD bless you!
ReplyDeletenice article, but you can add some thing more for advance viewer.
ReplyDeleteI love the way you present.
add some sort of OOP concept.
Nice example, but can you add a more complex task i.e: Contact.Address.City? o something like that
ReplyDeleteThe Link to download the script seems to be broken. I tried Chrome and IE10
ReplyDeleteThanks!
WBR
Why use a third party plugin for something that's already available by the browsers?
ReplyDeleteUse JSON.stringify(value[, replacer [, space]])
http://www.json.org/js.html
@Anonymous
ReplyDeleteNot all browsers have native JSON support.
IE8+
Firefox 3.1+
Safari 4.0.3+
Opera 10.5+
nice article,
ReplyDeleteGreat article, thanks for sharing
ReplyDeleteA quick notes on your scripts...
ReplyDeleteI would cut down some of your writing on how you instantiate your variables, objects and array.
var request = new Object();
var userDetails = new Object();
var user = new Object();
var websites=new Array();
__BECOMES__
var request = {},
userDetails = {},
users = {},
websites = [];
Cleaner, less code.
Best Regards,
Dan DiGangi
@ddigangi
Good Work Srinivas..!!
ReplyDeleteFantastic post. This JavaScript is very helpful for me. good one, it is very useful..
ReplyDeleteThis is such a Great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free
ReplyDeleteNice stuff.........!!!!!!!!!!!
ReplyDeleteHi srinivas,
ReplyDeletei am a continuous follower of your all post. in this post i have seen "website API URL" . which is not defined, how can i defined this? can i done this on localhost? if yes, then how i fetch jsonData in ajaxrequest page which i am using this as a website API URL.
Anyone here tests this javascript? I would love to use them for some special cases.
ReplyDeleteVery nice and useful
ReplyDeleteI can not stop reading this. And 'so fresh, so full of information, I do not know. I'm glad that people actually write the smart way to show the different sides of him.
ReplyDeleteI feel strongly about it and love learning more on this topic.
ReplyDelete