php - Getting extra values in json while fetching from MySQL -
i trying fetch data ajax call via json , access data after successful ajax call. purpose, wrote following code :
<?php error_reporting(e_all); ini_set('display_errors', 1); require_once('../include/functions.php'); // session_start(); if( isset($_post['bike_id'])) { $rows = array(); // echo " in isset"; $bike_id = $_post['bike_id']; // $modal_name = $_post['modal_name']; // $json['insertmodal'] = false; // json_decode($modal_name); json_decode($bike_id); $result = selectbike_modal($bike_id); while ( $row = mysqli_fetch_array($result)) { $rows[] = $row; } echo json_encode($rows); } else { echo "bike_id not set"; } ?>
now want access via javascript :
$('#choose_bike').on('blur', function (e) { e.preventdefault(); var bike_id = $('#choose_bike').val(); // var modal_name = $('#modal_name').val(); // // alert("bike_id " + bike_id); alert("on blur clicked."); if ( bike_id == "select bike") { $('#defaulterror').addclass("alert alert-danger"); $('#defaulterror').text("please choose bike"); } else { // alert("bike : " + bike_id); $.ajax( { url:'../admin/backend/getmodal.php', type:'post', data: { bike_id: bike_id}, datatype:"json", success:function(data) { alert(" in success"); var obj = json.parse(data); alert("object " +obj); }, error : function() { console.log(arguments); } } ); } });
i have 2 issues :
i not getting after :
alert(" in success");
means following not working :
var obj = json.parse(data); alert("object " +obj);
- the php response follows:
[{"0":"5","bike_modal_id":"5","1":"shahjahan","bike_modal_name":"shahjahan","2":"30","bike_id":"30"},{"0":"6","bike_modal_id":"6","1":"ram","bike_modal_name":"ram","2":"30","bike_id":"30"}]
i getting
"0":"5","bike_modal_id":"5"
extra. please me parse json correctly in javascript , getting required ajax values.
edit :
select bike_model looks :
function selectbike_modal($bike_id) { include("connectvars.php"); $query = "select * bike_model bike_id = '$bike_id'"; $result = mysqli_query($dbc,$query) or die('error in fetching'); // if ( mysqli_num_rows($result)) // return 0; // else return $result; // if ( () ) // { // return $result; // } // else // { // return 0; // } }
issue 1
since set datatype:"json"
in ajax properties, parsing returned data json.parse()
not needed, returned data object. can access objects doing data[0].bike_modal_name
.
issue 2
issue of duplicate values, ie. "0":"5","bike_modal_id":"5"
because default mysqli_fetch_array()
fetches result row both associative , numeric array. can either change
while ( $row = mysqli_fetch_array($result))
to
while ( $row = mysqli_fetch_array($result, mysqli_assoc))
or
while ( $row = mysqli_fetch_assoc($result))