2
\$\begingroup\$

I've reusing this code for multiple areas and will like to make it more short and/or portable. What suggestions or changes could I make to simplify shorten it's callback processes?

 $("#add_question_member").submit(function(){
 $.ajax({
 type:'post',
 url: '/posts_in.php',
 dataType: "json",
 data: $(this).serialize(),
 success: function(data){
 var response = data[0]; 
 $("#entry_area").fadeOut(function(){ 
 if(response==1){ 
 $("#msg0").stop().fadeIn("slow").delay(8000).fadeOut("slow",function(){
 $("#entry_area").stop().fadeIn("slow");
 });
 }else{ 
 $("#msg1").stop().fadeIn("slow").delay(8000).fadeOut("slow",function(){
 $("#entry_area").stop().fadeIn("slow");
 });
 }
 });
 }
 });
 return false; 
 });
asked Feb 6, 2012 at 16:39
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Here is a jsfiddle where I cleaned it up for you

I did not actually test it so there might be a syntax error here and there but its how you would do it overall. It might not be 100% but it should get you started as far as the techniques you should look into such as:

That's a lot of stuff and a bit overkill on this example but I wanted to showcase the techniques for you. Feel free to ask any questions.

A couple additional notes

  • You generally want to use the expression context parameter to limit your selectors
  • You probably want to avoid using ids and use classes instead since things get wierd if you accidentally end up with 2 of the same id on the page. This is something that happens more often as you start to make your views more composable. This is something that using the expression context can help with.
  • submit is only available on forms anyways, you could denote that explicitly $('form#add_question_member')
  • Do you really want to be returning false?
  • Consider using the form's action and method properties instead of hardcoding them - $(this).prop('action'), $(this).prop('method') at the same level as you serialize the form

    //****This part can be in a seperate script file **********// (function() { //use an immediately executing function to limit scope var submitFormDefaults = { //set up all the defaults to be used the function type: 'post', url: '/posts_in.php', dataType: "json", myAppUnWrapData: true //a custom option to unrwap your returned data by default };

    var standardSubmitForm = function(successFnOrOptions) {
     // This allows your input to be just the success function or a richer object
     var options = $.isFunction(successFnOrOptions) ? {
     success: successFnOrOptions
     } : successFnOrOptions;
     // return the actual submit handler
     return function() {
     var op = $.extend(true, //deep clone
     submitFormDefaults, //use defaults unless overridden
     { data: $(this).serialize() }, //not in the defaults cause it needs access to 'this'
     options //any overrides specified
     );
     if (op.myAppUnWrapData && op.success) { //if unwrap data custom option is truthy and there is a success callback
     var _oldSuccess = op.success;
     op.success = function(data) {
     _oldSuccess(data[0]);
     }
     }
     $.ajax(op);
     return false;
     }
    }
    //Export the local function to the gloabl namespace using Module pattern
    window.MyApp = window.MyApp || {}; //create a global MyApp namespace
    $.extend(window.MyApp, { //add some global functions. I prefer to use $.extend rather than directly assigning it - I have no good reason for this
     submitForm: standardSubmitForm //export our function to the global namespace 
    });
    window.MyApp.submitForm.defaults = submitFormDefaults //export the defaults as a global property on this function
    

})(); //Invoke the above immediately invoking function

//******************** Elsewhere ********************************//
$("#add_question_member").submit(window.MyApp.submitForm(function(response) { //this will return a function handler
 if (response !== 1) {
 $("#msg0").stop().fadeIn("slow").delay(8000).fadeOut("slow", function() {
 $("#entry_area").stop().fadeIn("slow");
 });
 } else {
 $("#msg1").stop().fadeIn("slow").delay(8000).fadeOut("slow", function() {
 $("#entry_area").stop().fadeIn("slow");
 });
 }
}));
// or...
$('form.blah').submit(window.MyApp.submitForm({
 url: '/somewhere/else',
 success: function() {
 console.log('ok', this, arguments);
 }
});
// or...
window.MyApp.submitForm.defaults.action = 'GET'; //changes it globally
$('form.blah').submit(window.MyApp.submitForm({
 url: '/somewhere/else',
 myAppUnWrapData: false, //keep it from doing the data[0] thing
 success: function(data) {
 console.log('ok', this, arguments);
 }

});

answered Feb 6, 2012 at 18:21
\$\endgroup\$
4
  • \$\begingroup\$ no no, he said shorten and simplify \$\endgroup\$ Commented Feb 6, 2012 at 18:38
  • 1
    \$\begingroup\$ Like I said, I don't know his exact usecase so I'm showing the techniques. However, the actual usage code is significantly shorter and simpler \$\endgroup\$ Commented Feb 6, 2012 at 18:40
  • 1
    \$\begingroup\$ yea, i was just poking fun. +1 btw you might want to add the code inline in case that jsfiddle ever gets removed \$\endgroup\$ Commented Feb 6, 2012 at 18:46
  • \$\begingroup\$ Oh wow, this is super. I definitely need to go through every single point you've included, learn it and make sense of it. The fiddle looks great! Thank you so much for this. \$\endgroup\$ Commented Feb 6, 2012 at 19:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.