Home > Back-end >  Ajax request - get form data and loop through element_name[]
Ajax request - get form data and loop through element_name[]

Time:02-14

I am performing an AJAX-Reqest with form data and additional data as array (selected_members)

$.ajax({
    type: "POST",
    url: "inc/insert.inc.php",
    data: { 
        frmData: $("#frmData").serialize(),
        selected_members: selected_members
    },

How can I get these data in insert.inc.php as two arrays (form data and selected_members)? The form contains also elements with name="element_name[]"

    var_dump($_POST);
        array(2) {
  ["frmData"]=>
  string(232) "datDate=2022-02-13&tmBeginn=17:00&tmEnde=17:00&cmb_Mittel[]=1&txt_Aufwandmenge[]=1&txt_mKh[]=1&cmb_Mittel[]=2&txt_Aufwandmenge[]=2&txt_mKh[]=3&cmbGeraet=1&cmbDuese=1&txtWasser=300&cmbGasse=2&cmbAnwender=1"
  ["selected_members"]=>
  array(2) {
    [0]=>
    string(1) "3"
    [1]=>
    string(1) "4"
  }
}

How can I get the form data, and loop through each "row" of the three element_name[] inputs?

CodePudding user response:

As we can see, cmb_item and txt_amount are existing values in $yourarray and they are arrays of items. They do not need to be associative arrays, because they share the same name and differ in value only. In order to refer to them, you can simply do $yourarray['cmb_item'] and $yourarray['txt_amount'], respectively.

EDIT

Example:

<?php

$foo = 'datDate=2022-02-13&tmStart=15:00&tmEnd=15:00&cmb_item[]=1&txt_amount[]=30&cmb_item[]=2&txt_amount[]=50&&cmbDevice=1';

parse_str($foo, $bar);

echo var_dump($bar['cmb_item']);

The result is

array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
}
  • Related