使用jQuery / Ajax将数据发送到数据库

时间:2015-02-22 15:52:19

标签: php jquery mysql ajax

我正在尝试创建一个使用jQuery将数据发送到mysql数据库的表单。它在没有jquery的情况下工作,但我坚持将它转换为jquery。

我曾尝试使用that solution,但我失败了,我不知道如何处理该代码......

HTML:

 <!-- Newsletter section start -->
    <div class="section third-section">
        <div class="container newsletter">
            <div class="sub-section">
                <div class="title clearfix">
                    <div class="pull-left">
                        <h3>Zapisz się na warsztaty!</h3>
                    </div>
                </div>
            </div>
            <div id="success-subscribe" class="alert alert-success invisible">
                <strong>Well done!</strong>You successfully subscribet to our newsletter.</div>
            <div class="row-fluid">
                <div class="span5">
                    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
                </div>
                <div class="span12">
                <form  id="newsletter" action="php/newsletter.php" >
                        <input type="text" name="imie" id="imie" class="span5" placeholder="Imię" required><br>
                        <input type="text" name="nazwisko" id="nazwisko" class="span5" placeholder="Nazwisko" required><br>
                        <input type="text" name="email" id="nlmail" class="span5" placeholder="Twój adres email" required><br>
                        <input type="text" name="uczelnia" id="uczelnia" class="span5" placeholder="Uczelnia" required><br>
                        <input type="text" name="kolo" id="kolo" class="span5" placeholder="Koło naukowe" required><br>
                        <input type="text" name="aktywnosc" id="aktywnosc" class="span5" placeholder="Prezentacja/Poster/Brak"  required><br>
                        <input type="text" name="tytul" id="tytul" class="span5" placeholder="Tutuł prezentacji lub posteru" ><br>
                        <button id="subscribe" class="button button-sp">Wyślij</button>
                </form>
                    <div id="err-subscribe" class="error centered">Please provide valid email address.</div>
                </div>
            </div>
        </div>
    </div>
    <!-- Newsletter section end -->

jQuery代码:

 $('#subscribe').click(function () {
    var error = false;
    var emailCompare = /^([a-z0-9_.-]+)@([0-9a-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
    var email = $('input#nlmail').val().toLowerCase(); // get the value of the input field
    if (email == "" || email == " " || !emailCompare.test(email)) {
        $('#err-subscribe').show(500);
        $('#err-subscribe').delay(4000);
        $('#err-subscribe').animate({
            height: 'toggle'
        }, 500, function () {
            // Animation complete.
        });
        error = true; // change the error state to true
    }

    if (error === false) {
        $.ajax({
            type: 'POST',
            url: 'php/newsletter.php',

             data: $('#newsletter').serialize(),
            /* 
            data: {
                imie: $('#imie').val()
                nazwisko: $('#nazwisko').val()
                email: $('#nlmail').val()
                uczelnia: $('#uczelnia').val()
                kolo: $('#kolo').val()
                aktywnosc: $('#aktywnosc').val()
                tytul: $('#tytul').val()
            }, */
            error: function (request, error) {
                alert("An error occurred");
            },
            success: function (response) {
                if (response == 'OK') {
                    $('#success-subscribe').show();
                    $('#nlmail').val('')
                } else {
                    alert("An error occurred");
                }
            }
        });
    }

    return false;
});

PHP代码:

<?php

include 'functions.php';

if (!empty($_POST)){

  $data['success'] = true;
  $_POST  = multiDimensionalArrayMap('cleanEvilTags', $_POST);
  $_POST  = multiDimensionalArrayMap('cleanData', $_POST);

 $dane=$_POST['serialize'];

  $imie = $dane["imie"];
  $nazwisko = $dane["nazwisko"];
  $email = $dane["email"];
  $uczelnia = $dane["uczelnia"];
  $kolo = $dane["kolo"];
  $aktywnosc = $dane["aktywnosc"];
  $tytul = $dane["tytul"];
  $ip = $_SERVER['REMOTE_ADDR'];

  if($imie == "")
   $data['success'] = false;

  if($nazwisko == "")
   $data['success'] = false;
  if($uczelnia == "")
   $data['success'] = false;
  if($kolo == "")
   $data['success'] = false;
  if($aktywnosc == "")
   $data['success'] = false;

 if (!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) 
   $data['success'] = false;



 if($data['success'] == true){

 mysql_connect("***);
mysql_select_db("***");

   mysql_query("INSERT INTO `***` (`imie`, `nazwisko`, `email`, `uczelnia`, `kolo`, `aktywnosc`, `tytul`, `ip`)
            VALUES ('".$imie."', '".$nazwisko."', '".$email."', '".$uczelnia."', '".$kolo."','".$aktywnosc."', '".$tytul."', '".$ip."');");

  $data['success'] = true;
  echo 'OK';
}
}

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我使用该模板中的另一个函数做了一个解决方法。

jquery代码:

$("#send-register").click(function () {

    var imie = $('input#imie').val(); // get the value of the input field
    var error = false;
    if (imie == "" || imie == " ") {
        $('#err-imie').show(500);
        $('#err-imie').delay(4000);
        $('#err-imie').animate({
            height: 'toggle'
        }, 500, function () {
            // Animation complete.
        });
        error = true; // change the error state to true
    }

    var nazwisko = $('input#nazwisko').val(); // get the value of the input field
    var error = false;
    if (nazwisko == "" || nazwisko == " ") {
        $('#err-nazwisko').show(500);
        $('#err-nazwisko').delay(4000);
        $('#err-nazwisko').animate({
            height: 'toggle'
        }, 500, function () {
            // Animation complete.
        });
        error = true; // change the error state to true
    }

    var emailCompare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
    var email2 = $('input#email2').val().toLowerCase(); // get the value of the input field
    if (email2 == "" || email2 == " " || !emailCompare.test(email2)) {
        $('#err-email2').show(500);
        $('#err-email2').delay(4000);
        $('#err-email2').animate({
            height: 'toggle'
        }, 500, function () {
            // Animation complete.
        });
        error = true; // change the error state to true
    }

    var uczelnia = $('input#uczelnia').val(); // get the value of the input field
    var error = false;
    if (uczelnia == "" || uczelnia == " ") {
        $('#err-uczelnia').show(500);
        $('#err-uczelnia').delay(4000);
        $('#err-uczelnia').animate({
            height: 'toggle'
        }, 500, function () {
            // Animation complete.
        });
        error = true; // change the error state to true
    }

    var kolo = $('input#kolo').val(); // get the value of the input field
    var error = false;
    if (kolo == "" || kolo == " ") {
        $('#err-kolo').show(500);
        $('#err-kolo').delay(4000);
        $('#err-kolo').animate({
            height: 'toggle'
        }, 500, function () {
            // Animation complete.
        });
        error = true; // change the error state to true
    }

            var aktywnosc = $('input#aktywnosc').val(); // get the value of the input field
    var error = false;
    if (aktywnosc == "" || aktywnosc == " ") {
        $('#err-aktywnosc').show(500);
        $('#err-aktywnosc').delay(4000);
        $('#err-aktywnosc').animate({
            height: 'toggle'
        }, 500, function () {
            // Animation complete.
        });
        error = true; // change the error state to true
    }

    if (error == false) {
        var dataString = $('#register-form').serialize(); // Collect data from form
        $.ajax({
            type: "POST",
            url: $('#register-form').attr('action'),
            data: dataString,
            timeout: 6000,
            error: function (request, error) {

            },
            success: function (response) {
                response = $.parseJSON(response);
                if (response.success) {
                    $('#successSend-register').show();
                    $("#imie").val('');
                    $("#nazwisko").val('');
                    $("#email2").val('');
                    $("#uczelnia").val('');
                    $("#kolo").val('');
                    $("#aktywnosc").val('');
                } else {
                    $('#errorSend-register').show();
                }
            }
        });
        return false;
    }

    return false; // stops user browser being directed to the php file
});

包含错误代码和其他精美小工具的HTML。

<div class="span12 newsletter centered">
                    <div id="successSend-register" class="alert alert-success invisible">
                        Twoje zgłoszenie zostało wysłane!</div>
                    <div id="errorSend-register" class="alert alert-error invisible">Wystąpił błąd.</div>
                    <form id="register-form" action="php/register.php">
                        <div class="control-group">
                            <div class="controls">
                                <input class="span12" type="text" id="imie" name="imie" placeholder="* Imię..." />
                                <div class="error left-align" id="err-imie">Proszę podać swoje imię.</div>
                            </div>
                        </div>
                        <div class="control-group">
                            <div class="controls">
                                <input class="span12" type="text" id="nazwisko" name="nazwisko" placeholder="* Nazwisko..." />
                                <div class="error left-align" id="err-nazwisko">Proszę podać swoje nazwisko.</div>
                            </div>
                        </div>
                        <div class="control-group">
                            <div class="controls">
                                <input class="span12" type="email" name="email2" id="email2" placeholder="* Adres email..." />
                                <div class="error left-align" id="err-email2">Proszę podać poprawny adres email.</div>
                            </div>
                        </div>
                        <div class="control-group">
                            <div class="controls">
                                <input class="span12" type="text" id="uczelnia" name="uczelnia" placeholder="* Uczelnia..." />
                                <div class="error left-align" id="err-uczelnia">Proszę podać nazwę uczelni.</div>
                            </div>
                        </div>
                        <div class="control-group">
                            <div class="controls">
                                <input class="span12" type="text" id="kolo" name="kolo" placeholder="* Koło..." />
                                <div class="error left-align" id="err-kolo">Proszę podać nazwę koła naukowego.</div>
                            </div>
                        </div>
                        <div class="control-group">
                            <div class="controls">
                                <input class="span12" type="text" id="aktywnosc" name="aktywnosc" placeholder="* Rodzaj uczestnictwa: Prezentacja/Poster/Brak..." />
                                <div class="error left-align" id="err-aktywnosc">Proszę podać rodzaj uczestnictwa: Prezentacja/Poster/Brak.</div>
                            </div>
                        </div>
                        <div class="control-group">
                            <div class="controls">
                                <input class="span12" type="text" id="tytul" name="tytul" placeholder="Tytuł prezentacji/posteru (jeśli dotyczy)..." />
                            </div>
                        </div>                              
                        <div class="control-group">
                            <div class="controls">
                                <button id="send-register" class="message-btn">Wyślij zgłoszenie</button>
                            </div>
                        </div>
                    </form>
                </div>

PHP几乎没有任何差异。