3

i'm new to php and ajax and i`m trying to send a php form data via ajax (without the reflesh) and display the echo msg of the php on an alert box via ajax sucess, but it didnt work. The code goes like this:

jQuery(document).ready(function(){
        jQuery('#ajax_form').submit(function(){
            var dados = jQuery( this ).serialize();

            jQuery.ajax({
                type: "POST",
                url: "env.php",
                data: dados,
                success: function( data )
                {
                    alert( data );
                }
            });

            return false;
        });
    });

and the php echo responses (send and error):

 $erros = "";

 if(empty($_POST['nome'])){
     $erros .= "O nome deve ser preenchido.";
 }

 if(empty($_POST['email']) ){
      $erros .= "O E-mail deve ser preenchido.";
 }else{
      $email = $_POST['email'];
      eregi("([\._0-9A-Za-z-]+)@([0-9A-Za-z-]+)(\.[0-9A-Za-z\.]+)",$email,$match);
    if(!isset($match)){
       $erros .= "O e-mail informado é inválido.";
    }
}

if(empty($_POST['mensagem'])){
    $erros .= "A mensagem deve ser preenchida.";
}
if( empty($erros) ){

all the code to get form data and send

 $send = $phpmail->Send();

    if($send){
        echo "A Mensagem foi enviada com sucesso.";
    }else{
        echo "Não foi possível enviar a mensagem. Erro: " .$phpmail->ErrorInfo;
    }

    }else{
        echo $erros;
    }

I want to put the echo message of env.php on the alert, but i really dont know how to do this, i tryied putting data, but it shows the entire document (with html on text form). Can anyone help me please?

ps: the form is on a .html and the php on a .php

EDIT:

I tryied to add $json = json_encode($erros); but it wont work, how can i read this on the sucess ajax function? (on a alert box)


I tryied to add $json = json_encode($erros); but it wont work, how can i read this on the sucess ajax function? (on a alert box)

4

2 回答 2

0

env.php needs to respond to the AJAX call with only the data you want it to, not an entire page. All you have to do is modify env.php to not have all the HTML stuff you don't need.

于 2012-10-02T02:27:44.187 回答
0

这样做我的朋友:

jQuery(document).ready(function(){
        jQuery('#ajax_form').submit(function(){
            var dados = jQuery( this ).serialize();

            jQuery.ajax({
                type: "POST",
                url: "env.php",
                data: dados,
                success: function( data )
                {
                    var data_output = data;
                    alert(data_output);
                }
            });

            return false;
        });
    });
于 2016-04-20T10:55:58.307 回答