Ir para conteúdo

POWERED BY:

Arquivado

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

Williams Duarte

Formulário via Ajax, os arrays chegam vazios

Recommended Posts

Olá pessoal,

 

tenho um form que envia por ajax os arrays, porém estes dados não chega até o script php

já dei um debug pelo firebug, mas sempre mostra vazio.

 


<pre>Array ( )

 

script.js

$(function(){
    $('.submit-btn').click(function(){
        var formInputs = new Array();
        // Obter o formulário de ID
        var id = $(this).parent().attr('id');
        $('#' + id + ' input').each(function(){
            // Obter o valor de entrada
            var inputValue = $(this).val();
            // Obter o ID de entrada
            var inputId = $(this).attr('id');
            // Adicione-os à matriz
            formInputs[inputId] = inputValue; 
        });
		
        $.ajax({
            url: 'test.php',
            type: 'POST',
            data: {
                inputs: formInputs
            },
            success: function(data) {
				alert('Cadastro efetuado!');
            }
        });
    });
});

index.html

 

<!DOCTYPE html>
<head>
    <script type='text/javascript' src='http://code.jquery.com/jquery.min.js'></script>
    
    <script src='script.js'></script>
    <link href="../css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link media="screen" href='style.css' rel="stylesheet" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
    <div id='frame'>
        <h1>Register Form</h1>
        <div id='response' class='alert alert-success'></div>
        <form class='form-horizontal' id="form1">
            <div class='control-group'>
                <label class="control-label">Username:</label>
                <div class='controls'>
                    <input type='text' class='input-large' placeholder='Username' id='username' />
                </div>
            </div>
            <div class='control-group'>
                <label class="control-label">Real Name:</label>
                <div class='controls'>
                    <input type='text' class='input-large' placeholder='Real Name' id='real-name' />
                </div>
            </div>
            <div class='control-group'>
                <label class="control-label">E-Mail:</label>
                <div class='controls'>
                    <input type='text' class='input-large' placeholder='E-Mail' id='email' />
                </div>
            </div>
            <a href='#' class='btn btn-inverse btn-large pull-right submit-btn'><i class='icon-ok icon-white'></i> Submit</a>
        </form>
    </div>
	<script src="../js/bootstrap.min.js"></script>
</body>

Segue o script completo onde recebo os arrays e retorna um json para poder apresentar os erros encontrados.

 

<?php
    //Create an array to store data that we will send back to the jQuery
    $data = array(
        'success' => false, //Flag whether everything was successful
        'errors' => array() //Provide information regarding the error(s)
    );
 
    //Check to make sure that the inputs variable has been posted
    if (isset($_POST['inputs'])) {
        //Store the posted data into an array
        $inputs = $_POST['inputs'];
        //Loop through each input field
        foreach ($inputs as $input) {
            $id = $input['id'];
            $value = $input['value'];
            //Determine what validation we need to be doing
            switch($id) {
                //Username and real name need the same validation, so only need one case block here
                case "username":
                case "real-name":
                    //Ensure that they are both at least 6 characters long
                    if (strlen($value) < 6) {
                        //To make it more readable, replace the "-"'s with spaces and make the first character upper case
                        $msg = "Your " . str_replace("-", " ", ucfirst($id)) . " must be at least 6 characters in length";
                    }
                    break;
                case "email":
                    //Use PHP filter to validate the E-Mail address
                    if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                        $msg = "You must provide a valid e-mail address";
                    }
                    break;
                default:
                        //If some field has been passed over, we report the error
                        $msg = "Sorry, we don't understand this data, please try again";
                    break;
            }
            //If there is an error, add it to the errors array with the field id
            if (!empty($msg)) {
                $data['errors'][] = array(
                    'msg' => $msg,
                    'field' => $id
                );
            }
        }
 
        //Validation over, was it successful?
        if (empty($data['errors'])) {
            $data['success'] = true;
        }
 
    } else {
        $data['errors'][] = "Data missing";
    }
 
    //Set the content type and charset to ensure the browser is expecting the correct data format, also ensure charset is set-to UTF-8 and not utf8 to prevent any IE issues
    header("Content-Type: application/json; charset=UTF-8");
    echo json_encode((object)$data);
?>

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Tentei aqui mais não consegui,

 

não manjo nada de javascript.

 

Como eu adaptaria a esse código?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Brow geralmente no fórum de php onde participo mais e ajudo, a galera posta um código onde tem dificuldades, além de incluir links de funções do manual, vemos onde está errado, corrigimos e comentamos o código do porque de tal função está incluída em um fragmento do código, eu sei o quanto é difícil para o novatos, assim como esta sendo para mim agora.

 

deve ser por isso que muitos vão lá nó fórum de php e posta coisas de javascript e galera ajuda a resolver.

 

é uma das virtudes da comunidade do php

 

Dou outro jeito, e obrigado pela ajuda.

Compartilhar este post


Link para o post
Compartilhar em outros sites

pra começar atribua um NAME aos inputs

<input type="text" name="username" />
<input type="text" name="real-name" />
<input type="text" name="email" />

dai...

$('.submit-btn').click(function(){
var formdata = $('#form1').serialize();
$.ajax({
	url: 'test.php',
	type: 'POST',
	data: formdata,
	success: function(data) {
		alert( data );
	}
});
});

ainda mais simples...

$('.submit-btn').click(function(){
$.post('test.php', $('#form1').serialize(), function(data){
	alert('Cadastro efetuado!');
});
});

Compartilhar este post


Link para o post
Compartilhar em outros sites

Valeu pela ajuda Hugo Sóstenes, você achou o ponto crucial, os names, tava desde ontem batendo cabeça.

 

Obrigado. :thumbsup:

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.