使用PHP的jQuery Ajax POST示例

时间:2011-02-15 13:28:57

标签: php javascript 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 )?

17 个答案:

答案 0 :(得分:891)

.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()和{{1} }。

注意:请记住上述代码段必须在DOM准备好后完成,因此您应该将其放在$(document).ready()处理程序中(或使用.always()简写)。

提示:您可以chain这样的回调处理程序:$()

PHP(即form.php):

$.ajax().done().fail().always();

注意:始终sanitize posted data,以防止注入和其他恶意代码。

您也可以在上面的JavaScript代码中使用简写.post代替// You can access the values posted by jQuery.ajax // through the global variable $_POST, like this: $bar = isset($_POST['bar']) ? $_POST['bar'] : null;

.ajax

注意:上面的JavaScript代码适用于jQuery 1.8及更高版本,但它应该适用于以前的版本,直到jQuery 1.5。

答案 1 :(得分:197)

要使用 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');
     });

jQuery 1.8 开始,不推荐使用.success().error().complete()回调。要准备最终删除的代码,请改用.done().fail().always()

MDN: abort()。如果已经发送了请求,则此方法将中止请求。

所以我们现在已成功发送ajax请求,以便将数据提取到服务器。

<强> PHP

当我们在ajax调用(type: "post")中发出POST请求时,我们现在可以使用$_REQUEST$_POST

来获取数据
  $bar = $_POST['bar']

您也可以通过以下方式查看POST请求中的内容,顺便说一下,确保$ _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);
 });

有几个Shorthand Methods你可以在代码下面使用它做同样的工作。

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

答案 2 :(得分:48)

我想分享一个详细的方法,了解如何使用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> <span id="success"></span> </li> </ul> <input type="submit" value="Send" /> </form>

process.php


使用jQuery客户端验证验证表单,并将数据传递给$(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);

{{1}}

项目文件可以从http://projects.decodingweb.com/simple_ajax_form.zip下载。

答案 3 :(得分:26)

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

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

答案 4 :(得分:20)

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

答案 5 :(得分:16)

我用这种方式。它提交所有文件

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

        }
    });        

});

答案 6 :(得分:9)

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

答案 7 :(得分:9)

  

如果你想使用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" />

答案 8 :(得分:4)

在提交之前和提交成功显示警告引导框之后处理ajax错误和加载器,并带有一个示例:

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

答案 9 :(得分:3)

我使用这个简单的一行代码多年没有问题。 (它需要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 :(得分:1)

嗨,请检查这是完整的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();
});

答案 11 :(得分:1)

由于Fetch API的引入,现在真的没有理由再使用jQuery Ajax或XMLHttpRequests了。要将表单数据发布到原始JavaScript中的PHP脚本中,您可以执行以下操作:

function postData() {
    const form = document.getElementById('form');
    const data = new FormData();
    data.append('name', form.name.value);

    fetch('../php/contact.php', {method: 'POST', body: data}).then(response => {
        if (!response.ok){
            throw new Error('Network response was not ok.');
        }
    }).catch(err => console.log(err));
}
<form id="form" action="javascript:postData()">
    <input id="name" name="name" placeholder="Name" type="text" required>
    <input type="submit" value="Submit">
</form>

这是一个PHP脚本的非常基本的示例,该脚本获取数据并发送电子邮件:

<?php
    header('Content-type: text/html; charset=utf-8');

    if (isset($_POST['name'])) {
        $name = $_POST['name'];
    }

    $to = "test@example.com";
    $subject = "New name submitted";
    $body = "You received the following name: $name";

    mail($to, $subject, $body);

答案 12 :(得分:1)

在您的php文件中输入:

$content_raw = file_get_contents("php://input"); // THIS IS WHAT YOU NEED
$decoded_data = json_decode($content_raw, true); // THIS IS WHAT YOU NEED
$bar = $decoded_data['bar']; // THIS IS WHAT YOU NEED
$time = $decoded_data['time'];
$hash = $hash_data['hash'];
echo "You have sent a POST request containing the bar variable with the value $bar";

并在您的js文件中发送带有数据对象的ajax

var data = { 
    bar : 'bar value',
    time: calculatedTimeStamp,
    hash: calculatedHash,
    uid: userID,
    sid: sessionID,
    iid: itemID
};

$.ajax({
    method: 'POST',
    crossDomain: true,
    dataType: 'json',
    crossOrigin: true,
    async: true,
    contentType: 'application/json',
    data: data,
    headers: {
        'Access-Control-Allow-Methods': '*',
        "Access-Control-Allow-Credentials": true,
        "Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
        "Access-Control-Allow-Origin": "*",
        "Control-Allow-Origin": "*",
        "cache-control": "no-cache",
        'Content-Type': 'application/json'
    },
    url: 'https://yoururl.com/somephpfile.php',
    success: function(response){
        console.log("Respond was: ", response);
    },
    error: function (request, status, error) {
        console.log("There was an error: ", request.responseText);
    }
  })

或与提交表单一样保留它。仅当您要发送修改后的请求时,才需要此请求,该请求包含计算出的其他内容,而不仅是某些表单数据(由客户端输入),还可以发送。例如哈希,时间戳,用户ID,会话ID等。

答案 13 :(得分:1)

纯JS

在纯JS中,它将更加简单

foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(foo)});
}

foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(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>

答案 14 :(得分:0)

这是a very good article,其中包含您需要了解的有关jQuery表单提交的所有信息。

文章摘要:

简单的HTML表单提交

HTML:

<form action="path/to/server/script" method="post" id="my_form">
    <label>Name</label>
    <input type="text" name="name" />
    <label>Email</label>
    <input type="email" name="email" />
    <label>Website</label>
    <input type="url" name="website" />
    <input type="submit" name="submit" value="Submit Form" />
    <div id="server-results"><!-- For server results --></div>
</form>

JavaScript:

$("#my_form").submit(function(event){
    event.preventDefault(); // Prevent default action
    var post_url = $(this).attr("action"); // Get the form action URL
    var request_method = $(this).attr("method"); // Get form GET/POST method
    var form_data = $(this).serialize(); // Encode form elements for submission

    $.ajax({
        url : post_url,
        type: request_method,
        data : form_data
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});

HTML Multipart /表单数据表单提交

要将文件上传到服务器,我们可以使用XMLHttpRequest2可用的FormData接口,该接口构造一个FormData对象,并可以使用jQuery Ajax轻松将其发送到服务器。

HTML:

<form action="path/to/server/script" method="post" id="my_form">
    <label>Name</label>
    <input type="text" name="name" />
    <label>Email</label>
    <input type="email" name="email" />
    <label>Website</label>
    <input type="url" name="website" />
    <input type="file" name="my_file[]" /> <!-- File Field Added -->
    <input type="submit" name="submit" value="Submit Form" />
    <div id="server-results"><!-- For server results --></div>
</form>

JavaScript:

$("#my_form").submit(function(event){
    event.preventDefault(); // Prevent default action
    var post_url = $(this).attr("action"); // Get form action URL
    var request_method = $(this).attr("method"); // Get form GET/POST method
    var form_data = new FormData(this); // Creates new FormData object
    $.ajax({
        url : post_url,
        type: request_method,
        data : form_data,
        contentType: false,
        cache: false,
        processData: false
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});

我希望这会有所帮助。

答案 15 :(得分:0)

我还有一个想法。

提供下载文件的 PHP 文件的 URL。 然后您必须通过 ajax 触发相同的 URL,我检查了第二个请求仅在您的第一个请求完成下载文件后才给出响应。所以你可以得到它的事件。

它通过 ajax 处理相同的第二个请求。}

答案 16 :(得分:0)

这是使用 select 填充 option 中的 HTML ajax 标记的代码,XMLHttpRequest 使用 API 编写在 {{ 1}} 和 PHP

conn.php

PDO

category.php

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "db_event";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

script.js

<?php
 include 'conn.php';
try {
    $data = json_decode(file_get_contents("php://input"));
    $stmt = $conn->prepare("SELECT *  FROM events ");
    http_response_code(200);
    $stmt->execute();
    
    header('Content-Type: application/json');

    $arr=[];
    while($value=$stmt->fetch(PDO::FETCH_ASSOC)){
        array_push($arr,$value);
    }
    echo json_encode($arr);
   
  } catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
  }

index.html

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        data = JSON.parse(this.responseText);

        for (let i in data) {


            $("#cars").append(
                '<option value="' + data[i].category + '">' + data[i].category + '</option>'

            )
        }
    }
};
xhttp.open("GET", "http://127.0.0.1:8000/category.php", true);
xhttp.send();