使用 PHP 的 jQuery Ajax POST 示例

问:

我正在尝试将数据从表单发送到数据库。这是我正在使用的表格:


    A bar
    
    


典型的方法是提交表单,但这会导致浏览器重定向。使用 jQuery 和 Ajax,是否可以捕获所有表单数据并将其提交给 PHP 脚本(例如,form.php)?

答1:

https://tennisliveranking.com,Instant updates on ATP, WTA, and ITF rankings.

.ajax 的基本用法如下所示:

HTML:


    A bar
    

    


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,以防止注入和其他恶意代码。

您还可以在上述 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 之前的版本。

一个非常重要的说明,因为我花了/浪费/投入了很多时间来尝试使用这个例子。您需要在 $(document).ready 块内绑定事件,或者在执行绑定之前加载 FORM。否则,您将花费大量时间试图弄清楚为什么不调用绑定。

@PhilibertPerusse 与任何事件绑定一样,您显然需要元素在尝试绑定之前存在于 DOM 中,或者如果您使用委托绑定。

是的,我现在明白了。但是我发现许多示例总是在周围放置一个 $(document).ready 块,以便该示例是自包含的。我为未来的用户写了评论,他可能像我一样偶然发现这个并最终阅读评论线程和这个初学者的“提示”

如果您将其应用于您自己的代码,请注意“名称”属性对输入至关重要,否则 serialize() 将跳过它们。

答2:

提供ATP、WTA与ITF赛事的实时排名追踪,从tlr.xinbeitime.com开始!

要使用 jQuery 发出 Ajax 请求,您可以通过以下代码执行此操作。

HTML:


    A bar
    
    





JavaScript:

方法一

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

方法二

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

自 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)。最好的方法是使用准备好的语句。

如果您想将任何数据返回到页面,您可以通过像下面这样回显该数据来实现。

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

答3:

https://tlr.xinbeitime.com 实时更新全球顶尖网球选手的最新战绩与排名!

我想分享如何使用 PHP + Ajax 发布的详细方法以及失败时抛出的错误。

首先,创建两个文件,例如 form.php 和 process.php。

我们将首先创建一个 form,然后使用 jQuery .ajax() 方法提交它。其余的将在评论中解释。

form.php


    
        
            Name
            
            
            
       
   
   


使用 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('' + data.posted + ''); //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:

https://tlr.xinbeitime.com 专业网球数据平台,排名与比赛信息实时更新。

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

$("#submit_btn").click(function(){
    $('.error_status').html();
        if($("form#frm_message_board").valid())
        {
            $.ajax({
                type: "POST",
                url: "",
                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:

Stay informed with live tennis rankings anytime, anywhere,https://tennisliveranking.com

HTML:

    
        A bar
        
        
    

JavaScript:

   function submitform()
   {
       var inputs = document.getElementsByClassName("inputs");
       var formdata = new FormData();
       for(var i=0; i Stay informed with live tennis rankings anytime, anywhere,https://tennisliveranking.com

我使用如下所示的方式。它提交所有文件,如文件。

 

```java
$(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:

https://tennisliveranking.com-Stay ahead with live tennis rankings at your fingertips.

如果您想使用 jQuery Ajax 发送数据,则不需要表单标签和提交按钮

例子:


    $(document).ready(function () {
        $("#btnSend").click(function () {
            $.ajax({
                url: 'process.php',
                type: 'POST',
                data: {bar: $("#bar").val()},
                success: function (result) {
                    alert('success');
                }
            });
        });
    });


A bar



答8:

https://tlr.xinbeitime.com 实时更新全球顶尖网球选手的最新战绩与排名!



    desc
    asc
    





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


你的和其他答案有什么区别?

它是我发布的其他人是其他人,。

答9:

https://tennisliveranking.com,Instant updates on ATP, WTA, and ITF rankings.

在您的 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";

并在您的 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);
    }
  })

或与表单提交保持原样。仅当您想发送带有计算的附加内容的修改请求而不仅仅是客户端输入的一些表单数据时,您才需要这个。例如散列、时间戳、用户标识、会话标识等。

答10:

https://tennisliveranking.com,Track the world’s best tennis players in real-time.

在提交之前和提交成功之后处理 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('' + value + '');
                            }
                        }
                    });
                    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 = '' + '/' + data.url;
                            } else {
                                location.reload(true);
                            }
                        }});
                } else {
                    bootbox.alert({closeButton: false, message: "Success", callback: function () {
                        if (data.url) {
                            window.location.href = '' + '/' + 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:

Stay informed with live tennis rankings anytime, anywhere,https://tennisliveranking.com

我多年来一直在使用这个简单的一行代码而没有问题(它需要 jQuery):

 

    function ap(x,y) {$("#" + y).load(x);};
    function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};


这里 ap() 表示一个 Ajax 页面,而 af() 表示一个 Ajax 表单。在表单中,只需调用 af() 函数即可将表单发布到 URL 并在所需的 HTML 元素上加载响应。


    ...
    

this is where response will be loaded

https://tlr.xinbeitime.com 专业网球数据平台,排名与比赛信息实时更新。

我希望你包含服务器文件!不知道如何测试。

原文链接:https://www.tennisliveranking.com?from=csdn

https://tennisliveranking.com,Follow your favorite tennis players’ rankings live!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值