PHP를 이용한 jQuery Ajax POST 예제 같습니다. <form name=”foo”

양식에서 데이터베이스로 데이터를 보내려고합니다. 사용중인 양식은 다음과 같습니다.

<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 )에 제출할 수 있습니까?



답변

기본 사용법은 .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 코드 .post대신 속기 를 사용할 수도 있습니다 .ajax.

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

참고 : 위 JavaScript 코드는 jQuery 1.8 이상에서 작동하도록 만들어졌지만 이전 버전에서는 jQuery 1.5까지 작동해야합니다.


답변

jQuery 를 사용하여 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>

<!-- 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 the 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 can be aborted 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(). 요청이 이미 전송 된 경우이 메소드는 요청을 중단합니다.

이제 Ajax 요청을 성공적으로 보냈으며 이제 서버로 데이터를 가져갈 차례입니다.

PHP

우리는 Ajax 호출 (에서 POST 요청을 따라 type: "post"), 우리는 지금 잡아 데이터 중 하나를 사용 할 수 있습니다 $_REQUEST또는 $_POST:

  $bar = $_POST['bar']

POST 요청에서 얻는 것을 간단히 볼 수도 있습니다. BTW, 설정되어 있는지 확인하십시오 $_POST. 그렇지 않으면 오류가 발생합니다.

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

그리고 당신은 데이터베이스에 값을 삽입하고 있습니다. 조회를 작성하기 전에 모든 요청 (GET 또는 POST를 작성했는지 여부)을 올바르게 감지 하거나 이스케이프 했는지 확인하십시오 . 가장 좋은 것은 준비된 진술을 사용하는 것 입니다.

그리고 데이터를 다시 페이지로 되돌리려면 아래와 같이 해당 데이터를 에코하면됩니다.

// 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");
});


답변

PHP + Ajax로 게시하는 방법과 실패시 다시 발생하는 오류에 대한 자세한 방법을 공유하고 싶습니다.

우선, 예를 들어 form.php및과 같이 두 개의 파일을 만듭니다 process.php.

먼저을 만들어서 메소드를 form사용하여 제출합니다 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 에서 다운로드 할 수 있습니다 .


답변

직렬화를 사용할 수 있습니다. 아래는 예입니다.

$("#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;
    });


답변

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);
   }


답변

아래 표시된 방법을 사용합니다. 파일과 같은 모든 것을 제출합니다.

$(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");
        }
    });
});


답변

jQuery Ajax를 사용하여 데이터를 보내려면 양식 태그와 제출 버튼이 필요하지 않습니다.

예:

<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" />