How to send json data in jquery ajax for restful web services

advertisements

I am sending the json format data in jquery ajax for restful web services but It is not sending. I am new in web technology, so please help me. I write the script for sending the JSON data using following link how to pass JSON data to restful web services through ajax and also how to get JSON data?

My javascript code is

<script type="text/javascript">
 $(document).ready(function(){
     $('#btnBooking').click(function(){
             var serviceCategory=document.getElementById("services").value;
             var availDate=document.getElementById("scheduledDate").value;
             var custName=document.getElementById("userName").value;
             var custMobile=document.getElementById("userContactNumber").value;
             var custEmail=document.getElementById("addressemailId").value;
             var custAddress=document.getElementById("address1").value;
             var JSONObject= {"serviceCategory":serviceCategory, "availDate":availDate, "custName":custName, "custMobile":custMobile, "custEmail":custEmail, "custAddress":custAddress};
             var jsonData = JSON.stringify( JSONObject );
             $.ajax({
                 url: "http://localhost:8080/HomeServiceProvider/rest/booking/saveBookingDetails",
                 type: "POST",
                 dataType: "json",
                 data: jsonData,
                 contentType: "application/json",
                 success: function(response){
                    alert(JSON.stringify(response));
                 },
                 error: function(err){
                    alert(JSON.stringify(err));
                 }
            });
     });
}); 

</script>

My Html code is

<form class="form-horizontal" id="scheduleLaterForm" name="scheduleLaterForm" action="#" method="post">
    <div class="col-lg-8">
        <div class="alert alert-danger alert-dismissable" style="display: none;" id="errorMessageDiv">Error
                Message Goes Here</div>
        <div class="form-group">
                    <label class="col-lg-3 control-label">Name:<font style="color: red;">*</font></label>
                    <div class="col-lg-9">
                        <input class="form-control" id="userName" name="userName" placeholder="Full Name" value="" type="text">
                    </div>
        </div>                          

        <div class="form-group">
            <label class="col-lg-3 control-label">Services:</label>
            <div class="col-lg-9">
                <select class="form-control" id="services" name="subService">
                    <option>Select Service</option>
                    <option value="1">Carpenter</option>
                    <option value="2">Mobile SIM services</option>
                </select>
            </div>
        </div>                                  

        <div class="form-group">
            <label for="schedule-tme" class="col-lg-3 control-label">Schedule Date:<font style="color: red;">*</font></label>
            <div class="col-lg-9">
                <div class="input-group date form_datetime" data-date="dd-M-yyyy">
                    <input placeholder="Choose Date" class="form-control" value="" onchange="timeValidate()" id="scheduledDate" name="scheduledDate" readonly="readonly" type="text"> <span class="input-group-addon"> <span class="glyphicon glyphicon-th calender-click"></span></span>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">Address:<font style="color: red;">*</font></label>
            <div class="col-lg-9">
                <input class="form-control" name="address1" id="address1" placeholder="Full address" value="" type="text">
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">City:</label>
            <div class="col-lg-9">
                <input class="form-control" id="" value="Bangalore" name="" placeholder="City Name" readonly="readonly" type="text">
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">Mobile:<font style="color: red;">*</font></label>
            <div class="col-lg-9">
                <input class="form-control" id="userContactNumber" name="userContactNumber" placeholder="Mobile Number" onkeypress="enableKeys(event);" maxlength="10" type="text">
            </div>
        </div>

        <div class="form-group">
                <label class="col-lg-3 control-label">Email:<font style="color: red;">*</font></label>
                <div class="col-lg-9">
                <input class="form-control" name="addressemailId" id="addressemailId" placeholder="[email protected]" value="" type="text">                                       

                </div>
        </div>

        <div class="form-group marg-bot-45">
            <label class="col-lg-3 control-label"></label>
            <div class="col-lg-9">
                <a href="index.html" class="btn btn-info"  id="btnBooking">Confirm Booking&nbsp;<span class="glyphicon glyphicon-ok"></span></a>
            </div>
        </div>
    </div>
</form>

Booking.java

import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * Booking generated by hbm2java
 */
@Entity
@Table(name = "booking", catalog = "service4homes")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Booking implements java.io.Serializable {

    private Integer BId;
    private ServiceProviderStatus serviceProviderStatus;
    private ServiceCategory serviceCategory;
    private Date availDate;
    private String custName;
    private String custMobile;
    private String custEmail;
    private String custAddress;
    private Set<Allocation> allocations = new HashSet<Allocation>(0);
    private Set<SuperAdmin> superAdmins = new HashSet<SuperAdmin>(0);

    public Booking() {
    }

    public Booking(ServiceProviderStatus serviceProviderStatus,
            Customer customer, ServiceCategory serviceCategory, Date availDate,
            String custEmail) {
        this.serviceProviderStatus = serviceProviderStatus;
        this.serviceCategory = serviceCategory;
        this.availDate = availDate;
        this.custEmail = custEmail;
    }

    public Booking(ServiceProviderStatus serviceProviderStatus,
            Customer customer, ServiceCategory serviceCategory, Date availDate,
            String custName, String custMobile, String custEmail,
            String custAddress, Set<Allocation> allocations,
            Set<SuperAdmin> superAdmins) {
        this.serviceProviderStatus = serviceProviderStatus;
        this.serviceCategory = serviceCategory;
        this.availDate = availDate;
        this.custName = custName;
        this.custMobile = custMobile;
        this.custEmail = custEmail;
        this.custAddress = custAddress;
        this.allocations = allocations;
        this.superAdmins = superAdmins;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "b_id", unique = true, nullable = false)
    public Integer getBId() {
        return this.BId;
    }

    public void setBId(Integer BId) {
        this.BId = BId;
    }

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "sps_id", nullable = false)
    @JsonIgnore
    public ServiceProviderStatus getServiceProviderStatus() {
        return this.serviceProviderStatus;
    }

    public void setServiceProviderStatus(
            ServiceProviderStatus serviceProviderStatus) {
        this.serviceProviderStatus = serviceProviderStatus;
    }

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "sc_id", nullable = false)
    @JsonIgnore
    public ServiceCategory getServiceCategory() {
        return this.serviceCategory;
    }

    public void setServiceCategory(ServiceCategory serviceCategory) {
        this.serviceCategory = serviceCategory;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "avail_date", nullable = false, length = 19)
    public Date getAvailDate() {
        return this.availDate;
    }

    public void setAvailDate(Date availDate) {
        this.availDate = availDate;
    }

    @Column(name = "cust_name", length = 50)
    public String getCustName() {
        return this.custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    @Column(name = "cust_mobile", length = 13)
    public String getCustMobile() {
        return this.custMobile;
    }

    public void setCustMobile(String custMobile) {
        this.custMobile = custMobile;
    }

    @Column(name = "cust_email", nullable = false, length = 50)
    public String getCustEmail() {
        return this.custEmail;
    }

    public void setCustEmail(String custEmail) {
        this.custEmail = custEmail;
    }

    @Column(name = "cust_address", length = 100)
    public String getCustAddress() {
        return this.custAddress;
    }

    public void setCustAddress(String custAddress) {
        this.custAddress = custAddress;
    }

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "booking")
    public Set<Allocation> getAllocations() {
        return this.allocations;
    }

    public void setAllocations(Set<Allocation> allocations) {
        this.allocations = allocations;
    }

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "booking")
    @JsonIgnore
    public Set<SuperAdmin> getSuperAdmins() {
        return this.superAdmins;
    }

    public void setSuperAdmins(Set<SuperAdmin> superAdmins) {
        this.superAdmins = superAdmins;
    }

}


You have to send a string which is Json data. So convert your javascript object "JSONObject" with JSON.stringify

var JSONObject= ...;
var jsonData = JSON.stringify( JSONObject );

Here you can find an example how u can extend jquery to have a postJSON function if you need this functionality more often http://rohanradio.com/blog/2011/02/22/posting-json-with-jquery/