복붙노트

[JQUERY] AJAX는 페이지 새로 고침없이 PHP로 폼 데이터를 전달하여 양식 제출

JQUERY

AJAX는 페이지 새로 고침없이 PHP로 폼 데이터를 전달하여 양식 제출

해결법


  1. 1.양식은 아약스 요청 후 제출한다.

    양식은 아약스 요청 후 제출한다.

    <html>
      <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script>
          $(function () {
    
            $('form').on('submit', function (e) {
    
              e.preventDefault();
    
              $.ajax({
                type: 'post',
                url: 'post.php',
                data: $('form').serialize(),
                success: function () {
                  alert('form was submitted');
                }
              });
    
            });
    
          });
        </script>
      </head>
      <body>
        <form>
          <input name="time" value="00:00:00.00"><br>
          <input name="date" value="0000-00-00"><br>
          <input name="submit" type="submit" value="Submit">
        </form>
      </body>
    </html>
    

  2. 2.

    <html>
      <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script>
          $(function () {
            $('form').bind('click', function (event) {
            // using this page stop being refreshing 
            event.preventDefault();
    
              $.ajax({
                type: 'POST',
                url: 'post.php',
                data: $('form').serialize(),
                success: function () {
                  alert('form was submitted');
                }
              });
            });
          });
        </script>
      </head>
      <body>
        <form>
          <input name="time" value="00:00:00.00"><br>
          <input name="date" value="0000-00-00"><br>
          <input name="submit" type="submit" value="Submit">
        </form>
      </body>
    </html>
    

    PHP

    <?php
    
    if(isset($_POST["date"]) || isset($_POST["time"])) {
    $time="";
    $date="";
    if(isset($_POST['time'])){$time=$_POST['time']}
    if(isset($_POST['date'])){$date=$_POST['date']}
    
    echo $time."<br>";
    echo $date;
    }
    ?>
    

  3. 3.JS 코드

    JS 코드

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/   libs/jquery/1.3.0/jquery.min.js">
    </script>
    
    <script type="text/javascript" >
      $(function() {
      $(".submit").click(function() {
      var time = $("#time").val();
      var date = $("#date").val();
      var dataString = 'time='+ time + '&date=' + date;
    
    if(time=='' || date=='')
    {
      $('.success').fadeOut(200).hide();
      $('.error').fadeOut(200).show();
    }
    else
    {
      $.ajax({
        type: "POST",
        url: "post.php",
        data: dataString,
        success: function(){
         $('.success').fadeIn(200).show();
         $('.error').fadeOut(200).hide();
        }
      });
    }
    return false;
    });
    });
    </script>
    

    HTML 양식

       <form>
          <input id="time" value="00:00:00.00"><br>
          <input id="date" value="0000-00-00"><br>
          <input name="submit" type="button" value="Submit">
        </form>
    <span class="error" style="display:none"> Please Enter Valid Data</span>
    <span class="success" style="display:none"> Form Submitted Success</span>
    </div>
    

    PHP 코드

    <?php
    if($_POST)
    {
    $date=$_POST['date'];
    $time=$_POST['time'];
    mysql_query("SQL insert statement.......");
    }else { }
    
    ?>
    

    여기에서 찍은


  4. 4.JS 코드

    JS 코드

        $("#submit").click(function() { 
        //get input field values
        var name            = $('#name').val(); 
        var email           = $('#email').val();
        var message         = $('#comment').val();
        var flag = true;
        /********validate all our form fields***********/
        /* Name field validation  */
        if(name==""){ 
            $('#name').css('border-color','red'); 
            flag = false;
        }
        /* email field validation  */
        if(email==""){ 
            $('#email').css('border-color','red'); 
            flag = false;
        } 
        /* message field validation */
        if(message=="") {  
           $('#comment').css('border-color','red'); 
            flag = false;
        }
        /********Validation end here ****/
        /* If all are ok then we send ajax request to email_send.php *******/
        if(flag) 
        {
            $.ajax({
                type: 'post',
                url: "email_send.php", 
                dataType: 'json',
                data: 'username='+name+'&useremail='+email+'&message='+message,
                beforeSend: function() {
                    $('#submit').attr('disabled', true);
                    $('#submit').after('<span class="wait">&nbsp;<img src="image/loading.gif" alt="" /></span>');
                },
                complete: function() {
                    $('#submit').attr('disabled', false);
                    $('.wait').remove();
                },  
                success: function(data)
                {
                    if(data.type == 'error')
                    {
                        output = '<div class="error">'+data.text+'</div>';
                    }else{
                        output = '<div class="success">'+data.text+'</div>';
                        $('input[type=text]').val(''); 
                        $('#contactform textarea').val(''); 
                    }
    
                    $("#result").hide().html(output).slideDown();           
                    }
            });
        }
    });
    //reset previously set border colors and hide all message on .keyup()
    $("#contactform input, #contactform textarea").keyup(function() { 
        $("#contactform input, #contactform textarea").css('border-color',''); 
        $("#result").slideUp();
    });
    

    HTML 양식

    <div  class="cover">
    <div id="result"></div>
    <div id="contactform">
        <p class="contact"><label for="name">Name</label></p>
        <input id="name" name="name" placeholder="Yourname" type="text">
    
        <p class="contact"><label for="email">Email</label></p>
        <input id="email" name="email" placeholder="admin@admin.com" type="text">
    
        <p class="contact"><label for="comment">Your Message</label></p>
        <textarea name="comment" id="comment" tabindex="4"></textarea> <br>
        <input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
    </div>
    

    PHP 코드

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    //check if its an ajax request, exit if not
    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    
        //exit script outputting json data
        $output = json_encode(
                array(
                    'type' => 'error',
                    'text' => 'Request must come from Ajax'
        ));
    
        die($output);
    }
    
    //check $_POST vars are set, exit if any missing
    if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) {
        $output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
        die($output);
    }
    
    //Sanitize input data using PHP filter_var().
    $username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
    $useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
    $message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);
    
    //additional php validation
    if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error.
        $output = json_encode(array('type' => 'error', 'text' => 'Name is too short!'));
        die($output);
    }
    if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation
        $output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
        die($output);
    }
    if (strlen($message) < 5) { //check emtpy message
        $output = json_encode(array('type' => 'error', 'text' => 'Too short message!'));
        die($output);
    }
    
    $to = "info@wearecoders.net"; //Replace with recipient email address
    //proceed with PHP email.
    $headers = 'From: ' . $useremail . '' . "\r\n" .
            'Reply-To: ' . $useremail . '' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();
    
    $sentMail = @mail($to, $subject, $message . '  -' . $username, $headers);
    //$sentMail = true;
    if (!$sentMail) {
        $output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.'));
        die($output);
    } else {
        $output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email'));
        die($output);
    }
    

    이 페이지는 간단한 예제를 가지고 http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/


  5. 5.여기에 jQuery를위한 좋은 플러그인입니다 아약스를 통해을 제출 양식이 :

    여기에 jQuery를위한 좋은 플러그인입니다 아약스를 통해을 제출 양식이 :

    http://malsup.com/jquery/form/

    그것으로 간단하게 :

    <script src="http://malsup.github.com/jquery.form.js"></script> 
    <script> 
        $(document).ready(function() { 
            $('#myForm').ajaxForm(function() { 
               alert('form was submitted');
            }); 
        }); 
    </script> 
    

    이 포스트 위치에 대한 양식 동작을 사용합니다. 회원님이 자신의 코드에 이것을 달성 할 수 있지만,이 플러그인 나를 위해 매우 잘 작동했다고!


  6. 6.TYPE = "버튼"

    TYPE = "버튼"

    해야한다

    type="submit"
    

  7. 7.이벤트 처리에서는, 함수에 이벤트 객체를 전달하고 문을 추가 즉 에서는 event.preventDefault ();

    이벤트 처리에서는, 함수에 이벤트 객체를 전달하고 문을 추가 즉 에서는 event.preventDefault ();

    이것은 새로 고침없이 웹 페이지에 데이터를 전달합니다.


  8. 8.

    $(document).ready(function(){
    $('#userForm').on('submit', function(e){
            e.preventDefault();
    //I had an issue that the forms were submitted in geometrical progression after the next submit. 
    // This solved the problem.
            e.stopImmediatePropagation();
        // show that something is loading
        $('#response').html("<b>Loading data...</b>");
    
        // Call ajax for pass data to other place
        $.ajax({
        type: 'POST',
        url: 'somephpfile.php',
        data: $(this).serialize() // getting filed value in serialize form
        })
        .done(function(data){ // if getting done then call.
    
        // show the response
        $('#response').html(data);
    
        })
        .fail(function() { // if fail then getting message
    
        // just in case posting your form failed
        alert( "Posting failed." );
    
        });
    
        // to prevent refreshing the whole page page
        return false;
    
        });
    

  9. 9.

    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript" >
      $(function () {
        $(".submit").click(function (event) {
          var time = $("#time").val();
          var date = $("#date").val();
          var dataString = 'time=' + time + '&date=' + date;
          console.log(dataString);
          if (time == '' || date == '')
          {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show();
          } else
          {
            $.ajax({
              type: "POST",
              url: "post.php",
              data: dataString,
              success: function (data) {
                $('.success').fadeIn(200).show();
                $('.error').fadeOut(200).hide();
                $("#data").html(data);
              }
            });
          }
          event.preventDefault();
        });
      });
    </script>
    <form action="post.php" method="POST">
      <input id="time" value=""><br>
      <input id="date" value=""><br>
      <input name="submit" type="button" value="Submit" class="submit">
    </form>
    <div id="data"></div>
    <span class="error" style="display:none"> Please Enter Valid Data</span>
    <span class="success" style="display:none"> Form Submitted Success</span>
    
    <?php
    
    print_r($_POST);
    if ($_POST['date']) {
      $date = $_POST['date'];
      $time = $_POST['time'];
      echo '<h1>' . $date . '---' . $time . '</h1>';
    }
    else {
    
    }
    ?>
    

  10. 10.

    <div class="container">
           <div class="row">
            <div class="col-md-3 col-sm-6 col-xs-12"></div>enter code here
              <div class="col-md-6 col-sm-6 col-xs-12">
              <div class="msg"></div>
                <form method="post" class="frm" id="form1" onsubmit="">
                   <div class="form-group">
                   <input type="text" class="form-control" name="fname" id="fname" placeholder="enter your first neme" required>
               <!--><span class="sp"><?php// echo $f_err;?></span><!-->
              </div>
            <div class="form-group">
                   <input type="text" class="form-control" name="lname" id="lname" placeholder="enter your last neme" required>
                  <!--><span class="sp"><?php// echo $l_err;?></span><!-->
                 </div>
                  <div class="form-group">
                   <input type="text" class="form-control" name="email" id="email" placeholder="enter your email Address" required>
                  <!--><span class="sp"><?php// echo $e_err;?></span><!-->
                 </div>
                 <div class="form-group">
                   <input type="number" class="form-control" name="mno" id="mno" placeholder="enter your mobile number" required>
                  <!--><span class="sp"><?php //echo $m_err;?></span><!-->
                 </div>
                  <div class="form-group">
                   <input type="password" class="form-control" name="pass" id="pass" pattern="(?=.*[a-z])(?=.*[A-Z]).{4,8}" placeholder="enter your Password" required>
                  <!--><span class="sp"><?php //echo $p_err;?></span><!-->
                 </div>
                  <div class="radio">
                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="male" name="gender" id="gender" checked>male<br>
                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="female" name="gender" id="gender">female<br>
                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="other" name="gender" id="gender">other<br>
                                             <!--><span class="sp"> <?php //echo $r_err;?></span><!-->
                 </div>
                    <div class="checkbox">
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" name="check" id="check" checked>I Agree Turms&Condition<br>
                       <!--><span class="sp"> <?php //echo $c_err;?></span><!-->
                     </div>
                     <input type="submit"  class="btn btn-warning" name="submit" id="submit">
                 </form>enter code here
    
              </div>
                   <div class="col-md-3 col-sm-6 col-xs-12"></div>
             </div> 
    
        </div>
    
  11. from https://stackoverflow.com/questions/16616250/form-submit-with-ajax-passing-form-data-to-php-without-page-refresh by cc-by-sa and MIT license