복붙노트

PHP로 jQuery Ajax POST 예제

PHP

PHP로 jQuery Ajax POST 예제

양식에서 데이터베이스로 데이터를 보내려고합니다. 여기에 제가 사용하는 양식이 있습니다 :

<form name="foo" action="form.php" method="POST" id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

일반적인 접근 방식은 양식을 제출하는 것이지만 브라우저가 리디렉션됩니다. jQuery와 Ajax를 사용하면 양식의 모든 데이터를 캡처하여 PHP 스크립트 (예 : form.php)에 제출할 수 있습니까?

해결법

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

    1.

    .ajax의 기본 사용법은 다음과 같습니다.

    HTML :

    <form id="foo">
        <label for="bar">A bar</label>
        <input id="bar" name="bar" type="text" value="" />
    
        <input type="submit" value="Send" />
    </form>
    

    JQuery :

    // Variable to hold request
    var request;
    
    // Bind to the submit event of our form
    $("#foo").submit(function(event){
    
        // Prevent default posting of form - put here to work in case of errors
        event.preventDefault();
    
        // Abort any pending request
        if (request) {
            request.abort();
        }
        // setup some local variables
        var $form = $(this);
    
        // Let's select and cache all the fields
        var $inputs = $form.find("input, select, button, textarea");
    
        // Serialize the data in the form
        var serializedData = $form.serialize();
    
        // Let's disable the inputs for the duration of the Ajax request.
        // Note: we disable elements AFTER the form data has been serialized.
        // Disabled form elements will not be serialized.
        $inputs.prop("disabled", true);
    
        // Fire off the request to /form.php
        request = $.ajax({
            url: "/form.php",
            type: "post",
            data: serializedData
        });
    
        // Callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it worked!");
        });
    
        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );
        });
    
        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });
    
    });
    

    참고 : jQuery 1.8 이후 .success (), .error () 및 .complete ()는 .done (), .fail () 및 .always ()를 사용하지 않으므로 사용되지 않습니다.

    참고 : 위의 스 니펫은 DOM 준비가 완료된 후에 수행해야하므로 $ (document) .ready () 핸들러에 넣거나 $ () 단축키를 사용해야합니다.

    팁 : 다음과 같이 콜백 핸들러를 연결할 수 있습니다. $ .ajax (). done (). fail (). always ();

    PHP (즉, form.php) :

    // You can access the values posted by jQuery.ajax
    // through the global variable $_POST, like this:
    $bar = isset($_POST['bar']) ? $_POST['bar'] : null;
    

    참고 : 주입 및 기타 악성 코드를 막기 위해 게시 된 데이터를 항상 위생적으로 처리하십시오.

    위의 JavaScript 코드에서 .ajax 대신 짧은 .post를 사용할 수도 있습니다.

    $.post('/form.php', serializedData, function(response) {
        // Log the response to the console
        console.log("Response: "+response);
    });
    

    참고 : 위의 JavaScript 코드는 jQuery 1.8 이상에서 작동하지만 jQuery 1.5 이전 버전에서 작동합니다.

  2. ==============================

    2.

    jQuery를 사용하여 아약스 요청을하려면 다음 코드를 수행하면된다.

    HTML :

    <form id="foo">
        <label for="bar">A bar</label>
        <input id="bar" name="bar" type="text" value="" />
        <input type="submit" value="Send" />
    </form>
    
    <!-- The result of the search will be rendered inside this div -->
    <div id="result"></div>
    

    자바 스크립트 :

    방법 1

     /* Get from elements values */
     var values = $(this).serialize();
    
     $.ajax({
            url: "test.php",
            type: "post",
            data: values ,
            success: function (response) {
               // you will get response from your php page (what you echo or print)                 
    
            },
            error: function(jqXHR, textStatus, errorThrown) {
               console.log(textStatus, errorThrown);
            }
    
    
        });
    

    방법 2

    /* Attach a submit handler to the form */
    $("#foo").submit(function(event) {
         var ajaxRequest;
    
        /* Stop form from submitting normally */
        event.preventDefault();
    
        /* Clear result div*/
        $("#result").html('');
    
        /* Get from elements values */
        var values = $(this).serialize();
    
        /* Send the data using post and put the results in a div */
        /* I am not aborting previous request because It's an asynchronous request, meaning 
           Once it's sent it's out there. but in case you want to abort it  you can do it by  
           abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */
           ajaxRequest= $.ajax({
                url: "test.php",
                type: "post",
                data: values
            });
    
          /*  request cab be abort by ajaxRequest.abort() */
    
         ajaxRequest.done(function (response, textStatus, jqXHR){
              // show successfully for submit message
              $("#result").html('Submitted successfully');
         });
    
         /* On failure of request this function will be called  */
         ajaxRequest.fail(function (){
    
           // show error
           $("#result").html('There is error while submit');
         });
    

    .success (), .error () 및 .complete () 콜백은 jQuery 1.8부터 사용되지 않습니다. 최종 제거를위한 코드를 준비하려면 대신 .done (), .fail () 및 .always ()를 사용하십시오.

    MDN : abort (). 요청이 이미 전송 된 경우이 메소드는 요청을 중단합니다.

    그래서 우리는 이제 서버에 데이터를 가져올 시간을 아약스 요청에 성공적으로 보냈습니다.

    PHP

    ajax 호출 (POST : "post")에서 POST 요청을하면 $ _REQUEST 또는 $ _POST를 사용하여 데이터를 가져올 수 있습니다

      $bar = $_POST['bar']
    

    당신은 또한 POST 요청에서 무엇을 얻을 수 있는지 간단히 알 수 있습니다. Btw는 $ _POST가 잘못 설정된 다른 설정으로되어 있는지 확인하십시오.

    var_dump($_POST);
    // or
    print_r($_POST);
    

    그리고 데이터베이스에 값을 삽입하여 쿼리를 만들기 전에 모든 요청 (GET 또는 POST 한 날씨)을 적절히 감추고 있는지 확인하십시오. Best는 준비된 명령문을 사용합니다.

    어떤 데이터를 페이지로 되돌리려면 다음과 같이 해당 데이터를 반향함으로써 수행 할 수 있습니다.

    // 1. Without JSON
       echo "hello this is one"
    
    // 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
    echo json_encode(array('returned_val' => 'yoho'));
    

    그리고 당신이 그것을 얻을 수있는 것보다

     ajaxRequest.done(function (response){  
        alert(response);
     });
    

    동일한 작업을 수행하는 코드 아래에서 사용할 수있는 몇 가지 속기 방법이 있습니다.

    var ajaxRequest= $.post( "test.php",values, function(data) {
      alert( data );
    })
      .fail(function() {
        alert( "error" );
      })
      .always(function() {
        alert( "finished" );
    });
    
  3. ==============================

    3.

    오류가 발생했을 때 PHP + Ajax를 사용하여 게시하는 방법을 자세히 설명하고 싶습니다.

    먼저 form.php와 process.php와 같은 두 개의 파일을 만듭니다.

    먼저 jQuery .ajax () 메소드를 사용하여 제출할 양식을 작성합니다. 나머지는 주석에서 설명 할 것입니다.

    form.php

    <form method="post" name="postForm">
        <ul>
            <li>
                <label>Name</label>
                <input type="text" name="name" id="name" placeholder="Bruce Wayne">
                <span class="throw_error"></span>
                <span id="success"></span>
           </li>
       </ul>
       <input type="submit" value="Send" />
    </form>
    

    jQuery 클라이언트 측 유효성 검사를 사용하여 양식의 유효성을 검사하고 데이터를 process.php로 전달하십시오.

    $(document).ready(function() {
        $('form').submit(function(event) { //Trigger on form submit
            $('#name + .throw_error').empty(); //Clear the messages first
            $('#success').empty();
    
            //Validate fields if required using jQuery
    
            var postForm = { //Fetch form data
                'name'     : $('input[name=name]').val() //Store name fields value
            };
    
            $.ajax({ //Process the form using $.ajax()
                type      : 'POST', //Method type
                url       : 'process.php', //Your form processing file URL
                data      : postForm, //Forms name
                dataType  : 'json',
                success   : function(data) {
                                if (!data.success) { //If fails
                                    if (data.errors.name) { //Returned if any error from process.php
                                        $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
                                    }
                                }
                                else {
                                        $('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
                                    }
                                }
            });
            event.preventDefault(); //Prevent the default submit
        });
    });
    

    이제 우리는 process.php를 살펴볼 것입니다.

    $errors = array(); //To store errors
    $form_data = array(); //Pass back the data to `form.php`
    
    /* Validate the form on the server side */
    if (empty($_POST['name'])) { //Name cannot be empty
        $errors['name'] = 'Name cannot be blank';
    }
    
    if (!empty($errors)) { //If errors in validation
        $form_data['success'] = false;
        $form_data['errors']  = $errors;
    }
    else { //If not, process the form, and return true on success
        $form_data['success'] = true;
        $form_data['posted'] = 'Data Was Posted Successfully';
    }
    
    //Return the data back to form.php
    echo json_encode($form_data);
    

    프로젝트 파일은 http://projects.decodingweb.com/simple_ajax_form.zip에서 다운로드 할 수 있습니다.

  4. ==============================

    4.

    serialize를 사용할 수 있습니다. 아래는 그 예입니다.

    $("#submit_btn").click(function(){
        $('.error_status').html();
            if($("form#frm_message_board").valid())
            {
                $.ajax({
                    type: "POST",
                    url: "<?php echo site_url('message_board/add');?>",
                    data: $('#frm_message_board').serialize(),
                    success: function(msg) {
                        var msg = $.parseJSON(msg);
                        if(msg.success=='yes')
                        {
                            return true;
                        }
                        else
                        {
                            alert('Server error');
                            return false;
                        }
                    }
                });
            }
            return false;
        });
    
  5. ==============================

    5.

    HTML :

        <form name="foo" action="form.php" method="POST" id="foo">
            <label for="bar">A bar</label>
            <input id="bar" class="inputs" name="bar" type="text" value="" />
            <input type="submit" value="Send" onclick="submitform(); return false;" />
        </form>
    

    자바 스크립트 :

       function submitform()
       {
           var inputs = document.getElementsByClassName("inputs");
           var formdata = new FormData();
           for(var i=0; i<inputs.length; i++)
           {
               formdata.append(inputs[i].name, inputs[i].value);
           }
           var xmlhttp;
           if(window.XMLHttpRequest)
           {
               xmlhttp = new XMLHttpRequest;
           }
           else
           {
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
           }
           xmlhttp.onreadystatechange = function()
           {
              if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
              {
    
              }
           }
           xmlhttp.open("POST", "insert.php");
           xmlhttp.send(formdata);
       }
    
  6. ==============================

    6.

    이 방법을 사용합니다. 파일과 같은 모든 것을 제출합니다.

    $(document).on("submit", "form", function(event)
    {
        event.preventDefault();
    
        var url=$(this).attr("action");
        $.ajax({
            url: url,
            type: 'POST',
            dataType: "JSON",
            data: new FormData(this),
            processData: false,
            contentType: false,
            success: function (data, status)
            {
    
            },
            error: function (xhr, desc, err)
            {
                console.log("error");
    
            }
        });        
    
    });
    
  7. ==============================

    7.

    <script src="http://code.jquery.com/jquery-1.7.2.js"></script>
    <form method="post" id="form_content" action="Javascript:void(0);">
        <button id="desc" name="desc" value="desc" style="display:none;">desc</button>
        <button id="asc" name="asc"  value="asc">asc</button>
        <input type='hidden' id='check' value=''/>
    </form>
    
    <div id="demoajax"></div>
    
    <script>
        numbers = '';
        $('#form_content button').click(function(){
            $('#form_content button').toggle();
            numbers = this.id;
            function_two(numbers);
        });
    
        function function_two(numbers){
            if (numbers === '')
            {
                $('#check').val("asc");
            }
            else
            {
                $('#check').val(numbers);
            }
            //alert(sort_var);
    
            $.ajax({
                url: 'test.php',
                type: 'POST',
                data: $('#form_content').serialize(),
                success: function(data){
                    $('#demoajax').show();
                    $('#demoajax').html(data);
                    }
            });
    
            return false;
        }
        $(document).ready(function_two());
    </script>
    
  8. ==============================

    8.

    예:

    <script>
        $(document).ready(function () {
            $("#btnSend").click(function () {
                $.ajax({
                    url: 'process.php',
                    type: 'POST',
                    data: {bar: $("#bar").val()},
                    success: function (result) {
                        alert('success');
                    }
                });
            });
        });
    </script>
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input id="btnSend" type="button" value="Send" />
    
  9. ==============================

    9.

    나는 문제없이 수년간이 간단한 한 줄 코드를 사용하고있다. (jquery가 필요합니다)

    <script type="text/javascript">
    function ap(x,y) {$("#" + y).load(x);};
    function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
    </script>
    

    여기서 ap ()는 ajax 페이지를 의미하고 af ()는 ajax 양식을 의미합니다. 폼에서 단순히 af () 함수를 호출하면 url에 양식을 게시하고 원하는 html 요소에 대한 응답을로드합니다.

    <form>
    ...
    <input type="button" onclick="af('http://example.com','load_response')"/>
    </form>
    <div id="load_response">this is where response will be loaded</div>
    
  10. ==============================

    10.

    제출하기 전에 아약스 오류 및 로더를 처리하고 성공을 표시 한 후 예를 들어 경보 부트 상자 표시 :

    var formData = formData;
    
    $.ajax({
        type: "POST",
        url: url,
        async: false,
        data: formData, //only input
        processData: false,
        contentType: false,
        xhr: function ()
        {
            $("#load_consulting").show();
            var xhr = new window.XMLHttpRequest();
            //Upload progress
            xhr.upload.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {
                    var percentComplete = (evt.loaded / evt.total) * 100;
                    $('#addLoad .progress-bar').css('width', percentComplete + '%');
                }
            }, false);
            //Download progress
            xhr.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                }
            }, false);
            return xhr;
        },
        beforeSend: function (xhr) {
            qyuraLoader.startLoader();
        },
        success: function (response, textStatus, jqXHR) {
            qyuraLoader.stopLoader();
            try {
                $("#load_consulting").hide();
    
                var data = $.parseJSON(response);
                if (data.status == 0)
                {
                    if (data.isAlive)
                    {
                        $('#addLoad .progress-bar').css('width', '00%');
                        console.log(data.errors);
                        $.each(data.errors, function (index, value) {
                            if (typeof data.custom == 'undefined') {
                                $('#err_' + index).html(value);
                            }
                            else
                            {
                                $('#err_' + index).addClass('error');
    
                                if (index == 'TopError')
                                {
                                    $('#er_' + index).html(value);
                                }
                                else {
                                    $('#er_TopError').append('<p>' + value + '</p>');
                                }
                            }
    
                        });
                        if (data.errors.TopError) {
                            $('#er_TopError').show();
                            $('#er_TopError').html(data.errors.TopError);
                            setTimeout(function () {
                                $('#er_TopError').hide(5000);
                                $('#er_TopError').html('');
                            }, 5000);
                        }
                    }
                    else
                    {
                        $('#headLogin').html(data.loginMod);
                    }
                } else {
                    //document.getElementById("setData").reset();
                    $('#myModal').modal('hide');
                    $('#successTop').show();
                    $('#successTop').html(data.msg);
                    if (data.msg != '' && data.msg != "undefined") {
    
                        bootbox.alert({closeButton: false, message: data.msg, callback: function () {
                                if (data.url) {
                                    window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                                } else {
                                    location.reload(true);
                                }
                            }});
                    } else {
    
                        bootbox.alert({closeButton: false, message: "Success", callback: function () {
                                if (data.url) {
                                    window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                                } else {
                                    location.reload(true);
                                }
                            }});
                    }
    
                }
            } catch (e) {
                if (e) {
                    $('#er_TopError').show();
                    $('#er_TopError').html(e);
                    setTimeout(function () {
                        $('#er_TopError').hide(5000);
                        $('#er_TopError').html('');
                    }, 5000);
                }
            }
        }
    });
    
  11. ==============================

    11.

    안녕하세요, 아약스 요청 코드 전체를 확인하십시오.

            $('#foo').submit(function(event) {
            // get the form data
            // there are many ways to get this data using jQuery (you can use the 
        class or id also)
        var formData = $('#foo').serialize();
        var url ='url of the request';
        // process the form.
    
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use
            url         : 'url/', // the url where we want to POST
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back.
            beforeSend : function() {
            //this will run before sending an ajax request do what ever activity 
             you want like show loaded 
             },
            success:function(response){
                var obj = eval(response);
                if(obj)
                {  
                    if(obj.error==0){
                    alert('success');
                    }
                else{  
                    alert('error');
                    }   
                }
            },
            complete : function() {
               //this will run after sending an ajax complete                   
                        },
            error:function (xhr, ajaxOptions, thrownError){ 
              alert('error occured');
            // if any error occurs in request 
            } 
        });
        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });
    
  12. from https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php by cc-by-sa and MIT lisence