Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

matusaires3

Problema com form javascript

Recommended Posts

Estou com um problema em jquery ui, ao tentar salvar esse formulario pelo method post em um arquivo php para ficar salvo no banco de dados ele nem armazena as variaves nem nada o que pode ser?

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery UI Dialog - Modal form</title>
    <link rel="stylesheet" href="resources/css/jquery-ui.css">
    <script type="javascript" src="resources/javascript/jquery-1.10.2.js"></script>
    <script type="javascript" src="resources/javascript/jquery-ui.js"></script>

	
    <style>
        body { font-size: 62.5%; }
        label, input { display:block; }
        input.text { margin-bottom:12px; width:95%; padding: .4em; }
        fieldset { padding:0; border:0; margin-top:25px; }
        h1 { font-size: 1.2em; margin: .6em 0; }
        div#users-contain { width: 350px; margin: 20px 0; }
        div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
        div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
        .ui-dialog .ui-state-error { padding: .3em; }
        .validateTips { border: 1px solid transparent; padding: 0.3em; }
    </style>

    <script>
        $(function() {
            var dialog, form,

                emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
                nome = $( "#nome" ),
                ip = $( "#ip" ),
                obs = $( "#obs" ),
                allFields = $( [] ).add( nome ).add( ip ).add( obs ),
                tips = $( ".validateTips" );

            function updateTips( t ) {
                tips
                    .text( t )
                    .addClass( "ui-state-highlight" );
                setTimeout(function() {
                    tips.removeClass( "ui-state-highlight", 1500 );
                }, 500 );
            }

            function checkLength( o, n, min, max ) {
                if ( o.val().length > max || o.val().length < min ) {
                    o.addClass( "ui-state-error" );
                    updateTips( "Length of " + n + " must be between " +
                    min + " and " + max + "." );
                    return false;
                } else {
                    return true;
                }
            }

            function checkRegexp( o, regexp, n ) {
                if ( !( regexp.test( o.val() ) ) ) {
                    o.addClass( "ui-state-error" );
                    updateTips( n );
                    return false;
                } else {
                    return true;
                }
            }
            <!-- Aqui eu coloco as permisões no formulario-->
            function addUser() {
                var valid = true;
                allFields.removeClass( "ui-state-error" );

                valid = valid && checkLength( nome, "nome", 3, 16 );
                valid = valid && checkLength( ip, "ip", 6, 80 );
                valid = valid && checkLength( obs, "obs", 5, 16 );

                valid = valid && checkRegexp( nome, /^[a-z.]([0-9a-z_\s])+$/i, "O usuário deve conter letras de  a-z, 0-9." );
                valid = valid && checkRegexp( ip, /^[0-9a-zA-Z]([-.\w])+$/i, "Digite o IP corretamente." );
                valid = valid && checkRegexp( obs, /^([0-9a-zA-Z])+$/,"Verifique a observação");

                if ( valid ) {
                    $( "#users tbody" ).append( "<tr>" +
                    "<td>" + nome.val() + "</td>" +
                    "<td>" + ip.val() + "</td>" +
                    "<td>" + obs.val() + "</td>" +
                    "</tr>" );
                    dialog.dialog( "close" );
                }
                return valid;
            }

            dialog = $( "#dialog-form" ).dialog({
                autoOpen: false,
                height: 300,
                width: 350,
                modal: true,
                buttons: {
                    "Adicionar novo servidor": addUser,
                    Cancelar: function() {
                        dialog.dialog( "close" );
                    }
                },
                close: function() {
                    form[ 0 ].reset();
                    allFields.removeClass( "ui-state-error" );
                }
            });

            form = dialog.find( "form" ).on( "submit", function( event ) {
                event.preventDefault();
                addUser();
            });

            $( "#create-user" ).button().on( "click", function() {
                dialog.dialog( "open" );
            });
        });
    </script>
</head>
<body>

<div id="dialog-form" title="Cadastrar novo servidor">
    <p class="validateTips">Preencha os campos corretamente.</p>

    <form action="salvar.php" method="post">
        <fieldset>
            <label for="name">Nome do servidor</label>
            <input type="text" name="nome" id="nome"  class="text ui-widget-content ui-corner-all">
            <label for="email">Ip do servidor</label>
            <input type="text" name="ip" id="ip"  class="text ui-widget-content ui-corner-all">
            <label for="text">Observacao</label>
            <input type="text" name="obs" id="obs"  class="text ui-widget-content ui-corner-all">

            <!-- Permitir o envio do formulário com teclado sem duplicar o botão de diálogo -->
            <input type="submit" tabindex="-1" id="create-user" style="position:absolute; top:-1000px">
        </fieldset>
    </form>
</div>


<div id="users-contain" class="ui-widget" >
    <h1>Servidores Cadastrados:</h1>
    <table id="users" class="ui-widget ui-widget-content">
        <thead>
        <tr class="ui-widget-header ">
            <th>Nome</th>
            <th>Ip do servidor</th>
            <th>Observação</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>Pereiro8bm</td>
            <td>172.2.10.1</td>
            <td>Torre Mateus</td>
        </tr>
        </tbody>
    </table> 
</div>
<button id="create-user">Adicionar novo servidor</button>


</body>
</html>

Salvar.php

<?php
require_once "config.php";

$nome = $_POST['nome'];
$ip = $_POST['ip'];
$obs = $_POST['obs'];


if(empty($nome)){
    echo "0";
}elseif(empty($ip)){
    echo "0";
}
elseif(empty($obs)){
    echo "0";
}

else
{   // essa primeira query e apenas registrada e depois no painel ela e faz um update no banco e no painel interno.
    mysql_query("insert into servidor(nome,ip,obs) values ('$nome','$ip','$obs')");

}

echo "$nome";
echo "$ip";
echo "$obs";
?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bruno eu tentei com ajax mais também não deu certo... como eu poderia fazer pode me ajudar por favor..


<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery UI Dialog - Modal form</title>
    <link rel="stylesheet" href="resources/css/jquery-ui.css">
    <script type="javascript" src="resources/javascript/jquery-1.10.2.js"></script>
    <script type="javascript" src="resources/javascript/jquery-ui.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('#ajax_form').submit(function(){
            var dados = jQuery( this ).serialize();
 
            jQuery.ajax({
                type: "POST",
                url: "grava.php",
                data: dados,
                success: function( data )
                {
                    alert( data );
                }
            });
            
            return false;
        });
    });
    </script>

	
    <style>
        body { font-size: 62.5%; }
        label, input { display:block; }
        input.text { margin-bottom:12px; width:95%; padding: .4em; }
        fieldset { padding:0; border:0; margin-top:25px; }
        h1 { font-size: 1.2em; margin: .6em 0; }
        div#users-contain { width: 350px; margin: 20px 0; }
        div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
        div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
        .ui-dialog .ui-state-error { padding: .3em; }
        .validateTips { border: 1px solid transparent; padding: 0.3em; }
    </style>

    <script>
        $(function() {
            var dialog, form,

                emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
                nome = $( "#nome" ),
                ip = $( "#ip" ),
                obs = $( "#obs" ),
                allFields = $( [] ).add( nome ).add( ip ).add( obs ),
                tips = $( ".validateTips" );

            function updateTips( t ) {
                tips
                    .text( t )
                    .addClass( "ui-state-highlight" );
                setTimeout(function() {
                    tips.removeClass( "ui-state-highlight", 1500 );
                }, 500 );
            }

            function checkLength( o, n, min, max ) {
                if ( o.val().length > max || o.val().length < min ) {
                    o.addClass( "ui-state-error" );
                    updateTips( "Length of " + n + " must be between " +
                    min + " and " + max + "." );
                    return false;
                } else {
                    return true;
                }
            }

            function checkRegexp( o, regexp, n ) {
                if ( !( regexp.test( o.val() ) ) ) {
                    o.addClass( "ui-state-error" );
                    updateTips( n );
                    return false;
                } else {
                    return true;
                }
            }
            <!-- Aqui eu coloco as permisões no formulario-->
            function addUser() {
                var valid = true;
                allFields.removeClass( "ui-state-error" );

                valid = valid && checkLength( nome, "nome", 3, 16 );
                valid = valid && checkLength( ip, "ip", 6, 80 );
                valid = valid && checkLength( obs, "obs", 5, 16 );

                valid = valid && checkRegexp( nome, /^[a-z.]([0-9a-z_\s])+$/i, "O usuário deve conter letras de  a-z, 0-9." );
                valid = valid && checkRegexp( ip, /^[0-9a-zA-Z]([-.\w])+$/i, "Digite o IP corretamente." );
                valid = valid && checkRegexp( obs, /^([0-9a-zA-Z])+$/,"Verifique a observação");

                if ( valid ) {
                    $( "#users tbody" ).append( "<tr>" +
                    "<td>" + nome.val() + "</td>" +
                    "<td>" + ip.val() + "</td>" +
                    "<td>" + obs.val() + "</td>" +
                    "</tr>" );
                    dialog.dialog( "close" );
                }
                return valid;
            }

            dialog = $( "#dialog-form" ).dialog({
                autoOpen: false,
                height: 300,
                width: 350,
                modal: true,
                buttons: {
                    "Adicionar novo servidor": addUser,
                    Cancelar: function() {
                        dialog.dialog( "close" );
                    }
                },
                close: function() {
                    form[ 0 ].reset();
                    allFields.removeClass( "ui-state-error" );
                }
            });

            form = dialog.find( "form" ).on( "submit", function( event ) {
                event.preventDefault();
                addUser();
            });

            $( "#create-user" ).button().on( "click", function() {
                dialog.dialog( "open" );
            });
        });
    </script>
</head>
<body>

<div id="dialog-form" title="Cadastrar novo servidor">
    <p class="validateTips">Preencha os campos corretamente.</p>

   <form method="post" id="ajax_form">
        <fieldset>
            <label for="name">Nome do servidor</label>
            <input type="text" name="nome" id="nome"  class="text ui-widget-content ui-corner-all">
            <label for="email">Ip do servidor</label>
            <input type="text" name="ip" id="ip"  class="text ui-widget-content ui-corner-all">
            <label for="text">Observacao</label>
            <input type="text" name="obs" id="obs"  class="text ui-widget-content ui-corner-all">

            <!-- Permitir o envio do formulário com teclado sem duplicar o botão de diálogo -->
            <input type="submit" tabindex="-1"  style="position:absolute; top:-1000px">
        </fieldset>
    </form>
</div>


<div id="users-contain" class="ui-widget" >
    <h1>Servidores Cadastrados:</h1>
    <table id="users" class="ui-widget ui-widget-content">
        <thead>
        <tr class="ui-widget-header ">
            <th>Nome</th>
            <th>Ip do servidor</th>
            <th>Observação</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>Pereiro8bm</td>
            <td>172.2.10.1</td>
            <td>Torre Mateus</td>
        </tr>
        </tbody>
    </table> 
</div>
<button id="create-user">Adicionar novo servidor</button>


</body>
</html>

Coloquei assim mais ainda não da certo,

Compartilhar este post


Link para o post
Compartilhar em outros sites

O que acontece ?

 

A requisição é disparada ? veja no console de erros se o ajax ao menos chega a ir até o servidor.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Vc está importando o core do jQuery 2 vezes. Importe uma única vez.

 

troque:

jQuery('#ajax_form').submit(function(){
por

jQuery('body').on('submit', '#ajax_form', function(){
pois como o form está dentro de um dialog, vc precisa de delegate para ativar o evento

Compartilhar este post


Link para o post
Compartilhar em outros sites

creio que o problema e aqui

 

dialog = $( "#dialog-form" ).dialog({
                autoOpen: false,
                height: 300,
                width: 350,
                modal: true,
                buttons: {
                    "Cadastrar": cadastrar,
                    Cancelar: function() {
                        dialog.dialog( "close" ); 
                    }
                },

pois quando eu coloco um button submit no form ele da certo, como faria para esse button cadastrar:cadastrar dar Submit

Compartilhar este post


Link para o post
Compartilhar em outros sites

tenta assim...

 

add essa função

function sendForm( form, callback ){
    return $.ajax({
        url: 'grava.php',
        type: 'POST',
        data: form.serialize(),
        cache: false
    }).done(callback);
}

e troque a função "addUser" por está...

function addUser() {
                var valid = true;
                allFields.removeClass( "ui-state-error" );

                valid = valid && checkLength( nome, "nome", 3, 16 );
                valid = valid && checkLength( ip, "ip", 6, 80 );
                valid = valid && checkLength( obs, "obs", 5, 16 );

                valid = valid && checkRegexp( nome, /^[a-z.]([0-9a-z_\s])+$/i, "O usuário deve conter letras de  a-z, 0-9." );
                valid = valid && checkRegexp( ip, /^[0-9a-zA-Z]([-.\w])+$/i, "Digite o IP corretamente." );
                valid = valid && checkRegexp( obs, /^([0-9a-zA-Z])+$/,"Verifique a observação");

                if( !valid ) return;
                    $( "#users tbody" ).append( "<tr>" +
                    "<td>" + nome.val() + "</td>" +
                    "<td>" + ip.val() + "</td>" +
                    "<td>" + obs.val() + "</td>" +
                    "</tr>" );
                    dialog.dialog( "close" );
                
                //return valid;

                sendForm($('#ajax_form'), function( data ){
                   // aqui vc debuga a resposta do servidor
                    console.log( data );
                });
            }

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.