简体   繁体   English

"使用 PHP 的 jQuery Ajax POST 示例"

[英]jQuery Ajax POST example with PHP

I am trying to send data from a form to a database.我正在尝试将数据从表单发送到数据库。 Here is the form I am using:这是我正在使用的表格:

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

Basic usage of .ajax would look something like this: .ajax的基本用法如下所示:

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

});

Note: Since jQuery 1.8, .success() , .error() and .complete() are deprecated in favor of .done() , .fail() and .always() .注意:从 jQuery 1.8 开始, .success().error().complete()被弃用,取而代之的是.done().fail().always()

Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a $(document).ready() handler (or use the $() shorthand).注意:请记住,上面的代码片段必须在 DOM 准备好之后完成,因此您应该将它放在$(document).ready()处理程序中(或使用$()简写)。

Tip: You can chain the callback handlers like this: $.ajax().done().fail().always();提示:您可以像这样链接回调处理程序: $.ajax().done().fail().always();

PHP (that is, form.php): 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;

Note: Always sanitize posted data , to prevent injections and other malicious code.注意:始终清理发布的数据,以防止注入和其他恶意代码。

You could also use the shorthand .post in place of .ajax in the above JavaScript code:您还可以在上述 JavaScript 代码中使用简写.post代替.ajax

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

Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.注意:上面的 JavaScript 代码适用于 jQuery 1.8 及更高版本,但它应该适用于 jQuery 1.5 之前的版本。

To make an Ajax request using jQuery<\/em> you can do this by the following code.要使用jQuery<\/em>发出 Ajax 请求,您可以通过以下代码执行此操作。

HTML:<\/strong> HTML:<\/strong>

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

I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.我想分享如何使用 PHP + Ajax 发布的详细方法以及失败时抛出的错误。

First of all, create two files, for example form.php and process.php .首先,创建两个文件,例如form.phpprocess.php

We will first create a form which will be then submitted using the jQuery .ajax() method.我们将首先创建一个form ,然后使用jQuery .ajax()方法提交该表单。 The rest will be explained in the comments.其余的将在评论中解释。


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>


Validate the form using jQuery client-side validation and pass the data to process.php .使用 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
    });
});

Now we will take a look at process.php现在我们来看看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);

The project files can be downloaded from http://projects.decodingweb.com/simple_ajax_form.zip .可以从http://projects.decodingweb.com/simple_ajax_form.zip下载项目文件。

You can use serialize.您可以使用序列化。 Below is an example.下面是一个例子。

$("#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<\/strong> : HTML<\/strong> :

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

I use the way shown below.我使用如下所示的方式。 It submits everything like files.它提交所有文件,如文件。

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

If you want to send data using jQuery Ajax then there is no need of form tag and submit button如果您想使用 jQuery Ajax 发送数据,则不需要表单标签和提交按钮

Example:<\/strong>例子:<\/strong>

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

In your php file enter:在您的 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 = $decoded_data['hash'];
echo "You have sent a POST request containing the bar variable with the value $bar";

Handling Ajax errors and loader before submit and after submitting success shows an alert boot box with an example:在提交之前和提交成功之后处理 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);
            }
        }
    }
});

I am using this simple one line code for years without a problem (it requires jQuery):我多年来一直在使用这个简单的一行代码而没有问题(它需要 jQuery):

<script src="http://malsup.github.com/jquery.form.js"></script> 
<script type="text/javascript">
    function ap(x,y) {$("#" + y).load(x);};
    function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>

Here ap() means an Ajax page and af() means an Ajax form.这里 ap() 表示一个 Ajax 页面,而 af() 表示一个 Ajax 表单。 In a form, simply calling af() function will post the form to the URL and load the response on the desired HTML element.在表单中,只需调用 af() 函数即可将表单发布到 URL 并在所需的 HTML 元素上加载响应。

<form id="form_id">
    ...
    <input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>

Please check this.请检查这个。 It is the complete Ajax request code.它是完整的 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 whatever 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();
});

Since the introduction of the Fetch API there really is no reason any more to do this with jQuery Ajax or XMLHttpRequests.自从引入Fetch API之后,真的没有理由再使用 jQuery Ajax 或 XMLHttpRequests 来做这件事了。 To POST form data to a PHP-script in vanilla JavaScript you can do the following:要将表单数据发布到原生 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>

Here is a very basic example of a PHP-script that takes the data and sends an email:这是一个非常基本的 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);

This is a very good article<\/a> that contains everything that you need to know about jQuery form submission.这是一篇非常好的文章<\/a>,其中包含您需要了解的有关 jQuery 表单提交的所有信息。

Article summary:文章摘要:

Simple HTML Form Submit<\/strong>简单的 HTML 表单提交<\/strong>

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>

Pure JS纯JS<\/h1>

In pure JS it will be much simpler在纯JS中它会简单得多

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

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

"

I have one other idea.我还有一个想法。

Which the URL that of PHP files which provided the download file.提供下载文件的 PHP 文件的 URL。 Then you have to fire the same URL via ajax and I checked this second request only gives the response after your first request complete the download file.然后您必须通过 ajax 触发相同的 URL,并且我检查了第二个请求仅在您的第一个请求完成下载文件后才给出响应。 So you can get the event of it.所以你可以得到它的事件。

It is working via ajax with the same second request.}它通过 ajax 使用相同的第二个请求工作。}

"

That's the code that fills a select<\/code> option<\/code> tag in HTML<\/code> using ajax<\/code> and XMLHttpRequest<\/code> with the API<\/code> is written in PHP<\/code> and PDO<\/code>这是使用ajax<\/code>和XMLHttpRequest<\/code>填充HTML<\/code>中的select<\/code> option<\/code>标签的代码, API<\/code>是用PHP<\/code>和PDO<\/code>编写的

conn.php<\/strong>连接文件<\/strong>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM