简体   繁体   English

通过ajax将html输入数组值传递给php脚本

[英]Pass html input array values to php script via ajax

I have the HTML below, the idea is that i have an add button and you can add multiple addresses. 我在下面有HTML,想法是我有一个添加按钮,您可以添加多个地址。 The add button would simply insert the html for another input with the same name thus creating an array of html inputs. 添加按钮将简单地为另一个具有相同名称的输入插入html,从而创建一个html输入数组。 I am unable to pass the multiple inputs to a php script via ajax. 我无法通过ajax将多个输入传递给php脚本。

<form id="addTripForm" class="form-horizontal">
<div class="form-group">
    <label class="col-xs-4 text-right">Address</label>
    <div class="col-xs-8"><input type="text" class="form-control" id="deliveryAddress[]" name="deliveryAddress[]" required/></div>
</div>
</form>

I have tried this way of passing the values (Here i just get the elements by the name and put that in the variable formData). 我尝试过这种传递值的方式(在这里,我只是通过名称获取元素并将其放在变量formData中)。

var deliveryAddress = document.getElementsByName('deliveryAddress[]');
var formData = {"deliveryAddress":deliveryAddress};

In the following way I get the elements and then loop through them and push those values to an array and then assign that array to the variable formData 通过以下方式,我获得了元素,然后遍历它们并将这些值推入数组,然后将该数组分配给变量formData

var deliveryAddress = document.getElementsByName('deliveryAddress[]');
var deliveries = new Array();
for(var i=0;i<deliveryAddress.length;i++){
        deliveries.push(deliveryAddress[i].value);
}
var formData = {"deliveryAddress":deliveries};

Then I use the value in the variable formData(from above) and push that via ajax 然后我使用变量formData(来自上面)中的值,并通过ajax将其推送

$.ajax({
        url : "/admin/PHPClasses/addToDB.php?type=Trip",
        type: "POST",
        data : formData,
        success: function(data, textStatus, jqXHR)
        {
            $('.form-group').hide();
            $('.bg-success').show();
            $('#saveChanges').hide();
            window.location.reload();
         },
         error: function (jqXHR, textStatus, errorThrown)
         {
            $('.bg-danger').show();
         }
});

Finally in my PHP script i am trying to access the deliveryAddress as follows 最后,在我的PHP脚本中,我尝试按以下方式访问deliveryAddress

$deliveryAddress = filter_input(INPUT_POST, "deliveryAddress");

If someone could show what I am doing wrong and also if this is the best approach to this problem. 如果有人可以证明我做错了什么,这也是解决此问题的最佳方法。 All your help is greatly appreciated. 非常感谢您的帮助。

Update: I think all the answers were probably correct, i just noticed i had not closed the body and the html tag at the bottom of the page and that was causing the javascript serialize to somehow not work. 更新:我认为所有答案都可能是正确的,我只是注意到我没有关闭页面底部的正文和html标签,这导致javascript序列化以某种方式无法正常工作。 Thanks for everyone's help 谢谢大家的帮助

You can use following approach: 您可以使用以下方法:

First, you can use jQuery .serialize() 首先,您可以使用jQuery .serialize()

Second, update your ajax code with serialize() 其次,使用serialize()更新您的ajax代码

Java-Script Ajax Code: Java脚本Ajax代码:

$(document).ready(function() {
    // form submit function
    $("#addTripForm").on("submit", function(e) {
        // stop form submission
        e.preventDefault();
        $.ajax({
            url: "/admin/PHPClasses/addToDB.php?type=Trip",
            type: "POST",
            data: $("#addTripForm").serialize(),
            success: function(data, textStatus, jqXHR) {
                $('.form-group').hide();
                $('.bg-success').show();
                $('#saveChanges').hide();
                //window.location.reload();
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $('.bg-danger').show();
            }
        });
    })
});

Third, use below php code to get adderss 第三,使用以下php代码获取加法器

<?php
// filter user input
$deliveryAddress = filter_input(INPUT_POST, 'deliveryAddress', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
// join array with comma
$deliveryAddress = implode(",\n", $deliveryAddress);
// show address
echo $deliveryAddress;

Here is full code html js and php: 这是完整的代码html js和php:

 $(document).ready(function() { //maximum input boxes allowed var max_fields = 10; //Fields wrapper var wrapper = $(".pure-control-group"); //initlal text box count var x = 1; //on add button click $('body').on("click", ".fa-plus-circle", function(e) { //max input box allowed if (x < max_fields) { //text box increment x++; //add input box var render = '<div class="pure-control-group"> ' + ' <label for="deliveryAddress[]">Address</label>' + ' <input name="deliveryAddress[]" type="text" placeholder="Address...">' + ' <i class="fa fa-plus-circle"></i> ' + ' <i class="fa fa-trash-o"></i>' + '</div>'; $(wrapper).after(render); } }); //on delete button click $('body').on("click", ".fa-trash-o", function(e) { //user click on remove text $(this).parent('div.pure-control-group').remove(); x--; }) // form submit function $("#addTripForm").on("submit", function(e) { // stop form submission e.preventDefault(); $.ajax({ url: "post.php?type=Trip", type: "POST", data: $("#addTripForm").serialize(), success: function(data, textStatus, jqXHR) { $('.form-group').hide(); $('.bg-success').show(); $('#saveChanges').hide(); //window.location.reload(); }, error: function(jqXHR, textStatus, errorThrown) { $('.bg-danger').show(); } }); }) }); 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Pass html input array values to php script via ajax</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <style type="text/css">i,i:hover{color:#0078e7;cursor:pointer;}</style> </head> <body> <form class="pure-form pure-form-aligned form-horizontal" id="addTripForm"> <fieldset> <div class="pure-control-group"> <label for="deliveryAddress[]">Address</label> <input name="deliveryAddress[]" type="text" placeholder="Address..."> <i class="fa fa-plus-circle"></i> </div> <div class="pure-controls"> <button type="submit" class="pure-button pure-button-primary">Submit</button> </div> </fieldset> </form> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="js.js"></script> </body> </html> 

Hi Try to use object of formData 您好尝试使用formData对象

var deliveries = new Array();
        $('#addTripForm input[name="deliveryAddress"]').each(function (){
            deliveries.push($(this).val()); 
        });

var formData = new FormData()
formData.append("deliveryAddress",deliveries);

$.ajax({
        url : "/admin/PHPClasses/addToDB.php?type=Trip",
        type: "POST",
        data : formData,
        cache: false,
        contentType: false,
        processData: false
        success: function(data, textStatus, jqXHR)
        {
            $('.form-group').hide();
            $('.bg-success').show();
            $('#saveChanges').hide();
            window.location.reload();
         },
         error: function (jqXHR, textStatus, errorThrown)
         {
            $('.bg-danger').show();
         }
});

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

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