简体   繁体   English

使用ajax将数组发布到PHP

[英]Posting Array to PHP using ajax

I'm having issues posting an Array to a PHP page using AJAX. 我在使用AJAX将数组发布到PHP页面时遇到问题。 I've been using this question as guidance, but for whatever reason I still can't get it to work. 我一直在用这个问题作为指导,但无论出于何种原因,我仍然无法让它发挥作用。 From what I can tell by using print_r($_POST) , I am posting an empty Array, but on the HTML/Javascript page I use an alert to see that the Array has been filled. 通过使用print_r($_POST)我可以告诉我,我发布一个空数组,但在HTML / Javascript页面上,我使用警报来查看数组已被填充。 The post is working because it inputs blank values into a MySQL database on post, but I can't figure out why it is passing an empty Array. 该帖子正在工作,因为它在帖子上将空白值输入到MySQL数据库中,但我无法弄清楚它为什么传递空数组。 The code is as follows: 代码如下:

Javascript: 使用Javascript:

<script type="text/javascript">
    var routeID = "testRoute";
    var custID = "testCustID";
    var stopnumber = "teststopnumber";
    var customer = "testCustomer";
    var lat = 10;
    var lng = 20;
    var timeStamp = "00:00:00";


    var dataArray = new Array(7);
  dataArray[0]= "routeID:" + routeID;
  dataArray[1]= "custID:" + custID;
  dataArray[2]= "stopnumber:" + stopnumber;
  dataArray[3]= "customer:" + customer;
  dataArray[4]= "latitude:" + lat;
  dataArray[5]= "longitude:" + lng; 
  dataArray[6]= "timestamp:" + timeStamp; 
  var jsonString = JSON.stringify(dataArray);
  function postData(){
    $.ajax({
       type: "POST",
       url: "AddtoDatabase.php", //includes full webserver url
       data: {data : jsonString}, 
       cache: false,

       success: function(){
           alert("OK");
       }
    });
  window.location = "AddtoDatabase.php"; //includes full webserver url
  }
alert(JSON.stringify(dataArray))
</script>

PHP: PHP:

<?php
  print_r($_POST);


$routeID = $_POST['routeID'];
  $custID = $_POST['custID'];
  $stopnumber = $_POST['stopnumber'];
  $customer = $_POST['customer'];
  $latitude = $_POST['latitude'];
  $longitude = $_POST['longitude'];
  $timestamp = $_POST['timestamp'];

$mysqli= new mysqli("fdb5.biz.nf","username","password","database");

mysqli_select_db($mysqli,"database");

    $sql = "INSERT INTO Locations (routeID, custID, stopnumber, customer, latitude, longitude, timestamp) VALUES " .
           "('$routeID','$custID','$stopnumber','$customer','$latitude','$longitude','$timestamp')";
    mysqli_query($mysqli, $sql); 

    $error = mysqli_error($mysqli);  
echo $error;
?>

print_r($_POST) only displays Array() on the php page while the jsonString alert on the javascript page shows ["routeID:testRoute", "custID:testCustID", "stopnumber:teststopnumber", "customer:testCustomer", "latitude:10", "longitude:20", "timestamp:00:00:00"] print_r($_POST)仅在php页面上显示Array(),而javascript页面上的jsonString警报显示["routeID:testRoute", "custID:testCustID", "stopnumber:teststopnumber", "customer:testCustomer", "latitude:10", "longitude:20", "timestamp:00:00:00"]

Anyone see what I'm doing wrong? 有谁看到我做错了什么?

Note: The main cause for your code to output array() is the fact that you're redirecting the client before the asynchronous (AJAX) request has been sent/processed 注:您的代码输出的主要原因 array()是你的异步之前重定向客户端的事实(AJAX)请求已发送/处理
Basically move window.location = "AddtoDatabase.php"; 基本上移动window.location = "AddtoDatabase.php"; to the success callback, as mentioned further down. 成功回调,如下所述。

First problem: Instead of using an array, you should use an object literal (~= assoc array in php). 第一个问题:您应该使用对象文字(在php中为〜= assoc数组),而不是使用数组。

To do so, change this bit: 为此,请更改此位:

var dataArray = new Array(7);//<== NEVER do this again, btw
dataArray[0]= "routeID:" + routeID;
dataArray[1]= "custID:" + custID;
dataArray[2]= "stopnumber:" + stopnumber;
dataArray[3]= "customer:" + customer;
dataArray[4]= "latitude:" + lat;
dataArray[5]= "longitude:" + lng; 
dataArray[6]= "timestamp:" + timeStamp; 

And write this, instead: 写下这个,而不是:

var dataObject = { routeID: routeID,
                   custID:  custID,
                   stopnumber: stopnumber
                   customer: customer,
                   latitude: lat,
                   longitute: lng,
                   timestamp: timeStamp};

There's nothing more too it. 没有什么比它更重要了。 To finish off, just send the data like so: 要完成,只需发送如下数据:

function postData()
{
    $.ajax({ type: "POST",
             url: "AddtoDatabase.php",
             data: dataObject,//no need to call JSON.stringify etc... jQ does this for you
             cache: false,
             success: function(resopnse)
             {//check response: it's always good to check server output when developing...
                 console.log(response);
                 alert('You will redirect in 10 seconds');
                 setTimeout(function()
                 {//just added timeout to give you some time to check console
                    window.location = 'AddtoDatabase.php';
                 },10000);
             }
    });

Secondly, your postData function redirects the client before the AJAX request has been sent! 其次, postData函数在发送AJAX请求之前重定向客户端! After the call to $.ajax , you have a window.location = "AddtoDatabase.php"; 在调用$.ajax ,你有一个window.location = "AddtoDatabase.php"; statement in your code. 代码中的语句。 If you want the client to be redirected after the ajax call, you will have to move that expression to your success callback function (the one where I log the response ) in the second snippet ^^. 如果您希望在ajax调用之后重定向客户端,则必须将该表达式移动到第二个代码段^^中的success回调函数(我记录response函数)。

When you've changed all this, your $_POST variable should look about right. 当你改变了所有这些后,你的$_POST变量看起来应该是正确的。 If not, print out the $_REQUEST object and see what the response of an ajax call is then. 如果没有,打印出$_REQUEST对象,然后查看ajax调用的响应。

Lastly, please be aware that using an api that supports prepared statements (and thus protects you against most injection attacks), that doesn't mean stringing unchecked POST/GET data into a query is any safer than it used to be... 最后, 注意使用支持预处理语句的api(从而保护您免受大多数注入攻击),这并不意味着将未经检查的POST / GET数据串入查询比以前更安全......
Bottom line: When you use an API that supports critical safety features such as prepared statements use those features . 结论:当您使用支持关键安全功能的API(如预准备语句)时,请使用这些功能

Just to be absolutely clear, and complete, here's a slightly reworked version of the PHP code, too: 只是为了绝对清楚,完整,这里也是一个稍微改进的PHP代码版本:

$routeID = $_POST['routeID'];
$custID = $_POST['custID'];
$stopnumber = $_POST['stopnumber'];
$customer = $_POST['customer'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$timestamp = $_POST['timestamp'];
//you're connecting OO-style, why do you switch to procedural next?
//choose one, don't mix them, that makes for fugly code:
$mysqli = mysqli_connect('fdb5.biz.nf', 'username', 'password', 'database');//procedural
//or, more in tune with the times:
$mysqli= new mysqli("fdb5.biz.nf","username","password","database");//OO

mysqli_select_db($mysqli,"database");
//or
$mysqli->select_db('database');

Check the docs to see the procedural counterpart of all methods I'll be using from here on end, if you want. 如果需要,检查文档以查看我将在这里使用的所有方法的过程对应物。 I prefer the OOP-API 我更喜欢OOP-API

//making a prepared statement:
$query = 'INSERT INTO Locations 
          (routeID, custID, stopnumber, customer, latitude, longitude, timestamp) VALUES 
          (?,?,?,?,?,?,?)';
if (!($stmt = $mysqli->prepare($query)))
{
    echo $query.' failed to prepare';
    exit();
}
$stmt->bind_param('s', $routeID);
$stmt->bind_param('s',$custID);
//and so on
$stmt->bind_param('d', $latitude);//will probably be a double
$stmt->execute();//query DB

Useful links on prepared statements: 准备好的陈述上有用的链接

you should use serialize. 你应该使用序列化。 then...... 然后......

<script>

jQuery(document).ready(function($){
/* attach a submit handler to the form */
$("#submit").click( function(event) {

/* stop form from submitting normally */
 event.preventDefault();

 /*clear result div*/
 $("#loginresponse").html('');

 /* use serialize take everthing into array */
    var frmdata = $("#formname").serialize();

$.ajax({
  url: "/file.php",
  type: "post",
  dataType: "json",
  data: frmdata,
  success: function(data, textStatus){
    if(data.redirect == 'true'){
       $('#formresponse').html(data.message);
      return true;
    }else{
      $('#formresponse').html(data.message);
      return false;
    }
  },
  error:function(){
      $("#formresponse").html('error');
  }
});
});
}); 

</script>

than in php take data with post 比在php中使用post获取数据

<?php
$routeID = $_POST['routeID'];
$custID = $_POST['custID'];
$stopnumber = $_POST['stopnumber'];
$customer = $_POST['customer'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$timestamp = $_POST['timestamp'];
?>

and display with json encode. 并使用json编码显示。 this way you can display errors 这样你就可以显示错误

<?php 

if(true)
    echo json_encode(array('redirect'=>'true', 'message'=>'form submitted'));
else
    echo json_encode(array('redirect'=>'false', 'message'=>'form not submited'));
?>

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

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