I have a PHP file that gives me output in JSON Format. The code is below -
<?php
include 'configure.php';
$qr = "SELECT * FROM student_details";
$res= mysql_query($qr);
$i=0;
while($row = mysql_fetch_array($res))
{
$stud_arr[$i]["full_name"] = $row["full_name"];
$stud_arr[$i]["reg_no"] = $row["regno"];
$stud_arr[$i]["address"] = $row["address"];
$stud_arr[$i]["mark1"] = $row["mark1"];
$stud_arr[$i]["mark2"]= $row["mark2"];
$stud_arr[$i]["mark3"] = $row["mark3"];
$i++;
}
header('Content-type: application/json');
echo json_encode($stud_arr);
?>
This file when ran on my server, is giving me the result perfectly, i.e. all the student details and their marks as here -
[{"full_name":"Lohith","reg_no":"100","address":"street, lane","mark1":"90","mark2":"87","mark3":"88"},{"full_name":"Ranjeet","reg_no":"101","address":"dfkljg","mark1":"56","mark2":"45","mark3":"39"},{"full_name":"karthik","reg_no":"102","address":"askjldf","mark1":"85","mark2":"90","mark3":"100"}]
Now I am trying to display this on a HTML file using -
function getAllDetails()
{
var myTable = '' ;
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;
myTable += "<tr><td><b>No</b></td><td><b>Full Name</b></td><td><b>Mark1</b></td><td><b>Mark2</b></td><td><b>Mark3</b></td></tr>";var url = "json-example2.php";
$.getJSON(url, function(json) { $.each(json, function(v) {
myTable += "<tr><td>"+v.reg_no+"</td><td>"+v.full_name+"</td><td>"+v.mark1+
"</td><td>"+v.mark2+
"</td><td>"+v.mark3+
"</td></tr>"; });
$("#stud_tbl").html(myTable);});};
The above code is displaying a table but says "undefined" in each data cell of the table.
No Full Name Mark1 Mark2 Mark3
undefined undefined undefined undefined undefined
undefined undefined undefined undefined undefined
undefined undefined undefined undefined undefined
Please help on how to debug this.
The first parameter to jQuery.each() is the index of the value and second one the value.
Solution change $.each(json, function(v) { to $.each(json, function(i v) {
function getAllDetails() {
var myTable = '';
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>';
myTable += "<tr><td><b>No</b></td><td><b>Full Name</b></td><td><b>Mark1</b></td><td><b>Mark2</b></td><td><b>Mark3</b></td></tr>";
var url = "data.json";
$.getJSON(url, function(json) {
$.each(json, function(i, v) {
myTable += "<tr><td>" + v.reg_no + "</td><td>"
+ v.full_name + "</td><td>" + v.mark1
+ "</td><td>" + v.mark2 + "</td><td>"
+ v.mark3 + "</td></tr>";
});
$("#stud_tbl").html(myTable);
});
};
Demo: Plunker
$.each has two parameters one is index and another is value
$.each(json, function(index, value) {
myTable += "<tr><td>" + value.reg_no + "</td><td>"
+ value.full_name + "</td><td>" + value.mark1
+ "</td><td>" + value.mark2 + "</td><td>"
+ value.mark3 + "</td></tr>";
});
try the following. Here is demo at http://jsfiddle.net/H3cjC/3/
html is
<div class="tbl">
</div>
var data='[{"full_name":"Lohith","reg_no":"100","address":"street, lane","mark1":"90","mark2":"87","mark3":"88"},{"full_name":"Ranjeet","reg_no":"101","address":"dfkljg","mark1":"56","mark2":"45","mark3":"39"},{"full_name":"karthik","reg_no":"102","address":"askjldf","mark1":"85","mark2":"90","mark3":"100"}]'
data=$.parseJSON(data);
var myTable = '' ;
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;
myTable += "<tr><td><b>No</b></td><td><b>Full Name</b></td><td><b>Mark1</b></td><td><b>Mark2</b></td><td><b>Mark3</b></td></tr>";var url = "json-example2.php";
$.each(data, function(i,v) {
myTable += "<tr><td>"+data[i].reg_no+"</td><td>"+data[i].full_name+"</td> <td>"+v.mark1+
"</td><td>"+data[i].mark2+
"</td><td>"+data[i].mark3+
"</td></tr>";
});
$('.tbl').html(myTable);
You must use the second parameter of the each function.
function getAllDetails()
{
var myTable = '' ;
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;
myTable += "<tr><td><b>No</b></td><td><b>Full Name</b></td><td><b>Mark1</b></td><td><b>Mark2</b></td><td><b>Mark3</b></td></tr>";
var url = "SCRIPTNAME.php";
$.getJSON(url, function(json) { $.each(json, function(v, x) {
console.log("REG NR = "+x.reg_no);
myTable += "<tr><td>"+x.reg_no+"</td><td>"+x.full_name+"</td><td>"+x.mark1+
"</td><td>"+x.mark2+
"</td><td>"+x.mark3+
"</td></tr>"; });
$("#stud_tbl").html(myTable);
});
}
Related
I am trying to generate dynamically form in table and submit but there is problem in my code which is difficult for me solve,
$(document).ready(function() {
$('#btnsummary').on('click', function() {
var date = $('#dddeliverydate').val();
var soid = $('#sssoid option:selected').val();
$.ajax({
url: "tblsum.php",
method: "POST",
dataType: 'JSON',
data:
"&date=" +
date +
"&soid=" +
soid,
success: function(response) {
if ( response.length == 0 ) {
alert("NO DATA FOUND!");
}
else{
$("#tblsum tbody").empty();
var len = response.length;
for(var i=0; i<len; i++){
var invoiceno = response[i].invoiceno;
var shopname = response[i].shopname;
var paymentmode = response[i].paymentmode;
var finalamount = response[i].finalamount;
if (finalamount==0){
return false
}
else if (paymentmode=="Credit"){
var tr_str = "<tr>" +
"<td align='center'>" + invoiceno + "<input type='hidden' name='invoiceno[]' value='"+invoiceno+"'></td>" +
"<td align='center'>" + shopname + "</td>" +
"<td align='center'>" + paymentmode + "</td>" +
"<td align='center'>" + finalamount + "</td>" +
"<td align='center'><input type='number' id='finalamount' name='finalamount[]' value='0'></td>" +
"</tr>";
$("#tblsum tbody").append(tr_str);
}
else{
var tr_str = "<tr>" +
"<td align='center'>" + invoiceno + "<input type='hidden' name='invoiceno[]' value='"+invoiceno+"'></td>" +
"<td align='center'>" + shopname + "</td>" +
"<td align='center'>" + paymentmode + "</td>" +
"<td align='center'>" + finalamount + "</td>" +
"<td align='center'><input type='number' id='finalamount' name='finalamount[]' value='" + finalamount + "'></td>" +
"</tr>";
$("#tblsum tbody").append(tr_str);
}
}
$("#tblsum tbody").append("<tr><td colspan='5'><button class='btn btn-success' type='button' id='btnsum'onclick='summary()'>Save</button></td></tr>");
}
}
})
});
})
There is two problem if final amount is 0 then save button did not appear, when I submit form first field which is invoiceno don't submit on next page,
below is submit function
function summary(){
$(document).ready(function(e) {
var date = $('#dddeliverydate').val();
var soid = $('#sssoid option:selected').val();
var form = $('#formsum').serialize();
$.ajax({
url: "test.php",
method: "POST",
data:
"&date=" +
date +
"&soid=" +
soid+
"&form=" +
form,
success: function(data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
}
})
})
}
Below is my PHP code.
for($count = 0; $count<count($_POST['invoiceno']); $count++){
$data = array(
$invoiceno = $_POST['invoiceno'][$count],
$amount = $_POST['finalamount'][$count],
);
echo "Invoice NO ".$invoiceno." Amount ".$amount.'<br>';
}
sorry for bad english.
I told you before return STOPS executing a function, so all code after it is obsolete. In this case, when finalamount == 0 you stop executing the function and return to the place where it started. So the code to create the submit button never will be reached. With some proper indentation, you could see that:
$(document).ready(function() {
//<< ===== START START START of onclick function
$('#btnsummary').on('click', function() {
....
$.ajax({
url: "tblsum.php",
....
success: function(response) {
if ( response.length == 0 ) { .... }
else{
$("#tblsum tbody").empty();
....
for(var i=0; i<len; i++){
var invoiceno = response[i].invoiceno;
var finalamount = response[i].finalamount;
....
if (finalamount==0){
return false
// STOP EXECUTING THIS FUNCTION
// AND GO DIRECTLY TO END OF FUNCTION ================= >>
// code after this will NOT be executed
}
else if (paymentmode=="Credit"){....}
else{....}
}
// if finalamount == 0, this will never be executed
$("#tblsum tbody").append("<tr><td colspan='5'><button class='btn btn-success' type='button' id='btnsum'onclick='summary()'>Save</button></td></tr>");
}
}
})
});
// ===== END END END of onclick function << ===============
// continue executing script from here
})
So you could use continue instead of return to skip only one itteration in the for loop.
FYI, I am working on localhost with wampserver, using PHP and AJAX, trying to display the JSON data rows (which are around 1526). and the problem is i am not able to display the rows which are based on the search conditions.
Output of print_r($result_array); in console output as below. here in below pic don't worry for console error this error is becoz of PHP array used in parsing JSON. This output i used to test weather my server PHP file is working correctly or not but it is working correctly.
After that i checked my encoding function, for which output of echo json_encode($result_array); i am getting red console error for some search condition and in other search condition i am able to display results correctly.
For example, below two images
I am not able to figure out what is happening to my code.
File search.php
<?php
// send a JSON encoded array to client
include('connection.php');
$sqlFlag = 0;
function queryDelimiter(){
global $sqlFlag;
if ($sqlFlag == 0){
$sqlFlag = 1;
return ' WHERE ';
}else{
return ' AND ';
}
}
$selectSQL = "SELECT * FROM tbl_main_lead_info";
if(isset($_POST['lead_status']) and strlen(trim($_POST['lead_status'])) > 0){
$selectSQL .= queryDelimiter()."LeadStatus = '".$_POST['lead_status']."'";
}
if(isset($_POST['lead_owner']) and strlen(trim($_POST['lead_owner'])) > 0){
$selectSQL .= queryDelimiter()."LeadAddedBy = '".$_POST['lead_owner']."'";
}
if(isset($_POST['company_name']) and strlen(trim($_POST['company_name'])) > 0){
$selectSQL .= queryDelimiter()."Company = '".$_POST['company_name']."'";
}
if(isset($_POST['tech_area']) and strlen(trim($_POST['tech_area'])) > 0){
$selectSQL .= queryDelimiter()."TechArea = '".$_POST['tech_area']."'";
}
if(isset($_POST['firm_size']) and strlen(trim($_POST['firm_size'])) > 0){
$selectSQL .= queryDelimiter()."FirmSize = '".$_POST['firm_size']."'";
}
if(isset($_POST['firm_type']) and strlen(trim($_POST['firm_type'])) > 0){
$selectSQL .= queryDelimiter()."FirmType = '".$_POST['firm_type']."'";
}
if(isset($_POST['country_name']) and strlen(trim($_POST['country_name'])) > 0){
$selectSQL .= queryDelimiter()."Country = '".$_POST['country_name']."'";
}
if(isset($_POST['state_name']) and strlen(trim($_POST['state_name'])) > 0){
$selectSQL .= queryDelimiter()."State = '".$_POST['state_name']."'";
}
if(isset($_POST['city_name']) and strlen(trim($_POST['city_name'])) > 0){
$selectSQL .= queryDelimiter()."City = '".$_POST['city_name']."'";
}
if(isset($_POST['start_date']) and strlen(trim($_POST['start_date'])) > 0){
$selectSQL .= queryDelimiter()."LastContactDate >='".$_POST['start_date']."'";
}
if(isset($_POST['end_date']) and strlen(trim($_POST['end_date'])) > 0){
$selectSQL .= queryDelimiter()."NextContactDate <= '".$_POST['end_date']."'";
}
$selectSQL .= " ORDER BY FirstName ASC, LastName ASC, Lead_Id ASC";
$result_array = array();
$result = $conn -> query ($selectSQL);
if(mysqli_num_rows($result) > 0){
while ($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
// print_r($result_array);
echo json_encode($result_array);
// $selectSQL = "SELECT * FROM tbl_main_lead_info as M, tbl_campaign_info as C";
$conn->close();
?>
File loadtable.js
// This is script to load table based on filter section
$(document).ready(function() {
// Campaign Submit Info
$('[name="search_submit"]').click(function(e) {
$('#load-csv-file-button').attr('style','display:none;');
$("#filterRecords").attr('style','display:block;');
$('#add_lead_info').attr('style','display:none;');
e.preventDefault();
// GET the admin and user id value
var adminvalue = $('#filterformpost').find('[name="adminvalue"]').val();
var useridvalue = $('#filterformpost').find('[name="useridvalue"]').val();
var lead_owner = $('#filterformpost').find('#lead_owner_select option:selected').val();
var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
var city_name = $('#filterformpost').find('#city_name_select option:selected').val();
var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
var start_date = $('#filterformpost').find('#start_date_search').val();
var end_date = $('#filterformpost').find('#end_date_search').val();
// console.log('adminvalue: '+adminvalue)
// console.log('useridvalue: '+useridvalue)
// console.log('lead_owner: '+lead_owner)
// console.log('country_name: '+country_name)
// console.log('State: '+state_name)
$.ajax({
type: "POST",
url: "./server/search.php",
data: {
"lead_owner": lead_owner,
"lead_status": lead_status,
"company_name": company_name,
"tech_area": tech_area,
"firm_size": firm_size,
"firm_type": firm_type,
"country_name": country_name,
"city_name": city_name,
"state_name": state_name,
"start_date": start_date,
"end_date": end_date
},
beforeSend: function() {
$('.search_lead_filter_message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success:function(data){
// console.log(data)
console.log("Data Length: "+data.length)
console.log(data)
if(data.length == 0){
$('.search_lead_filter_message_box').html('');
$("#filterRecords").html('No results fetched');
}
var result = $.parseJSON(data);
// console.log(result)
//###########################################
// Pagination code start
//###########################################
$('.search_lead_filter_message_box').html('');
$("#filterRecords").empty();
//###########################################
// Pagination code end
//###########################################
$("#pagination").attr('style', 'display:block;');
$("#number_of_rows").attr('style','display:block;');
$('#button-prev-next').attr('style','display:block;');
paginate_json_data(result, adminvalue, useridvalue)
}
});
});
});
function paginate_json_data(userDetails, adminvalue, useridvalue) {
adminvalue = adminvalue
useridvalue = useridvalue
userDetails = userDetails
var table = '';
table = $("<table></table>");
$('#pagination').html('<div id="nav-numbers" class="col nav"></div>');
$('#number_of_rows').html('');
$('#number_of_rows').html('<p1>Total number of leads fetched: ' + userDetails.length + '</p1>');
$('#button-prev-next').html('<button class="col PreviousButton" id="PreValue"><i class="ion-skip-backward"></i> Previous</button><button class="col NextButton" id="nextValue">Next <i class="ion-skip-forward"></i></button>');
var max_size = userDetails.length;
var sta = 0;
var elements_per_page = 10;
var limit = elements_per_page;
if(max_size<10){
// #####################################
// NUMBER OF ROWS A < 10 START START
// #####################################
table.append('<thead><th>#</th><th>Name</th><th>Company</th><th>Website</th><th>Designation</th><th>Email</th><th style="width: 150px;">Phone</th><th>City</th><th>State</th><th>Country</th><th>Lead Status</th></thead>');
table.append('<tbody id="myTable"></tbody>');
goFun_Modified(sta, max_size);
function goFun_Modified(sta, limit) {
for (var i = sta; i < limit; i++) {
var tab = '<tr><td>' + (i+1) + "\n" + '</td><td>' + "<a target='_blank' href=./lead/index.php?lead_id=" + userDetails[i].Lead_Id + " </a>" + userDetails[i].FirstName + ' ' + userDetails[i].LastName + "\n" + '</td><td>' + userDetails[i].Company + "\n" + '</td><td>' + userDetails[i].Website + "\n" + '</td><td>' + userDetails[i].Designation + "\n" + '</td><td>' + "" + userDetails[i].Email + "" + "\n" + '</td><td style="width: 150px;" >' + userDetails[i].Phone + "\n" + '</td><td>' + userDetails[i].City + "\n" + '</td><td>' + userDetails[i].State + "\n" + '</td><td>' + userDetails[i].Country + "\n" + '</td><td>' + userDetails[i].LeadStatus + "\n" + '</td></tr>';
console.log(tab)
$('#myTable').append(tab)
}
} // Function ended
$("#filterRecords").html(table);
$('#nextValue').click(function() {
// checks if it's the last page
if (currentPage < maxPage) {
currentPage++;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("End of page");
}
});
$('#PreValue').click(function() {
// checks if it's the first page
if (currentPage > 0) {
currentPage--;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("Start of page")
}
});
var number = Math.round(userDetails.length / elements_per_page);
for (i = 0; i <= number; i++) {
$('.nav').append('<button class="nav-numbers btn" id=' + i + '>' + (i+1) + '</button>');
}
$('.nav button').click(function() {
var start = $(this).text()-1;
// $(this).css({"background-color": "#e67e22", "color": "#ffffff"});
$('#myTable').empty();
limit = 10 * (parseInt(start) + 1) > max_size ? max_size : 10 * (parseInt(start) + 1)
goFun_Modified(start * 10, limit);
let $self = $(this);
// gets index of button relative to it's siblings
// https://api.jquery.com/index/
currentPage = $self.index();
$pagingBtn.removeClass('active');
$self.addClass('active');
});
// saves all the paging buttons for reusing, instead of calling $() every time
let $pagingBtn = $('#nav-numbers .btn');
let maxPage = $pagingBtn.length - 1;
let currentPage = 0;
$('.nav button')[0].click()
// #####################################
// NUMBER OF ROWS A < 10 END
// #####################################
}else{
// #####################################
// NUMBER OF ROWS A > 10 START
// #####################################
table.append('<thead><th>#</th><th>Name</th><th>Company</th><th>Website</th><th>Designation</th><th>Email</th><th>Phone</th><th>City</th><th>State</th><th>Country</th><th>Lead Status</th></thead>');
table.append('<tbody id="myTable"></tbody>');
goFun(sta, limit);
function goFun(sta, limit) {
for (var i = sta; i < limit; i++) {
var tab = '<tr><td>' + (i+1) + "\n" + '</td><td>' + "<a target='_blank' href=./lead/index.php?lead_id=" + userDetails[i].Lead_Id + " </a>" + userDetails[i].FirstName + ' ' + userDetails[i].LastName + "\n" + '</td><td>' + userDetails[i].Company + "\n" + '</td><td>' + userDetails[i].Website + "\n" + '</td><td>' + userDetails[i].Designation + "\n" + '</td><td>' + "" + userDetails[i].Email + "" + "\n" + '</td><td>' + userDetails[i].Phone + "\n" + '</td><td>' + userDetails[i].City + "\n" + '</td><td>' + userDetails[i].State + "\n" + '</td><td>' + userDetails[i].Country + "\n" + '</td><td>' + userDetails[i].LeadStatus + "\n" + '</td></tr>';
$('#myTable').append(tab)
}
$("#filterRecords").html(table);
}// FUNCTION ENDED
$('#nextValue').click(function() {
var next = limit;
if (max_size >= next) {
def = limit + elements_per_page;
limit = def
$('#myTable').empty();
if (limit > max_size) {
def = max_size;
}
goFun(next, def);
}
// checks if it's the last page
if (currentPage < maxPage) {
currentPage++;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("End of page");
}
});
$('#PreValue').click(function() {
var pre = limit - (2 * elements_per_page);
if (pre >= 0) {
limit = limit - elements_per_page;
$('#myTable').empty();
goFun(pre, limit);
}
// checks if it's the first page
if (currentPage > 0) {
currentPage--;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("Start of page")
}
});
var number = Math.round(userDetails.length / elements_per_page);
for (i = 0; i <= number; i++) {
$('.nav').append('<button class="nav-numbers btn" id=' + i + '>' + (i+1) + '</button>');
if(i == number){
}
}
$('.nav button').click(function() {
var start = $(this).text()-1;
$('#myTable').empty();
limit = 10 * (parseInt(start) + 1) > max_size ? max_size : 10 * (parseInt(start) + 1)
goFun(start * 10, limit);
let $self = $(this);
// gets index of button relative to it's siblings
// https://api.jquery.com/index/
currentPage = $self.index();
$pagingBtn.removeClass('active');
$self.addClass('active');
});
// saves all the paging buttons for reusing, instead of calling $() every time
let $pagingBtn = $('#nav-numbers .btn');
let maxPage = $pagingBtn.length - 1;
let currentPage = 0;
$('.nav button')[0].click()
// #####################################
// NUMBER OF ROWS A > 10 END
// #####################################
}
}
Updated:
Try add content-type specs to http header:
header("Content-Type: application/json");
and set UNICODE feature in json_encode:
echo json_encode($result_array, JSON_UNESCAPED_UNICODE);
In my dynamic dropdown list, how would I change the option value ='" + data[i].toLowerCase() + to be a value of different column from database table? My PHP is returning two jsonencode values, "ID" and "Outcome." JSQuery works when it is just "Outcome" return but not when both "ID" and "Outcome." I have tried.
options += '"<option value ="+ value[i] + "'>" + data[i] + "</option>";
Below is my code.
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data, value)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += '"<option value ="+ value[i] + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctOutcome").change(); //<-Here
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
You have to return in your values from php in json array so you can use it like data[i].id and data[i].outcome, Or you can use $ajax instead of $getJSON and you use the succes function to display result.
this is my code to show values in list box.
$.ajax({
type: "POST",
data: queryvalue,
url: "inputaction.php",
success: function (data) {
switch (action) {
case "GetMake":
console.log(data);
var select = $("#promake");
select.empty();
for (var i = 0; i < data.length; i++)
{
select.append('<option value="' + data[i].id + '">' + data[i].make + '</option>');
}
break;
}
}
});
i get the result of lot of undefined values in select field. and i have attached an console result in image file, in console output is correct how to rectify this problem.
Console Output
Page Output
$type = mysqli_real_escape_string($conn, $_POST['type']);
$make = mysqli_real_escape_string($conn, $_POST['make']);
$query = "select * from assetmodel where typeid = '".$type."' AND makeid = '".$make."' ORDER by model ASC";
$result = RunQuery($query, $conn);
while($row = mysqli_fetch_array($result)){
$re = array(
'id' => $row['id'],
'model' => $row['model']
);
}
echo json_encode($re);
this is my action page
You have to use "JSON.parse":
var select = $("#promake");
select.empty();
var parse = JSON.parse(json);
for (var i = 0; i < parse.length; i++)
{
select.append('<option value="' + parse[i].id + '">' + parse[i].make + '</option>');
}
decode the json in success
success: function (data) {
var data = $.parseJSON(data);
switch (action) {
case "GetMake":
console.log(data);
var select = $("#promake");
select.empty();
for (var i = 0; i < data.length; i++)
{
select.append('<option value="' + data[i].id + '">' + data[i].make + '</option>');
}
break;
}
}
You have to specify the dataType as json
$.ajax({
type: "POST",
data: queryvalue,
url: "inputaction.php",
dataType: "json",
success: function (data) {
switch (action) {
and set the MIME type of your response to application/json before sending the data:
header('Content-Type: application/json');
echo json_encode($re);
Simple fix in client-side is as below. Just a condition check inside your loop.
for (var i = 0; i < data.length; i++)
{
if (typeof data[i].id != "undefined" && typeof data[i].make != "undefined" ) {
select.append('<option value="' + data[i].id + '">' + data[i].make + '</option>');
}
}
If you want to have clean data from DB itself, you have to repair your query. That will eliminate the root cause.
I have this php code
$jsonArray = array();
$sql = "SELECT ID,CLIENT FROM PLD_SERVERS";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$jsonArray[] = array('id'=>$row['ID'],'client'=>$row['CLIENT']);
}
echo json_encode($jsonArray);
And this js
function autosearchLoadServers()
{
$.post("php/autosearch-load-servers.php",function(data){
var toAppend = "";
for(var i = 0; i < data.length; i++){
toAppend += '<option value = \"' + data[i].id + '\">' + data[i].client + '</option>';
}
$("#serverSelect").empty();
$("#serverSelect").html(toAppend);
});
}
The problem is that i get only undefined values. How can this be? The values are in the JSON, i checked using firebug in mozilla so there has to be something with the data variable but i can't understand what. I tried different ways and no results.
Try specifying the datatype in the post call like this:
$.post("php/autosearch-load-servers.php",function(data){
var toAppend = "";
for(var i = 0; i < data.length; i++){
toAppend += '<option value = \"' + data[i].id + '\">' + data[i].client + '</option>';
}
$("#serverSelect").empty();
$("#serverSelect").html(toAppend);
}, "json");