0

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="you@example.com" 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;
    }

}
Community
  • 1
  • 1
Neelabh Singh
  • 2,600
  • 12
  • 51
  • 88
  • what exact is not working? add a success and error handler to your $.ajax() function and write to your console to see if the $.ajax() fails or what the server send back – micha Jan 18 '15 at 15:12
  • $.ajax({ url : "AJAX_POST_URL", type: "POST", data : formData, success: function(data, textStatus, jqXHR) { //data - response from server }, error: function (jqXHR, textStatus, errorThrown) { } }); – micha Jan 18 '15 at 15:15
  • what is not working now? what is the server response? – micha Jan 19 '15 at 15:57

4 Answers4

0

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.

Prashant Pokhriyal
  • 3,727
  • 4
  • 28
  • 40
micha
  • 1,238
  • 10
  • 7
0

You have mixed up JSON.parse() and JSON.stringify()

JSON.parse(): The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.

JSON.stringify(): The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

So in your code, you have to change JSON.parse to JSON.stringify

Prashant Pokhriyal
  • 3,727
  • 4
  • 28
  • 40
AtlasDev
  • 99
  • 4
  • Thanks for your answer I changed according to you but it is not working. – Neelabh Singh Jan 18 '15 at 14:58
  • Are you sure the code is working on the API side? Try the chrome app postman to verify that. http://www.getpostman.com – AtlasDev Jan 18 '15 at 16:09
  • Thanks for your replay But I am getting following error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at localhost:8080/HomeServiceProvider/customer/saveCustomer. This can be fixed by moving the resource to the same domain or enabling CORS – Neelabh Singh Jan 20 '15 at 09:52
0

I think you will have to add contentType also to the ajax request call,because you are trying to send json format data to server,like below.

var request = $.ajax({
                 url: "http://localhost:8080/HomeServiceProvider/rest/booking/saveBookingDetails",
                 type: "POST",
                 data: jsonData,
                 contentType: "application/json",
                 dataType: "json"
            });   

dataType : data format, you are expecting form server

contentType : data format ,you are sending to server

dReAmEr
  • 6,986
  • 7
  • 36
  • 63
  • 1
    Thanks for your answer I changed according to you but it is not working. – Neelabh Singh Jan 18 '15 at 15:36
  • what is the error?can you see the request in the network tab of your browser,the request header and body? – dReAmEr Jan 18 '15 at 15:37
  • Thanks for your replay But I am getting following error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at localhost:8080/HomeServiceProvider/customer/saveCustomer. This can be fixed by moving the resource to the same domain or enabling CORS – Neelabh Singh Jan 20 '15 at 09:51
0

Are you sure its not working ? I copied the same code as yours and tried executing on my domain and its just fine. here is the code, I replaced the variables with some hardcoded numbers.

var jsonData = JSON.stringify({"serviceCategory": 4, "availDate":2, "custName":4, "custMobile":4, "custEmail":4, "custAddress":4});
$.ajax({
             url: "http://cloudpanel.abstractdns.com",
             type: "POST",
             dataType: "json",                  
             data: jsonData,
             contentType: "application/json",
             success: function(response){
                alert(JSON.stringify(response));
             },
             error: function(err){
                alert(JSON.stringify(err));
             }
        });  

And here is the screenshot from firefox console that shows JSON data was sent properly.

enter image description here

The screenshot above clearly says its sending the correct data in the format specified. And if its not working can paste the screenshot from firebug so we can understand if its really not working, I'm saying this as you have already told that your new to web technologies. In case you don't know, you can install firebug on mozilla and chrome and do the inspecting yourself that will give you the insights of errors in any.

With respect to your comment, you have stated that you get an error regarding CORS. So this could be solved by replacing dataType: json with dataType: "jsonp". That should solve your problem if your app that has ajax and the app that ajax sends requests are on different servers.

Hope that helps

Pramod Solanky
  • 1,690
  • 15
  • 17
  • Thanks for your replay But I am getting following error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/HomeServiceProvider/customer/saveCustomer. This can be fixed by moving the resource to the same domain or enabling CORS. – Neelabh Singh Jan 20 '15 at 09:20
  • Ah ha! Well, that got nothing to do with your request. Is your app and the call that your making via ajax are on different servers ? – Pramod Solanky Jan 20 '15 at 09:23
  • When I am using advanced server I am able to send but through JQuery Not able to send. – Neelabh Singh Jan 20 '15 at 09:37
  • If the app is on the same server then it should work just fine. What's the backend ur using ? And by same server you also mean that they both use the same urls also .. Right ? – Pramod Solanky Jan 20 '15 at 09:58
  • In back end I am using MySQl, Hibernate, Maven – Neelabh Singh Jan 20 '15 at 10:06
  • please check 1st answer: http://stackoverflow.com/questions/24182259/cross-origin-request-blocked-the-same-origin-policy-disallows-reading-the-remot?rq=1 How I will do Access-Control-Allow-Origin: for local host, – Neelabh Singh Jan 20 '15 at 10:33
  • No I am Just asking That Is that problem ? If It is then please help me modify source code. – Neelabh Singh Jan 20 '15 at 10:52