0

Is there a way to fetch data from xmlhttprequest Object as an array (not using json & jquery) in php?

I have encountered a text saying that in order to handle ajax requests in php it will be first checked whether the input data is an array or not. here's the code regarding the text:

  <?php
    $data = $_REQUEST['fld'];
    if ( is_array($data) )
        echo file_put_contents('db.csv', implode(",", $data) . "\n", FILE_APPEND) ? 1 : 2;
    else 
        echo 3;//Error 
  ?>
Obaid
  • 373
  • 2
  • 10

1 Answers1

0

You must create the QUERY_STRING with encoded field-names and -values(let's assume you would send these fields via a form by using GET, the QUERY_STRING you would see in the address-bar of the browser you must create via JS ).

Example:

  var  name   = 'fld[]',//name of the fields
       enc    = encodeURIComponent(name),//encoded name 
       query  = [],//array to store the data
       flds   = document.querySelectorAll('input[name="'+name+'"]');//the inputs

  for(var f = 0; f < flds.length; ++f){//iterate over the inputs
    //collect the data
    query.push([enc,encodeURIComponent(flds[f].value)].join('='));
  }
  //prepare the data
  query=query.join('&');

  //query now is ready for transmission: 

  //either via GET:
  XMLHttpRequestInstance.open('GET', 'some.php?'+query, true);


  //or via POST:
  XMLHttpRequestInstance.send(query);

$_REQUEST['fld'] will be an array.

Note: when you send the data via POST you must also send appropriate headers, see: Send POST data using XMLHttpRequest

Community
  • 1
  • 1
Dr.Molle
  • 113,505
  • 14
  • 184
  • 194