Форум: Форум PHPФорум ApacheФорум Регулярные ВыраженияФорум MySQLHTML+CSS+JavaScriptФорум FlashРазное
Новые темы: 0000000
Социальная инженерия и социальные хакеры. Авторы: Кузнецов М.В., Симдянов И.В. Самоучитель PHP 5 / 6 (3 издание). Авторы: Кузнецов М.В., Симдянов И.В. PHP. Практика создания Web-сайтов (второе издание). Авторы: Кузнецов М.В., Симдянов И.В. Программирование. Ступени успешной карьеры. Авторы: Кузнецов М.В., Симдянов И.В. PHP 5. На примерах. Авторы: Кузнецов М.В., Симдянов И.В., Голышев С.В.
ВСЕ НАШИ КНИГИ
Консультационный центр SoftTime

HTML+CSS+JavaScript

Выбрать другой форум

 

Здравствуйте, Посетитель!

вид форума:
Линейный форум Структурный форум

тема: ajax json form
 
 автор: makigo   (10.01.2013 в 12:24)   письмо автору
 
 

Привет всем.
У меня такая форма:

index.php

<html>
    <head>
        <title>My Form</title>
        
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        
        <script type="text/javascript">
            
            $(document).ready(function(){
                            
                $("#myForm").submit(function(){
                    var tvyalner = $("#myForm").serialize();
                    $.ajax({
                        type: "POST",
                        url: "postForm.ajax.php",
                        data: tvyalner,
                        dataType: "json",
                        
                        success: function(data){
                            $("#formResponse").removeClass('error');
                            $("#formResponse").addClass(data.status);
                            $("#formResponse").html(data.message);
                            if(data.status === 'success'){$("#myForm table").hide();}
                        },
                        error: function(){
                    $("#formResponse").removeClass('success');
                    $("#formResponse").addClass('error');
                    $("#formResponse").html("There was an error submitting the form. Please try again.");
                        }
                    });
                    
                    //make sure the form doens't post
                    return false;
                
                
                });
            
            
            });
        </script>
        
        <style type="text/css">
        
            .success{
                
                border: 2px solid #009400;
                background: #B3FFB3;
                color: #555;
                font-weight: bold;
                
            }
            
            .error{
                
                border: 2px solid #DE001A;
                background: #FFA8B3;
                color: #000;
                font-weight: bold;
            }
        </style>
        
    </head>
    <body>
<div class="mfm">
    <form id="myForm" name="myForm" method="post" action="" style="margin: 0 auto; width: 300px;">
    
        <div id="formResponse"></div>
        
        <table>
            
            <tr><td>Name:</td><td><input name="name" type="text" value=""></td></tr>
            <tr><td>Email:</td><td><input name="email" type="text" value=""></td></tr>
            <tr><td>Message:</td><td><textarea name="message" rows="5" cols="20"></textarea></td></tr>
            <tr><td>&nbsp;</td><td><input type="submit" name="submitForm" value="Submit Form"></td></tr>
            
        </table>

    </form>
</div>    
    </body>
</html>


postForm.ajax.php


<?php

//function to validate the email address
//returns false if email is invalid
function checkEmail($email){
   
    if(
eregi("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]"$email)){
        return 
FALSE;
    }

    list(
$Username$Domain) = split("@",$email);

    if(@
getmxrr($Domain$MXHost)){
        return 
TRUE;
   
    } else {
        if(@
fsockopen($Domain25$errno$errstr30)){
            return 
TRUE
        } else {

            return 
FALSE
        }
    }
}    



//response array with status code and message
$response_array = array();

//validate the post form

//check the name field
if(empty($_POST['name'])){

    
//set the response
    
$response_array['status'] = 'error';
    
$response_array['message'] = 'Name is blank';

//check the email field
} elseif(!checkEmail($_POST['email'])) {

    
//set the response
    
$response_array['status'] = 'error';
    
$response_array['message'] = 'Email is blank or invalid';

//check the message field
} elseif(empty($_POST['message'])) {

    
//set the response
    
$response_array['status'] = 'error';
    
$response_array['message'] = 'Message is blank';


//form validated. send email
} else {
    
    
//send the email
    
$body $_POST['name'] . " sent you a message\n";
    
$body .= "Details:\n\n" $_POST['message'];
    
mail($_POST['email'], "SUBJECT LINE"$body);

    
//set the response
    
$response_array['status'] = 'success';
    
$response_array['message'] = 'Email sent!';

}


echo 
json_encode($response_array);

?>


Пробовал на Денвере и после первой пустой отправки выдает "Name is blank" а после его заполнения и второй отправки "There was an error submitting the form. Please try again." и все не работает...

  Ответить  
 
 автор: mihdan   (15.01.2013 в 16:21)   письмо автору
 
   для: makigo   (10.01.2013 в 12:24)
 

Для отправки форм ajax'ом проще использовать jquery.form, а отладку проводить через консоль вашего браузера.

  Ответить  
Rambler's Top100
вверх

Rambler's Top100 Яндекс.Метрика Яндекс цитирования