简体   繁体   English

如何从 javascript 到 ajax 发送和检索数组

[英]How to send and retrieve an array from javascript through ajax

I have a 2d array in javascript, which i need to insert database so i need to send it to php via ajax.我在 javascript 中有一个二维数组,我需要插入数据库,所以我需要通过 ajax 将其发送到 php。

I have tried different solutions given on similar issues on stackoverflow, i was able to solve my error through them but can't get proper data on php file.我已经尝试过针对 stackoverflow 上的类似问题给出的不同解决方案,我能够通过它们解决我的错误,但无法在 php 文件上获得正确的数据。

I have a javascript code in which i have taken an array Arr_Records = [];我有一个 javascript 代码,其中我采用了数组 Arr_Records = []; this array is filled on 'Add' button click from some other array (var_ItemDetails).该数组在从其他数组(var_ItemDetails)单击“添加”按钮时填充。 (This is working good as data is setting perfectly in Arr_Records). (这很好,因为数据在 Arr_Records 中设置得很好)。

I have another button function OnCheckOutClick defined in javascript from where i need to insert records in Arr_Records to mysql database so i have been trying ajax to send it to insert.php file but unable to receive the data of Arr_Records there successfully. I have another button function OnCheckOutClick defined in javascript from where i need to insert records in Arr_Records to mysql database so i have been trying ajax to send it to insert.php file but unable to receive the data of Arr_Records there successfully.

<script>
var Arr_Records = [];
var indx = 0;

// This function is setting records in Arr_Records from another array. Its working fine (indx was initialized with 0).
function OnAddItemClick()
{
Arr_Records.push([
    var_ItemDetails.Id, 
    var_ItemDetails.Item, 
    var_ItemDetails.CategoryId, 
    var_ItemDetails.Category, 
    var_ItemDetails.Price, 
    var_ItemDetails.AvbQty,
    var_ItemDetails.PurQty,
    var_ItemDetails.RemQty, 
    var_ItemDetails.TotalPrice
]);


alert(Arr_Records[indx][1]); // only to confirm insertion
indx++; 

OnClearClick(); // to clear input fields.
}

function OnCheckOutClick()
{        
 var ajax = new XMLHttpRequest();
 var method = "POST";
 var url = "insertdata.php";
 var async = true;

 ajax.open(method, url, async);    
 ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 ajax.send(JSON.stringify(Arr_Records));
 ajax.onreadystatechange =  function()
 {
    if(this.readyState == 4 && this.status == 200)
    {
        var response_Data = ajax.responseText;
        alert(response_Data);
    }
 }    

}
</script>


// **** insertdata.php ****

<?php

$arrRecords = filter_input_array(INPUT_POST, 'Arr_Records');

$arrRecords = json_decode($arrRecords); 

if ( $arrRecords != null )
 echo $arrRecords[0][1];
else
  echo "No Data Found";   // this line executes  

?>

I want to have correct array recieve in insertdata.php so i can access all the items i have set from OnAddClick like itemid, item, category etc to insert in mysql.我想在 insertdata.php 中接收正确的数组,这样我就可以访问我从 OnAddClick 设置的所有项目,例如 itemid、item、category 等以插入 mysql。

use jquery for ajax like this:像这样对 ajax 使用 jquery :

$.ajax({
type: 'POST',
url: 'insert.php',
data: {
   Arr_Records:{
         "id":var_ItemDetails.Id,
         ...
    }
},
success: function(msg){
    alert('data sent' + msg);
}
});'

and in your php insert.php并在您的 php insert.php

i don't know what data is sending there var_dump $_POST and check the data in my case it would belike this in php我不知道那里发送了什么数据 var_dump $_POST 并在我的情况下检查数据,它在 php 中会像这样

$array_record = $_POST["Arr_Records"];
$id = $array_record['id'];

The javascript - ajax function needs to send the payload data with a field name that can be captured in PHP ( such as $_POST['payload'] ) and the PHP needs to use filter_input rather than filter_input_array to filter the data - assigning no actual filter is the equivalent of not filtering at all - hence use FILTER_SANITIZE_STRING The javascript - ajax function needs to send the payload data with a field name that can be captured in PHP ( such as $_POST['payload'] ) and the PHP needs to use filter_input rather than filter_input_array to filter the data - assigning no actual过滤器相当于根本不过滤 - 因此使用FILTER_SANITIZE_STRING

<script>

    var Arr_Records = [];
    var indx = 0;

    // This function is setting records in Arr_Records from another array. Its working fine (indx was initialized with 0).
    function OnAddItemClick(){
        Arr_Records.push([
            var_ItemDetails.Id, 
            var_ItemDetails.Item, 
            var_ItemDetails.CategoryId, 
            var_ItemDetails.Category, 
            var_ItemDetails.Price, 
            var_ItemDetails.AvbQty,
            var_ItemDetails.PurQty,
            var_ItemDetails.RemQty, 
            var_ItemDetails.TotalPrice
        ]);
        indx++; 

        OnClearClick();
    }



    function OnCheckOutClick(){
        var payload=JSON.stringify( Arr_Records );
        var ajax = new XMLHttpRequest();
            ajax.onreadystatechange =  function(){
                if( this.readyState == 4 && this.status == 200 ){
                    alert( this.response );
                }
            }
            ajax.open( 'POST', 'insertdata.php', true );
            ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            /* send the data as the value of a named parameter / post field */
            ajax.send( 'payload='+payload );
    }
</script>




<?php

    /* insertdata.php */
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['payload'] ) {

        $data = filter_input( INPUT_POST, 'payload', FILTER_SANITIZE_STRING );
        $json = json_decode( $data ); 

        if( empty( json_last_error() ) ){
            echo $json[0][1];

        } else {
            echo 'No Data Found';
        }
    }
?>

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

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