views:

29

answers:

1

Hi,

I am trying to upload a text file with more than one record but I keep getting a syntax() error. The implemented logic works fine if there is only one record in the file. Could the problem be that I am echoing multiple records in my foreach loop?

Description:

Ext JS interface where the user browses for a file. Once file is selected it is then uploaded to the server and parsed in PHP. The parsed process is called processFile which is called by the js file.

What I have noticed

  1. The implemented logic works fine if there is only one record in the file.
  2. The json format is correct.
  3. If the file contains 3 records a fourth BLANK record is still read.

Herewith the PHP code:

<?php

$action = $_REQUEST['action'];
if ($action == 'uploadFile') {
  $fileName = $_FILES['file']['tmp_name'];
  $fileContent = file_get_contents($fileName);
  $fileInfo = parseFile($fileContent); //custom formatting 
    echo wrap_answer(array(
    'originalFile' => $fileContent,    
    'fileInfo' => $fileInfo,
    'success' => true
    ));  
}

if ($action == 'processFile') {
  $fileContent = $_REQUEST['file'];
  $fileInfo = parseFile($fileContent);  

  foreach($fileInfo['lines'] as $line) {        
    $input = array(
            'id' => $line['id'],
            'name' => $line['name']);              
    //custom function to insert records from file into clients table
    //function returns the inserted records ID  
    $insert_id = handler_Insert('clients',$input);    

    $success = ($insert_id == null || $insert_id == 0)?false:true;
    echo json_encode(array(
    'success' => $success)
    );    
    //NOTE:Processing records 1 by 1 and echoing the result
    //     Could this be the error? Any suggestions to better
    //     handle this process?
  }
}

Any help,suggesstions etc much appreciated! Thanks

A: 

SOLVED

I had to rewrite my code to return only ONE json string with multiple records like this:

 //new variable to hold all array elements
    $rows = array();
    //In the foreach loop push the array item on $rows
    array_push($rows,array(
      'success' => $success,
      'record' => $input));    

    } //end of foreach loop
      echo json_encode(array(
      'id' => 'clients',
      'rows' => $rows));
   }//end of processFile function

Then in my js file all I had to do was loop through the result using Ext.each like this:

loadClient:function(result){
      var records = result.rows; //rows[0]{id,name},rows[1]      
      console.log(records);
      Ext.each(records,this.processKey,this);
    },
processKey:function(item,itemIndex){
      if(item.success){
         alert('Record inserted!');
      }
      else{
         alert('Failed to insert record');
      }
}
Bosvark