views:

74

answers:

2

Hi I am doing form submission and validation using jquey and from server side I am getting a response in JSON format.. I am displaying the message in jquery dialog box but not able to show the message from server....

my approach:

    <script type="text/javascript">
//<![CDATA[
    $.validator.setDefaults({
    submitHandler: function() { 
        var spogName         = $("input#spogname").val();
        var spogDis            = $("input#spogdescription").val();
        var dataString         ='&spogName='+ spogName +'&spogDescription=' + spogDis;
        $.ajax({
            url: "/cpsb/spogMaster.do?method=addSpog",    
            type: "POST",        
            data: dataString,        
            cache: false,
            success: function() {  
                $("#dialog-message").dialog({
                    resizable:false,
                    height:180,
                    modal: true,
                    buttons: {
                        Ok: function() {
                            $(this).dialog('close');
                        }
                    }
                });

               },   

           error: function(){

               }                    
        });



         },
    highlight: function(input) {
        $(input).addClass("ui-state-highlight");
    },
    unhighlight: function(input) {
        $(input).removeClass("ui-state-highlight");
    }
});

$(document).ready(function() {
    navMenu();
    $("#spogForm").validate({
        rules: {
            spogname:{
            required: true
            }
        },
        messages: {
            spogname: "Please enter the Spog Name"
        }
    });


    $(":submit").button();
});
//]]>
</script>

my markup:

<div id="dialog-message" title="Spog Message" style="display:none;">

    <p>
        <span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
         Spog added successfully!
    </p>
</div>
<div id="header"><jsp:include  page="../menu_v1.jsp"/></div>
<div id="mainContent">
<div id="spog_form">
  <form class="cmxform" id="spogForm" method="post" action="/cpsb/spogMaster.do?method=addSpog">
    <fieldset class="ui-widget ui-widget-content ui-corner-all">
        <legend class="ui-widget ui-widget-header ui-corner-all">ADD SPOG</legend>
        <p>
            <label for="spogname">Spog Name (required)</label>
            <input id="spogname" name="spogName" class="required ui-widget-content" minlength="2" />
        </p>
        <p>
            <label for="spogdescription">Spog Description </label>
            <input id="spogdescription" name="spogDescription" class="spogD ui-widget-content" />
        </p>

        <p>
            <button class="submit" type="submit">Submit</button>
        </p>
    </fieldset>
</form>
</div>
</div>
</body>

json string I am getting if spog existed in database:

{"messageId":"errorMessage","message":"spog found with Name 10000 Description nuts"}

Update1:

   <script type="text/javascript">
//<![CDATA[
    $.validator.setDefaults({
    submitHandler: function() { 
        var spogName         = $("input#spogname").val();
        var spogDis            = $("input#spogdescription").val();
        $.ajax({
            url: "/cpsb/spogMaster.do?method=addSpog",    
            type: "POST",    
            datatype:'json',    
            data: {
                method:"addSpog",
                spogName:spogName,
                spogDescription:spogDis
            },    
            cache: false,
            success: function(data) {
              if ( data.messageId === 'errorMessage' ) {
                // server responded with an error, show the error placeholder
                // fill in the error message, and spawn the dialog
                $("#dialog-message")
                  .find('.success').hide().end()
                  .find('.error').show()
                    .find('.message').text( data.message ).end()
                    .end()
                  .dialog({
                    resizable:false,
                    height:180,
                    modal: true,
                    buttons: {
                      Ok: function() {
                        $(this).dialog('close');
                      }
                    }
                  });
              } else {
                // server liked it, show the success placeholder and spawn the dialog
                $("#dialog-message")
                  .find('.error').hide().end()
                  .find('.success').show().end()
                  .dialog({
                    resizable:false,
                    height:180,
                    modal: true,
                    buttons: {
                      Ok: function() {
                        $(this).dialog('close');
                      }
                    }
                  });
              }
            }


        });



         },
    highlight: function(input) {
        $(input).addClass("ui-state-highlight");
    },
    unhighlight: function(input) {
        $(input).removeClass("ui-state-highlight");
    }
});

$(document).ready(function() {
    navMenu();
    $("#spogForm").validate({
        rules: {
            spogname:{
            required: true
            }
        },
        messages: {
            spogname: "Please enter the Spog Name"
        }
    });


    $(":submit").button();
});
//]]>
</script>

markup:

<div id="dialog-message" title="Spog Message" style="display:none;">
    <p class="success">
        <span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
         Spog added successfully!
    </p>
    <p class="error">
        An error occurred while adding spog: 
        <span class="message"></span>
    </p>
</div>
A: 

Add the following above "success": datatype: "json",

Then change success to something like:

success: function(data) {  
    $("#dialog-message").append('<p>'+data.message+'</p>').dialog({
        resizable:false,
        height:180,
        modal: true,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });
},

Basically you need to;
a) Tell your code that your server will be returning JSON (and it should therefore eval it)
b) Do something with that JSON - e.g. pull out the message and append it to your dialog box

Please understand that the above code is only a suggestion and I haven't tested it!

Sam
Just out of curiosity: why have I been down-voted?
Sam
Was an accident actually. I was trying to remove the up-vote, but it down-voted instead.
BBonifield
Edit your answer, and I can up-vote it instead :)
BBonifield
@Sam I have voted you +1 ...I sm using @BBonified approach and adding that json datatype but still only able to receive only one message not able to receive the other message when spog is already existed in database
paul
@BBonifield - I've edited my post. @paul - Can we see a demo page so we can debug the problem? At the minute we're all working blind!
Sam
@Sam My application is still in development phase and don't have any public URL....I have tried to debug it and see that instead of going to if statement it directly go to else block and show me the successful message instead of showing the error message....so it is not executing if ( data.messageId === 'errorMessage' )
paul
+2  A: 

As @Sam notes, you'll need to adjust your success callback, and you'd also need to adjust your HTML a bit.

<div id="dialog-message" title="Spog Message" style="display:none;">
    <p class="success">
        <span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
         Spog added successfully!
    </p>
    <p class="error">
        An error occurred while adding spog: 
        <span class="message">placeholder</span>
    </p>
</div>

Then the JS change...

success: function(data) {
  if ( data.messageId && data.messageId === 'errorMessage' ) {
    // server responded with an error, show the error placeholder
    // fill in the error message, and spawn the dialog
    $("#dialog-message")
      .find('.success').hide().end()
      .find('.error').show()
        .find('.message').text( data.message ).end()
        .end()
      .dialog({
        resizable:false,
        height:180,
        modal: true,
        buttons: {
          Ok: function() {
            $(this).dialog('close');
          }
        }
      });
  } else {
    // server liked it, show the success placeholder and spawn the dialog
    $("#dialog-message")
      .find('.error').hide().end()
      .find('.success').show().end()
      .dialog({
        resizable:false,
        height:180,
        modal: true,
        buttons: {
          Ok: function() {
            $(this).dialog('close');
          }
        }
      });
  }
},
BBonifield
well I tried your suggestion but still it showing me spog added successfully instead of showing the server response {"messageId":"errorMessage","message":"spog found with Name 10000 Description toys"}
paul
Did you properly change "success: function(){" to "success: function(data){" ? Assuming your server is giving the proper "application/json" content-type header and writing out the data, it should work properly.
BBonifield
Yes, I changed to function(data)..Please check my updated js as you suggested above
paul
Have you verified that "data" is actually the proper JSON return object with console.log()?
BBonifield
yes I verified the JSON string and it is {"messageId":"errorMessage","message":"spog found with Name 10000 Description toys"}
paul