Monday 1 July 2013

How to get multiple value in AJAX success using json Encode

json.php

 <script type="text/javascript" language="javascript" src="jquery.js" ></script> // jQuery library   
  <script>   
  $(document).ready(function(){   
  $('#fname').change(function(){ // will be trigger when you select value in selectbox   
   var id = $(this).val(); // store selected value in 'id' variable   
   var ajax_value_file="search.php"; // process file   
   $.ajax // ajax call   
     ({   
      type: "POST",   
      url: ajax_value_file,   
      dataType: "json", // must be defined to use json   
      data: "id="+id,   
      success: function(mydata) // "mydata" will be return from search.php as a json encoded string.   
       {   
       $('#lname').val(mydata.lname); // use mydata as object and get data from string and place it wherever you want. in this case it'll be stored in an input with an ID "lname"   
       $('#mobile').val(mydata.mobile);   
       }   
     });   
  });   
  });   
  </script>   
  <form name="test">   
  First Name : <select id="fname" name="fname">   
  <option value="">Select to get details</option>   
  <option value="1">Test 1</option>   
  <option value="2">Test 2</option>   
  <option value="3">Test 3</option>   
  </select><br/>   
  Last Name : <input type="text" name="lname" id="lname"value=""/><br/> //will be come after select any of first name...   
  Mobile No :<input type="text" id="mobile" name="mobile" value=""/>   
  <input type="button" onclick="javascript:alert('bingo....dude..You`ve made it')" value="Check" />   
  </form>  

search.php

 <?php   
  include_once('config.php'); // Your configuration file path. To connect with database   
  if($_POST['id']!="") {   
  $id=$_POST['id'];   
  $select = "select * from jason where id='".$id."'";   
  $data=$db->select($select);   
  $lname = $data[0]['lname'];   
  $mobile = $data[0]['mobile'];   
  echo $html= json_encode(array("lname" =>$lname,"mobile " => $mobile));  // It will convert this array in json string   
  }   
  ?>