복붙노트

아약스와 PHP는 데이터베이스에 여러 양식 입력 입력

PHP

아약스와 PHP는 데이터베이스에 여러 양식 입력 입력

나는 사용자 선택에 의해 결정되는 다수의 입력 필드를 가진 PHP 생성 폼을 가지고있다. 모든 데이터를 데이터베이스에 입력하려면 ajax 함수를 사용하고 싶습니다. 문제는 내가 아약스를 처음 접했을 때 호에 대해 잘 모르겠다는 것입니다. 아래의 ajax javascript 함수는 내가 성취하고자하는 샘플이며 올바른 것은 아니라는 것을 알고 있습니다. 누군가가 올바른 방향으로 나를 가리킬 수 있습니까? 나는 주변을 둘러 보았다. Json은 해결책이 될지 모르지만 나는 그것에 대해 아무것도 모르고 그것에 대해 읽고 난 여전히 이해하지 못한다.

샘플 아약스 :

function MyFunction(){

var i = 1;
var x = $('#num_to_enter').val();
   while (i <= x){
    var name = $('#fname[i]').val();
    var lname = $('#lname[i]').val();
    var email = $('#Email[i]').val();
    i++;
 }
    $('#SuccessDiv').html('Entering Info.<img src="images/processing.gif" />');
     $.ajax({url : 'process.php',
    type:"POST",
   while (i <= x){
    data: "fname[i]=" + name[i] + "&lname[i]=" + lname[i] + "&email[i]=" + email[i],
    i++;
 }
     success : function(data){
    window.setTimeout(function()
    {
    $('#SuccessDiv').html('Info Added!');
    $('#data').css("display","block");
    $('#data').html(data);
    }, 2000);
        }
});
        return false;
          }

양식 샘플 :

<?php

   echo "<form method='post'>";

   $i=1;

    while($i <= $num_to_enter){

    $form_output .= "First Name:

    <input id='fname' type='text' name='fname[$i]'><br />

     Last Name:

    <input id='lname' type='text' name='lname[$i]'><br />

    Email:

    <input id='Email' type='text' name='Email[$i]'><br />

    $i++;

   }

   echo"<input type='button' value='SUBMIT' onClick='MyFunction()'></form>";

   ?>

Then DB MySQL Sample


   <?php
       while ($i <= $x){

    $x = $_POST['num_to_enter'];
    $fname = $_POST['fname[$i]'];
    $fname = $_POST['fname[$i]'];
    $fname = $_POST['email[$i]'];

        $sql = "INSERT INTO `mytable` 
    (`firstname`, `lastname`, `email`) VALUES ('$fname[$i]', '$lname[$i]', '$email[$i]');";

    $i++;

    }

   ?>

해결법

  1. ==============================

    1.다음은 AJAX의 간단한 데모입니다.

    다음은 AJAX의 간단한 데모입니다.

    HTML

    <form method="POST" action="process.php" id="my_form">
        <input type="text" name="firstname[]">
        <input type="text" name="firstname[]">
        <input type="text" name="firstname[]">
        <input type="text" name="firstname[custom1]">
        <input type="text" name="firstname[custom2]">
        <br><br>
        <input type="submit" value="Submit">
    </form>
    

    jQuery

    // listen for user to SUBMIT the form
    $(document).on('submit', '#my_form', function(e){
    
        // do not allow native browser submit process to proceed
        e.preventDefault();
    
        // AJAX yay!
        $.ajax({
            url: $(this).attr('action') // <- find process.php from action attribute
            ,async: true // <- don't hold things up
            ,cache: false // <- don't let cache issues haunt you
            ,type: $(this).attr('method') // <- find POST from method attribute
            ,data: $(this).serialize() // <- create the object to be POSTed to process.php
            ,dataType: 'json' // <- we expect JSON from the PHP file
            ,success: function(data){
    
                // Server responded with a 200 code
    
                // data is a JSON object so treat it as such
                // un-comment below for debuggin goodness
                // console.log(data);
    
                if(data.success == 'yes'){
                    alert('yay!');
                }
                else{
                    alert('insert failed!');
                }
            }
            ,error: function(){
                // There was an error such as the server returning a 404 or 500
                // or maybe the URL is not reachable
            }
            ,complete: function(){
                // Always perform this action after success() and error()
                // have been called
            }
        });
    });
    

    PHP process.php

    <?php
    /**************************************************/
    /* Uncommenting in here will break the AJAX call */
    /* Don't use AJAX and just submit the form normally to see this in action */
    
    // see all your POST data
    // echo '<pre>'.print_r($_POST, true).'</pre>';
    
    // see the first names only
    // echo $_POST['firstname'][0];
    // echo $_POST['firstname'][1];
    // echo $_POST['firstname'][2];
    // echo $_POST['firstname']['custom1'];
    // echo $_POST['firstname']['custom2'];
    
    /**************************************************/
    
    // some logic for sql insert, you can do this part
    
    if($sql_logic == 'success'){
    
        // give JSON back to AJAX call
        echo json_encode(array('success'=>'yes'));
    }
    else{
    
        // give JSON back to AJAX call
        echo json_encode(array('success'=>'no'));
    }
    ?>
    
  2. ==============================

    2.

    var postdata={};
    postdata['num']=x;
       while (i <= x){
        postdata['fname'+i]= name[i];
        postdata['lname'+i]= lname[i];
        postdata['email'+i]= email[i];
    
        i++;
    }
     $.ajax({url : 'process.php',
        type:"POST",
        data:postdata,
        success : function(data){
        window.setTimeout(function()
        {
        $('#SuccessDiv').html('Info Added!');
        $('#data').css("display","block");
        $('#data').html(data);
        }, 2000);
            }
    });
    

    PHP

    $num=$_POST['num'];
    for($i=1;i<=$num;i++)
    {
     echo $_POST['fname'.$i];
     echo $_POST['lname'.$i];
     echo $_POST['email'.$i];
    }
    
  3. from https://stackoverflow.com/questions/20150130/ajax-and-php-to-enter-multiple-forms-input-to-database by cc-by-sa and MIT license