Uchsun
Uchsun

Reputation: 361

How to take the second array in json?

I have use auto complete with json and php. it works, but now I need to get the second array from the json.

This my script on source.php

<?php

$req = "SELECT namaBarang, harga FROM masternamabarang WHERE namaBarang LIKE '%".$_REQUEST['term']."%' ";

       $query = mysql_query($req);

       while($row = mysql_fetch_array($query))
       {
           $results[] = array('label' => $row['namaBarang'],'harga' => $row['harga']);
       }

       echo json_encode($results);  
?>

and this script for autocomplate.php

<html>
   <head>

    <script src="js/jquery-1.9.1.js"></script>
    <script src="json/js/jquery-ui-1.10.3.js"></script>
    <script>
      $(function() 
      {
       $( "#NAMA" ).autocomplete({
           source: 'source.php'
      });
      });
    </script>

    <script>
    function ambil()
    {
    var x = document.getElementById('NAMA').value;

    document.getElementById('HARGA').value=x;   
    }
    </script>
</head>
<body>
  <form>
    <input type="text" name="NAMA" size="50" id="NAMA" onchange="ambil()"/><br>
    <input type="text" name="HARGA"  size="50"  id="HARGA" />

  </form>
</body>

The Autocomplete works well, but ALL I need is, take the second array[HARGA] from JSON array and fill it on text box HARGA.

I appreciate your answers.

Upvotes: 0

Views: 1566

Answers (2)

daremachine
daremachine

Reputation: 2788

your script.php works fine. It give you json result something like

[{"label":"laba","value":"vala"},{"label":"labb","value":"valb"}]

you can log (javascript) result in browser like this

console.log(data[0].value); // array index 0 for first row, you can try 1,2 etc...

you probably need select method to bind what was selected:

$( "#search" ).autocomplete({
      source: data,
      select: function( event, ui ) {
        console.log(ui); // log selected data row
        $('#mySelectedInput').val(ui.item.value); // bind value wherever you like
      }
 });

resources
http://api.jqueryui.com/autocomplete/#event-select
http://jqueryui.com/autocomplete/#custom-data

Upvotes: 1

Red Wolf&#39;s Husband
Red Wolf&#39;s Husband

Reputation: 145

echo json_encode($results[1]); 

Is this what you want?

Upvotes: 1

Related Questions