Skip to content Skip to sidebar Skip to footer

Toggle() Div Element With Submitting Form Data

this is my problem: After submitting a form I want to see some data from a database (MySQL) for the selected object in a div-element. This element was set to “display:none” whe

Solution 1:

By default, a button element will submit a form, however, you overrode that behavior by setting type="button". (A tad counterintuitive, I agree.)

Since you're already using jQuery, you can take advantage of its built-in AJAX support and override the default form submission behavior. That's an approach that degrades gracefully: if a user is running in an environment that doesn't execute JavaScript, they will submit the form using default browser behavior and still see the results. (You would tweak your CSS to make your div visible by default in that case, and use JS to hide it during page load.) DEMO jsFiddle

var$form = $('form');
var$resultDiv = $('#wbtogdiv');
$resultDiv.hide();

var successHandler = function(data, textStatus, jqXhr) {
    $resultDiv.html(data);
    $resultDiv.fadeToggle(200);    
};

$form.submit(function(ev) {
    ev.preventDefault();
    if (! $resultDiv.is(':visible')) {
        $.post(
            '/path/to/your/script',
            $form.serialize(),
            successHandler
        );
    } else {
        $resultDiv.fadeToggle(200);
    }
});

(Also, since this is a test post, it's possible you aren't doing this in your actual code, but for heaven's sake, be extremely careful about a script that reveals information about its internal working to a user, or a script that echoes user-supplied content, unescaped, back to a web page. These are the first steps toward a fairly major security hole.)

Solution 2:

You can try this :

Do not use display: none; in CSS and instead do it by JQuery.

<style>#wbtogdiv {
    width:30%; 
    height:100px;
    border:6px solid green;
}
</style>

And this is what you do :

<divid="wbtogdiv"form-submitted = "no">KASTEN: <?phpecho print_r($_POST)?></div><script>
$(document).ready(function(){
    if($('#wbtogdiv').attr('form-submitted') == "no") {
       $('#wbtogdiv').hide(); 
    }   
});

$(document).ready(function(){
    $("#btn").submit(function(event){
        $("#wbtogdiv").fadeToggle(20);
        returntrue;

        $("#wbtogdiv").attr('form-submitted', "yes");
    });  
});
</script>

Post a Comment for "Toggle() Div Element With Submitting Form Data"