tags:

views:

23

answers:

1

hi, i got a page wich shows content depending if a cookie is set or not, some of this content repeats itself , for example some jQuery code repeats itself:

$("form#maj_email").submit(function(){
var _data= $(this).serialize()
  $.ajax({
        type: 'POST',
        url: 'validation_profil.php?var=maj_email',
        beforeSend: function(){
$("div#ajax_icon_maj_email").css({background:"url('http://localho/www3/includes/images/ajax_loader.gif')"})


        },
        data:_data,
        success: function(html){
         $('div#error_maj_email').html(html)
  $("div#ajax_icon_maj_email").css({background:"url('none')"})
  if( $("div#error_maj_email").text()=="Email syntaxe incorrecte"){
   $("form#maj_email input:[name=email]").css({border:"1px solid red"})
 }
else{ $("form#maj_email input:[name=email]").css({border:"1px solid gray"})  }

         }
     })

})

so i was wondering is there a way to take this whole code and make it equal to a variable?

A: 

You can put your reusable code in a function

function standard_code()
{
  var _data= $(this).serialize()
  $.ajax({
        type: 'POST',
        url: 'validation_profil.php?var=maj_email',
        beforeSend: function(){
$("div#ajax_icon_maj_email").css({background:"url('http://localho/www3/includes/images/ajax_loader.gif')"})


        },
        data:_data,
        success: function(html){
         $('div#error_maj_email').html(html)
  $("div#ajax_icon_maj_email").css({background:"url('none')"})
  if( $("div#error_maj_email").text()=="Email syntaxe incorrecte"){
   $("form#maj_email input:[name=email]").css({border:"1px solid red"})
 }
else{ $("form#maj_email input:[name=email]").css({border:"1px solid gray"})  }

         }
     })

}

and then call it whenever you want

$("form#maj_email").submit(standard_code()) ;
Romain Deveaud