views:

70

answers:

3

Hi everyone,

I have a small survey, but when i submit it says that the msg is null, i don't see where is my error.

If you could help me i apreciate it.

Thank you

My Form with Jquery and Ajax Function

<!DOCTYPE HTML>
<hmtl lang="pt-PT">
        <head>
                <title>Formul&aacute;rio</title>
                <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
        </head>
<body>
<hr />
        <h3>Formulario</h3>

        <script type="text/javascript" charset="utf-8">
                $(function () {
                        $('#submiter').click( function() {
                                $.ajax({
                                  type: "POST",
                                  url: 'validar.php',
                                  dataType: 'json',
                                  success: function(msg) {
                                        alert('Mensagem '+ msg.mensagem);
                                },
                                error : function () {
                                        alert('Ocorreu um erro');
                                }
                                });

                        });
                });
        </script>

        <form id="formulario" action="" method="post" accept-charset="utf-8">
                <p>Pergunta 1</p>
                <label for="pergunta1">sim</label><input type="radio" id="p1" name="pergunta1" value="1" /><br />
                <label for="pergunta1">n&atilde;o</label><input type="radio" id="p1" name="pergunta1" value="0" />
                <br />

                <p>Pergunta 2</p>
                <label for="pergunta2">sim</label><input type="radio" name="pergunta2" value="0" /><br />
                <label for="pergunta2">n&atilde;o</label><input type="radio" name="pergunta2" value="1" />
                <br />         

                <p>Pergunta 3</p>
                <label for="pergunta3">sim</label><input type="radio" name="pergunta3" value="0" /><br />
                <label for="pergunta3">n&atilde;o</label><input type="radio" name="pergunta3" value="1" />
                <br />         

                <p>Pergunta 4</p>
                <label for="pergunta4">sim</label><input type="radio" name="pergunta4" value="0" /><br />
                <label for="pergunta4">n&atilde;o</label><input type="radio" name="pergunta4" value="1" />
                <br /> 


                <p><input type="submit" id="submiter" value="Continue &rarr;"></p>
        </form>
        </body>
</html>

My PHP

<?php
    if($_POST) {
        $pergunta1 = $_POST['pergunta1'];
        $pergunta2 = $_POST['pergunta2'];
        $pergunta3 = $_POST['pergunta3'];
        $pergunta4 = $_POST['pergunta4'];

        $calcular = $pergunta1 + $pergunta2 + $pergunta3 + $pergunta4;

        $var = array ('mensagem' => $calcular);

        echo json_encode($var);
    }
    else {
        $var2 = array('mensagem' => 'sem resultado');
        echo json_encode($var2);
    }
?>
+4  A: 

There are two problems. Halfway down the PHP you have <php not <?php. But really you should be using json_encode. Just make a PHP array with your data, json_encode it, and it'll do all the clever JSON stuff for you. It'll be much easier to maintain that way.

Another problem: JSON keys should be strings.

Try something like this:

$result = array();
if ($calcular <= 9) {
    $result['mensagem'] = 1;
}
//... etc.

echo json_encode($result);

Edit: I've just done a check, and the following works for me:

$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: 'validar.php',
        dataType: 'json',
        success: function(msg) {
            alert('Mensagem '+ msg.mensagem);
        },
        error : function () {
            alert('Ocorreu um erro');
        }
    });
});
Skilldrick
Hey, thank you for your answer, i remade the code, but firebug is giving the same problem:msg is null[Break on this error] alert('Mensagem ' + msg.mensagem );
Davidslv
Oh man... thank you very much!!!!
Davidslv
Happy to help :)
Skilldrick
+1  A: 

I'm guessing it's because your JSON syntax isn't correct (look it up and see what quotes you missed :). You could use json_encode in PHP to save you from building it manually.

Also note that you should be serving an appropriate content type from the PHP responder (application/json). I don't know if that affects jQuery's built in parsing, but it feels cleaner.

Alex Ciminian
Thank you, i will check that... i had a similar code in Perl and didn't had any problem... i really don't know what is happening here..Thanks
Davidslv
A: 

JSON needs to be in a strict format, which your PHP is not giving. Use json_encode to make sure that your output is valid.

Something like:

<?php
    if(!empty($_POST)) { // ensure _POST exists, and is not empty
        foreach($_POST as $key => $val) {
            // if the string 'pergunta' is contained within that _POST key, add to a total
            if(strpos($key, "pergunta") !== false) { 
                $calcular += $val;
            }
        }

        // return '1' for 9 and under, '2' for 10 or 11, '3' for 12 and over
        $mensagem = ($calcular <= 9) ? 1 : ($calcular > 9 && $calcular <= 11) ? 2 : 3;

        // use json_encode to ensure that what we echo back is valid JSON, eg. {"mensagem":1}
        echo json_encode(array('mensagem' => $mensagem));
    }
?>
Adam Hepton