jstfsklh211 79 Light Poster

Some browsers will resort a json array by index to make access faster, I understand this.

The problem is that when I pass my json object to jeditable using the data setting, in those browsers my options dont come out in the order I need them (Alphabetic).

PHP creating the array

foreach($arrStations as $arrStation){
     $arrJSONStations[(string)$arrStation['station_id']]=$arrStation['station_name'];
}

JS/PHP dumping array into jeditable

$('.typeStation').editable('editable_ajax.php', {
    submitdata : {target_table: "<?php print ip_address?>", action_taken:"update", key_column_name:"<?php print ipID?>", related_table:"station", related_column_name:"station_name"},
    indicator : 'Saving...',
    tooltip   : 'Click to edit...',
    data   : "<?php print addslashes(json_encode($arrJSONStations))?>",
    type   : 'select',
    submit : 'OK'
}

Dani AI

Generated

Short answer: the order loss comes from using an object whose keys are "integer-like" (station IDs). Modern JS engines enumerate integer property names in sorted order per the ECMAScript rules, so an object created from your PHP associative array will not preserve insertion order in all browsers. See the spec and MDN for the property-enumeration details: ECMAScript spec — OrdinaryOwnPropertyKeys and MDN — Object.keys (note on order).

Practical fixes for

  1. Server-side: emit a semicolon-separated key:value string (jEditable parses that in order). Escape colons/semicolons in labels and embed it safely with json_encode so the string arrives intact in JS.
$options = array();
foreach ($stations as $st) {
  $label = str_replace(array('\\', ':', ';'), array('\\\\', '\:', '\;'), $st['name']);
  $options[] = $st['id'] . ':' . $label;
}
$optionsString = implode(';', $options);
// echo into JS with json_encode($optionsString)
  1. Client-side: send a JSON array (ordered list) from PHP and let data be a function that builds the ordered string or HTML options. That preserves order because arrays keep order; then return the semicolon string or option HTML to jEditable.
data: function() {
  var stations = /* server JSON array embedded via json_encode */;
  return stations.map(function(s){
    return s.id + ':' + s.name.replace(/[:;]/g, function(m){ return '\\' + m; });
  }).join(';');
}

Troubleshooting tips

  • Confirm order in the browser with console.log(Object.keys(obj)) or inspect the JSON payload.
  • Avoid hacks like addslashes(json_encode(...)); use json_encode to safely embed strings or fetch options via AJAX (loadurl) so you avoid quoting/escaping errors.
  • If you must keep numeric keys but avoid sorting, either prefix keys (and strip the prefix on submit) or use an ordered format (array/semicolon string) as shown.

jEditable docs for formats: .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.