load->libra" name="description" /> load->libra" />
53934

Passing array php into json gives undefined

Question:

I want to pass a JSON from php to js.

This is my php file :

public function upload() { $record = 0; if (!empty($_FILES)) { $config['upload_path'] = "./assets/uploads"; $config['allowed_types'] = 'csv'; $this->load->library('upload', $config); if (!$this->upload->do_upload("file")) { echo "File cannot be uploaded"; } else { $upload_data = $this->upload->data(); $csv = $upload_data['full_path']; $name_csv = $upload_data['file_name']; $tryOne = array(); if (file_exists($csv)) { $file = fopen($csv, 'r'); // r flag is for readonly mode while (( $line = fgetcsv($file) ) !== false) { // if line exists $tryOne[] = $line; // add to array } fclose($file); } echo json_encode(array( "nama_csv" => $name_csv, "path" => $csv, "isi" => $tryOne )); } } elseif ($this->input->post('file_to_remove')) { $file_to_remove = $this->input->post('file_to_remove'); unlink("./assets/uploads/" . $file_to_remove); } else { $this->listFiles(); } }

Please see in mv json. I debug it : print_r($tryOne);

Array ( [0] => Array ( [0] => NO [1] => COLUMN1 [2] => COLUMN2 [3] => COLUMN3 [4] => COLUMN4 [5] => COLUMN5 [6] => COLUMN6 [7] => COLUMN7 [8] => COLUMN8 [9] => COULMN9 [10] => COLUMN10 [11] => COLUMN11 [12] => COLUMN12 [13] => COLUMN13 ) [1] => Array ( [0] => 1 [1] => NYK FUJI [2] => AJU150708 [3] => [4] => 6C7132 [5] => 977NEF [6] => JKT-P.T.IRON WORKS [7] => 977NEF [8] => KCH8ATDM [9] => 17.9 [10] => 1690 [11] => 2150 [12] => 6C7132-1690 [13] => 175 ) [2] => Array ( [0] => 2 [1] => NYK FUJI [2] => AJU150708 [3] => [4] => 6C7132 [5] => 977NEF [6] => JKT-P.T.IRON WORKS [7] => 977NEF [8] => KCH8ATDM [9] => 17.9 [10] => 1700 [11] => 2138 [12] => 6C7132-1700 [13] => 176 ) )

Everything looks fine. But in ajax success :

success: function (response) { moment.locale("id"); for (i = 0; i <= response.isi.length; i++) { for (j = 0; j <= response.isi[i].length; j++) { $('#table-review').find('tbody').append("<tr>" + "<td>" + response.isi[i][j] + "</td>" + "</tr>"); } } $("#btnSave").attr("onclick", "save('" + response.path + "', '" + response.nama_csv + "')"); $('#modal_form').modal('show'); // show bootstrap modal $('.modal-title').text('Review Data Hasil Upload Dari CSV Pusat'); // Set Title to Bootstrap modal title reload_table(); listFilesOnServer(); },

gives me : <strong>TypeError: response.isi[i] is undefined</strong>

I want to display this array into a table in modal bootstrap, so i debug it again to see if response.isi is exist : console.log(response.isi)

[["NO", "COLUMN1", "COLUMN2", 11 more...]

I little confused, why in php array and js array looks like different, in php is separated into element, but in js is separated by comma.

<strong>UPDATE</strong>

Based suggestion below, I got a callback like this :

Object { 0="NO", 1="COLUMN1", 2="COLUMN2", more...} Object { 0="1", 1="NYK FUJI", 2="AJU150708 ", more...} Object { 0="2", 1="NYK FUJI", 2="AJU150708 ", more...}

So, I use for looping like this :

index = 1; $.each(response.isi, function (i, item) { $('#table-review').find('tbody').append("<tr>" + "<td>" + index + "</td>" + "<td>" + item.i + "</td>" + "</tr>"); index++; console.log(item); });

it gives me :

+---+-----------+ | 1 | undefined | | 2 | undefined | | 3 | undefined | +---+-----------+

Please advise.

Answer1:

in php encode it like this

echo json_encode(array( "nama_csv" => $name_csv, "path" => $csv, "isi" => $tryOne ), JSON_FORCE_OBJECT);

In ajax you have to parse it. As you seem to be using jquery then you can do like this

data = jQuery.parseJSON(response);

and then you get array. Use that like data.isi or data['isi']. Not sure which one of this will work according to your array type.

Answer2:

For the error after your update:

You are accessing the wrong index in your loop. See the corrected code:

var index = 1; $.each(response.isi, function (i, item) { $('#table-review').find('tbody').append("<tr>" + "<td>" + index + "</td>" + //"<td>" + item.i + "</td>" + // wrong: i doesn't exist as a property of item "<td>" + item[i] + "</td>" + // right: item array at index i will work "</tr>"); index++; console.log(item); });

Recommend

  • How to get info of an FTPFile
  • Adding counter to a loop inside a recursive method - Java
  • Android Delete Directory Not Working
  • Encrypt CSS external link and restrict access to it
  • Using for loop to move files from subdirectories to parent directories
  • Delete files that match regex
  • 'file_get_contents' The contents are encrypted?
  • Latest version of RSelenium and Firefox
  • Get File Creation Time
  • How to read CSV file and assign to Eigen Matrix?
  • How to sort an array considering localization?
  • Store array in cookie
  • Cookie multiple values
  • How to move a text file using Oracle
  • How to filter a range by first Character in a cell?
  • Handling null values with wso2 CEP
  • Recursive regex not matching template blocks
  • Index Multiple Columns w/ Ruby on Rails
  • Passing data from partial view inside a modal to the main view and then close the modal
  • Select from table that does not exist
  • Play WS (2.2.1): post/put large request
  • Can I check if a recipient has an automatic reply before I send an email?
  • Get data from AJAX - How to
  • FB SDK and cURL: Unknown SSL protocol error in connection to graph.facebook.com:443
  • Getting last autonumber in access
  • Different response to non-authenticated users and AJAX calls
  • How to limit post in wp_query
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • AngularJs get employee from factory
  • Benchmarking RAM performance - UWP and C#
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • -fvisibility=hidden not passed by compiler for Debug builds
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Memory offsets in inline assembly
  • Turn off referential integrity in Derby? is it possible?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Is it possible to post an object from jquery to bottle.py?
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize