-1

There is an employee registration from. I have sent the value to controller by ajax calling. Controller has got the value ( I saw the value in debugging) . But when I alert the response in jquery:

  success: function(response){
      // var obj = JSON.parse(response);
      var obj = jQuery.parseJSON(JSON.stringify(response));
      alert(response);
  },

it shows [object: object] But I want this type of response, like: this is an demo example

This is my JSP page:

    var company = [] ;
    var from = [] ;
    var to = [] ;
    var year =[];
    var organization =[];
    var topic =[];
    var duration =[];



    jQuery(document).ready(function($) { 
         var files; 
            var exp = $('input:radio[name=exp]:checked').val();
            var training = $('input:radio[name=training]:checked').val();

            $("#pexp").hide();
            $("#fieldexp").hide();
            $("#ptrain").hide();
            $("#fieldtrain").hide();


        $("#btnSubmit").click(function(){

            addEmployeeOnlineInformation();
             processFileUpload();

        });

     $("#image").on('change',prepareLoad);



    $('input[type=radio][name=exp]').change(function() {
        if (this.value == 'Yes') {

             $("#pexp").show();

             addExp();
        }
        else if (this.value == 'No') {

            $("#pexp").hide();
            $("#addmorefieldexp").empty();

        }
    });

    $('input[type=radio][name=train]').change(function() {
        if (this.value == 'Yes') {

             $("#ptrain").show();

             addTrain();
        }
        else if (this.value == 'No') {

            $("#ptrain").hide();
            $("#addmorefieldtrain").empty();

        }
    });

    });



    function addExp(){

           var scntDiv = $('#addmorefieldexp');



           $('#pexp').live('click', function() {
                          $( ' <br><br>'
                            +'<label for="inputPassword3" class="col-sm-2 control-label">Company Name</label>'
                            +'<div class="col-sm-2">'
                            +'<input type="text" class="form-control" name="field_company[]">'
                            +'</div>'

                            +'<label for="inputPassword3" class="col-sm-1 control-label">From</label>'
                            +'<div class="col-sm-2">'
                            +'<input type="text" class="form-control" name="field_from[]">'
                            +'</div>'

                            +'<label for="inputPassword3" class="col-sm-1 control-label">To</label>'
                            +'<div class="col-sm-2">'
                            +'<input type="text" class="form-control" name="field_to[]">'
                            +'</div>'

                            +'<label for="inputPassword3" class="col-sm-1 control-label">Year</label>'
                            +'<div class="col-sm-1">'
                            +'<input type="text" class="form-control" name="field_year[]">'
                            +'</div>').appendTo(scntDiv);


                        return false;  

           });


    }

    function addTrain(){

       var scntDiv = $('#addmorefieldtrain');



        $('#ptrain').live('click', function() {
                       $(        '<div class="form-group text-center" id="fieldtrain">'
                                +'<label for="inputPassword3" class="col-sm-2 control-label">Organization</label>'
                                +'<div class="col-sm-2">'
                                +'<input type="text" class="form-control" name="field_organization[]">'
                                +'</div>'

                                +'<label for="inputPassword3" class="col-sm-2 control-label">Topic</label>'
                                +'<div class="col-sm-2">'
                                +'<input type="text" class="form-control" name="field_topic[]">'
                                +'</div>'

                                +'<label for="inputPassword3" class="col-sm-2 control-label">Duration</label>'
                                +'<div class="col-sm-2">'
                                +'<input type="text" class="form-control" name="field_duration[]">'
                                +'</div>'
                                +'</div>').appendTo(scntDiv);


                     return false;  

        });


 }

    function array(){



        var inps = document.getElementsByName('field_company[]');
        for (var i = 0; i <inps.length; i++) {
        var inp=inps[i];
            company.push(inp.value);
    }
        var inps = document.getElementsByName('field_from[]');
        for (var i = 0; i <inps.length; i++) {
        var inp=inps[i];
            from.push(inp.value);
    }
        var inps = document.getElementsByName('field_to[]');
        for (var i = 0; i <inps.length; i++) {
        var inp=inps[i];
            to.push(inp.value);
    }
        var inps = document.getElementsByName('field_year[]');
        for (var i = 0; i <inps.length; i++) {
        var inp=inps[i];
            year.push(inp.value);
    }
        var inps = document.getElementsByName('field_organization[]');
        for (var i = 0; i <inps.length; i++) {
        var inp=inps[i];
            organization.push(inp.value);
    }
        var inps = document.getElementsByName('field_topic[]');
        for (var i = 0; i <inps.length; i++) {
        var inp=inps[i];
            topic.push(inp.value);
    }
        var inps = document.getElementsByName('field_duration[]');
        for (var i = 0; i <inps.length; i++) {
        var inp=inps[i];
            duration.push(inp.value);
    }
    }



    function addEmployeeOnlineInformation(){


         array();
         var gender = $('#gender').val();
         var blood = $('#blood').val();


        $.ajax({
            type: "post",
            url: "http://localhost:8080/EmployeeOnlineRegistrationForm/employee",
            cache: false,


           data:'name=' + $("#name").val() 
               +"&fname=" + $("#fname").val() 
               +"&mname=" + $("#mname").val() 
               +"&nid=" + $("#nid").val() 
               +"&age=" + $("#age").val()
               +"&blood=" + blood
               +"&gender=" + gender 
               +"&caddress=" + $("#caddress").val() 
               +"&paddress=" + $("#paddress").val()
               +"&paddress=" + $("#paddress").val()
               +"&pdegree=" + $("#pdegree").val()
               +"&puniversity=" + $("#puniversity").val()
               +"&pyear="+ $("#pyear").val()
               +"&presult=" + $("#presult").val()
               +"&mdegree=" + $("#mdegree").val()
               +"&muniversity=" + $("#muniversity").val()
               +"&mresult=" + $("#mresult").val()
               +"&myear=" + $("#myear").val()
               +"&bdegree=" + $("#bdegree").val()
               +"&buniversity=" + $("#buniversity").val()
               +"&bresult=" + $("#bresult").val()
               +"&byear=" + $("#byear").val()
               +"&hdegree=" + $("#hdegree").val()
               +"&college=" + $("#college").val()
               +"&hresult=" + $("#hresult").val()
               +"&hyear=" + $("#hyear").val()
               +"&sdegree=" + $("#sdegree").val()
               +"&school=" + $("#school").val()
               +"&sresult=" + $("#sresult").val()
               +"&syear=" + $("#syear").val()
               +"&date=" + $("#date").val()
               +"&department=" + $("#department").val()
               +"&location=" + $("#location").val()
               +"&company=" + company
               +"&from=" + from
               +"&to=" + to
               +"&year=" + year
               +"&organization=" + organization
               +"&topic=" + topic
               +"&duration=" + duration,

            success: function(response){

               // var obj = JSON.parse(response);
                var obj = jQuery.parseJSON(JSON.stringify(response));
                alert(obj);

            },

            error: function(){                      
                alert('Error while request..');
            }
        });

    }

    function prepareLoad(event)
    {
        files=event.target.files;
    }
    function processFileUpload()
    {
        var oMyForm = new FormData();
        oMyForm.append("file", files[0]);
        $
            .ajax({dataType : 'text',
                url : "http://localhost:8080/EmployeeOnlineRegistrationForm/uploadMyFile",
                data : oMyForm,
                type : "POST",
                enctype: 'multipart/form-data',
                processData: false,
                contentType:false,
                success : function(result) {
                    alert(result);
                },
                error : function(result){
                    alert('error'+result);
                }
            });
    }

This is my Controller:

@Controller

public class EmployeeRegistrationController {

    @RequestMapping(value="/employee",method = RequestMethod.POST)
     public @ResponseBody
     EmployeeOnlineRegistrationForm add(HttpServletRequest request, HttpServletResponse response)
       throws Exception {
        EmployeeOnlineRegistrationForm employeeregistration = new EmployeeOnlineRegistrationForm();

     String name = request.getParameter("name");
     String fname = request.getParameter("fname");
     String mname = request.getParameter("mname");
     String nid = request.getParameter("nid");
     String age = request.getParameter("age");
     String blood = request.getParameter("blood");
     String gender = request.getParameter("gender");
     String caddress = request.getParameter("caddress");
     String paddress = request.getParameter("paddress");
     String pdegree = request.getParameter("pdegree");
     String puniversity = request.getParameter("puniversity");
     String pyear = request.getParameter("pyear");
     String presult = request.getParameter("presult");
     String mdegree = request.getParameter("mdegree");
     String muniversity = request.getParameter("muniversity");
     String myear = request.getParameter("myear");
     String mresult = request.getParameter("mresult");
     String bdegree = request.getParameter("bdegree");
     String buniversity = request.getParameter("buniversity");
     String byear = request.getParameter("byear");
     String bresult = request.getParameter("bresult");
     String hdegree = request.getParameter("hdegree");
     String college = request.getParameter("college");
     String hyear = request.getParameter("hyear");
     String hresult = request.getParameter("hresult");
     String sdegree = request.getParameter("sdegree");
     String school = request.getParameter("school");
     String syear = request.getParameter("syear");
     String sresult = request.getParameter("sresult");
     String date = request.getParameter("date"); 
     String location = request.getParameter("location");
     String department =request.getParameter("department");
     String[] company =request.getParameter("company").split(",");
     String[] from =request.getParameter("from").split(",");
     String[] to =request.getParameter("to").split(",");
     String[] year =request.getParameter("year").split(",");
     String[] organization =request.getParameter("organization").split(",");
     String[] topic =request.getParameter("topic").split(",");
     String[] duration =request.getParameter("duration").split(","); 

     employeeregistration.setName(name);
     employeeregistration.setFname(fname);
     employeeregistration.setMname(mname);
     employeeregistration.setNid(nid);
     employeeregistration.setAge(age);
     employeeregistration.setBlood(blood);
     employeeregistration.setGender(gender);
     employeeregistration.setCaddress(caddress);
     employeeregistration.setPaddress(paddress);
     employeeregistration.setPdegree(pdegree);
     employeeregistration.setPuniversity(puniversity);
     employeeregistration.setPyear(pyear);
     employeeregistration.setPresult(presult);
     employeeregistration.setMdegree(mdegree);
     employeeregistration.setMuniversity(muniversity);
     employeeregistration.setMyear(myear);
     employeeregistration.setMresult(mresult);
     employeeregistration.setBdegree(bdegree);
     employeeregistration.setBuniversity(buniversity);
     employeeregistration.setByear(byear);
     employeeregistration.setBresult(bresult);
     employeeregistration.setHdegree(hdegree);
     employeeregistration.setCollege(college);
     employeeregistration.setHyear(hyear);
     employeeregistration.setHresult(hresult);
     employeeregistration.setSdegree(sdegree);
     employeeregistration.setSchool(school);
     employeeregistration.setSyear(syear);
     employeeregistration.setSresult(sresult);
     employeeregistration.setDate(date);
     employeeregistration.setDepartment(department);
     employeeregistration.setLocation(location);
     employeeregistration.setCompany(company);
     employeeregistration.setFrom(from);
     employeeregistration.setTo(to);
     employeeregistration.setYear(year);
     employeeregistration.setOrganization(organization);
     employeeregistration.setTopic(topic);
     employeeregistration.setDuration(duration);

     System.out.println(" name "+name+" fname "+fname+" mname "+mname+" blood "+blood+" gender "+ gender+" caddress "+caddress+" paddress "+paddress
          +" pyear "+pyear+" pdegree "+pdegree+" puniversity "+puniversity+" presult "+presult
          +" myear "+myear+" mdegree "+mdegree+"  muniversity "+muniversity+" mresult "+mresult
          +" byear "+byear+" bdegree "+bdegree+" buniversity "+buniversity+" bresult "+bresult
          +" hyear "+hyear+" hdegree "+hdegree+" college "+college+" hresult "+hresult
          +" syear "+syear+" sdegree "+sdegree+" school "+school+" sresult "+sresult
          +" date "+date+" location "+location+" department "+department);

      return employeeregistration;
     }


        @RequestMapping(value = "/welcome",method = RequestMethod.GET)
        public String index(ModelMap model){
            model.addAttribute("message", "Spring MVC XML Config Example");
            return "index";
        }

        @RequestMapping(value = "/uploadMyFile", method = RequestMethod.POST)
        @ResponseBody
        public String handleFileUpload(MultipartHttpServletRequest request)
                throws Exception {
            Iterator<String> itrator = request.getFileNames();
            MultipartFile multiFile = request.getFile(itrator.next());
            try {

                String fileName=multiFile.getOriginalFilename();
                //String path=request.getSession().getServletContext().getRealPath("/");
                //System.out.println(path);
                //making directories for our required path.
                byte[] bytes = multiFile.getBytes();
                //File directory=    new File(path+ "/image");
                File directory=    new File("/E:/Java_Project/EmployeeOnlineRegistrationForm/src/main/webapp/resources/image");
                if(!directory.exists())
                    directory.mkdirs();
                // saving the file
                File file=new File(directory.getAbsolutePath()+System.getProperty("file.separator")+multiFile.getOriginalFilename());
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(file));
                stream.write(bytes);
                stream.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Error while loading the file");
            }


            return "File Uploaded Successfully";
        }

How Can I get this response from controller?

Jai
  • 74,255
  • 12
  • 74
  • 103
OUN Saif
  • 305
  • 1
  • 4
  • 20

2 Answers2

0

Your response is javascript object. You can not alert object.Access object properties as below:

 var obj = JSON.parse(response);

                alert(obj.country);

This will alert Malaysia.Like this access other properties.

Check alert(typeof(response)); it outputs object.

JSON.strngfy() Converts a JavaScript object into a string.So your output is like this.see more here...http://www.w3schools.com/js/js_json_stringify.asp

Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19
  • `JSON.stringify()` **doesn't** convert object into JSON. It converts a JSON into string. That's why, _stringify_. – 31piy Jan 03 '17 at 04:44
  • @31piy: That's not quite correct. JSON is a *textual* data representation and can only exist in JavaScript as a string value. There is no such thing as "a" JSON. `JSON.stringify` converts any JavaScript value to JSON, `JSON.parse` converts JSON into a JavaScript value. – Felix Kling Jan 03 '17 at 04:45
  • *"Your response is javascript object."* Which is why `var obj = JSON.parse(response);` can't work. `response` is already an object. – Felix Kling Jan 03 '17 at 04:45
  • @ 31piy yes JSON.strngfy() Converts a JavaScript object into a string. – Hikmat Sijapati Jan 03 '17 at 04:48
  • @ Felix Kling ... json is also like string...but different is that json is used to transport information over internet. am I right? – Hikmat Sijapati Jan 03 '17 at 04:50
  • *"json is also like string"* Most data transmitted via HTTP is *text*. JSON is text. In JavaScript program, text is stored in strings. Therefore JSON exists inside strings. `JSON.stringify` returns a string containing JSON. – Felix Kling Jan 03 '17 at 04:53
  • But when I do this: **var obj = JSON.parse(response); ** , it shows the error in inspect: `Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () at Object.success (addEmployee.js:236) at fire (jquery-1.9.1.js:1037) at Object.fireWith [as resolveWith] (jquery-1.9.1.js:1148) at done (jquery-1.9.1.js:8074) at XMLHttpRequest.callback (jquery-1.9.1.js:8598)` – OUN Saif Jan 03 '17 at 04:58
  • `var obj = JSON.parse(response);` then `obj.country` . it will works. – Hikmat Sijapati Jan 03 '17 at 05:06
  • @OUNAsh: `response` is already an object. You don't need (or can) parse the value. Just access the properties you are interested in. See my answer. – Felix Kling Jan 03 '17 at 05:11
  • @ Felix Kling but response is sent from server...does it is possible to send data from server in object form? – Hikmat Sijapati Jan 03 '17 at 05:14
  • jQuery will automatically parse the response if the right headers are sent. – Felix Kling Jan 03 '17 at 05:41
0

Getting [object Object] when using alert is to be expected. [object Object] is the default string representation of an object, and alert converts its argument to a string. See:

var obj = {foo: 42};
alert(obj);
console.log(obj.toString());

If you want to debug your code you should use console.log or console.dir, not alert:

var obj = {foo: 42};
console.log(obj);

You just need to access the correct properties on response. See Access / process (nested) objects, arrays or JSON for how.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143