2011-02-15 101 views
533

我想從表單發送數據到數據庫。這裏是我正在使用的表格:jQuery Ajax POST示例與PHP

<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)?

+3

請參閱[相關元討論](http://meta.stackexchange.com/q/161943/147191)推斷undeletion背後的推理。 – TRiG 2013-01-08 13:14:16

+0

最佳答案在這裏: http://stackoverflow.com/questions/19029703/jquery-using-ajax-to-send-data-and-save-in-php/19029778#19029778 檢查,測試工作 – rohitcopyright 2013-09-26 16:16:18

回答

816

.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()處理器中(或使用$()簡寫)。

提示:您可以chain回調處理程序是這樣的:$.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; 

注:始終sanitize posted data,防止注射和其他惡意代碼。

您也可以使用速記.post代替.ajax在上面的JavaScript代碼:

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

注:以上JavaScript代碼是由與jQuery 1.8和更高版本中運行,但它應該工作與以前的版本一直到jQuery 1.5。

+0

我可以做些什麼;)但是,form/php代碼應該怎麼樣? – Thew 2011-02-15 13:34:18

+3

編輯你的答案以解決一個錯誤:`request`被聲明爲一個局部變量var'if(request)request.abort();`永遠不會工作。 – 2013-06-05 06:44:33

+0

不應該`serializedData`是`$ inputs.serialize()`,還是有原因序列化並提交整個表單? – 2013-08-04 23:07:53

174

要使用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> 

的JavaScript:

方法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()。如果請求已經發送,則此方法將中止請求。

所以我們現在已經成功地發送ajax請求來抓取數據到服務器。

PHP

正如我們使AJAX調用(type: "post")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); 
}); 

還有的Shorthand Methods夫婦可以使用下面的代碼它做同樣的工作。

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

您可以使用序列化。下面是一個例子。

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

我想分享如何使用PHP + Ajax發佈的詳細方法以及失敗時拋出的錯誤。

首先,創建兩個文件,例如form.phpprocess.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> 
     </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下載。

8
<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> 
18

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> 

的JavaScript

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

我用這個way.It提交一切都像文件

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

     } 
    });   

}); 
2

我正在使用這個簡單的一行代碼多年沒有問題。 (它需要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> 
2
handling ajax error and loader before submit and after submit success show alert bootbox with example: 
    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); 
       } 
      } 
     } 
    }); 
3

如果你想使用jQuery阿賈克斯則沒有必要表單標籤的發送數據,並提交按鈕

例子:

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

嗨,請檢查這是完成e ajax請求代碼。

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