Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass JSON data to restful web services through ajax and also how to get JSON data?

Hi, I am new to JSON .My question is how to pass JSON data to restful web services through ajax?

Please Help me.

I tried by following code but I am not sure about it

MY INDEX PAGE

<script type="text/javascript">

 $(document).ready(function(){  

     var uname = document.getElementById("uname").value();
     var password = document.getElementById("pwd").value();


     $('#ok').click(function(){  
         $.ajax({  
             url:'http://localhost:8090/LoginAuthRWS/rest/orders',  
             type:'post',  
             dataType: 'Jsondemo',


             success: function(data) {  
                 $('#name').val(data.name);  
                 $('#email').val(data.email);  

                 var JSONObject= {
                         "uname":uname,
                         "password":password
                         };
             }  
         });  
     });  
}); 

</script>  
like image 744
Jagathesewaren Kuppuraj Avatar asked Oct 24 '13 04:10

Jagathesewaren Kuppuraj


2 Answers

var JSONObject= {"uname":uname, "password":password };
var jsonData = JSON.parse( JSONObject );    

var request = $.ajax({
  url: "rest/orders",
  type: "POST",
  data: jsonData,
  dataType: "json"
});        
like image 107
Arvind Avatar answered Nov 10 '22 15:11

Arvind


Problems with your code:

  • .value is a property not an function
  • You want to pass json use data of $.ajax
  • There no data type as Jsondemo you have to use JSON
  • if response data is not JSON you can use $.parseJSON to convertit to JSON

Complete Code

$(document).ready(function(){  
    $('#ok').click(function(){  
        var uname = document.getElementById("uname").value;
        var password = document.getElementById("pwd").value;
        var JSONObject= {
             "uname":uname,
             "password":password
             };

        $.ajax({  
            url:'http://localhost:8090/LoginAuthRWS/rest/orders',  
            type:'post',
            data :  JSONObject,      
            dataType: 'JSON',
            success: function(data) { 
                     var jsonData = $.parseJSON(data); //if data is not json
                     $('#name').val(jsonData.name);  
                     $('#email').val(jsonData.email);  
                }  
        });  
    });  
});      
like image 31
Satpal Avatar answered Nov 10 '22 17:11

Satpal