March 19, 2012

Form submitted, response via ajax

Question by Andy

Currently I have this, which works nicely – it’s an email signup list which returns a successful response or error, as appropriate.

$.ajax({  
    type: "POST",  
    url: "mailing_list/mailing_list_add2.php",  
    data: dataString,  
    success: function(response) { 
        $('#emailform').html("<div id='display_block'></div>");
        $('#display_block')                      
        .hide()  
        .fadeIn(500, function() {  
            $('#display_block').html(response)
        });             
}  
}); 
return false; 
});

The form is in a div with ID “emailform” and the “display_block” is the response. What I need is for the response to automatically disappear after a short time and for the form to fade back in. I’ve tried a few things but nothing that has worked yet.

Any help on what to add to the above code would be appreciated.

Answer by redDevil

Assuming your initial html is like,

<div id="emailform">
   <form>
   ...
   </form>
</div>

you can proceed like this,

.ajax({       
type: "POST",       
url: "mailing_list/mailing_list_add2.php",       
data: dataString,       
success: function(response) {  

    var backupHtml = $('#emailform').html();        
    $('#emailform').html("<div id='display_block'></div>");            

    $('#display_block')                               
    .hide()       
    .html(response)    
    .fadeIn(500, function() {               
        $(this).fadeOut(5000,function(){
            $('#emailform').html(backupHtml);
        }); 
    });

}   
});  

Answer by Starx

To do instead of all mumbo jumbo.

$('#emailform').html("<div id='display_block'></div>");
$('#display_block').hide().html(response).stop().fadeIn(500);   

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!