Search with jQuery.post and getJSON - php

I'm trying to built a search for a website and i'm having trouble in making it work right.
I want to get the query from POST (or link using GET) after submiting the form. post it to a php and return the json back to results div
.
I tried to post it with ajax but i cant make it right.
The url that returns json must have all the query values (cars.php?company_id=1&model_id=1&car_category=compact&priceFrom=min&priceTo=max&kmFrom=all&kmTo=all&yearFrom=all&yearTo=all) or retuns a specific query (with all the results from table)
$(document).ready(function () {
$("form1#submit").submit(function () {
$.ajax({
type: 'POST',
url: './system/feeds/cars.results.php',
data: $(this).serialize(),
success: function () {
$.getJSON('./system/feeds/cars.results.php', function (json) {
var output = '';
for (var i = 0; i < json.car.length; i++) {
output += '<div class="grid_12">';
output += '<div class="block3">';
output += '<img src="images/' + json.car[i].car_image + '" alt="" class="img_fleft img-rounded">';
output += '<div class="wrapper border_block">';
output += '<div class="marg2">';
output += '<div class="grid_6 alpha">';
output += '<strong>' + json.car[i].car_company + ' ' + json.car[i].car_model + ' ' + json.car[i].car_cc + '</strong><br>' + json.car[i].car_category + ', ' + json.car[i].car_combustible + ', ' + json.car[i].car_bhp + ' bhp</br></br>';
output += '<hr>';
output += '<p>' + json.car[i].car_description + '</p>';
output += 'read more';
output += '</div>';
output += '<div class="grid_3 omega">';
output += '<h4>Χρονολογία:</h4> <a class="btn">' + json.car[i].car_month + '/' + json.car[i].car_year + '</a><br>';
output += '<h4>Χιλιόμετρα:</h4> <a class="btn">' + json.car[i].car_km + '</a><br>';
output += '<h4>Τιμή:</h4> <a class="btn">€ ' + json.car[i].car_price + '</a><br>';
output += '</div>';
output += '</div>';
output += '</div>';
output += '</div>';
output += '</div>';
output += '<div class="clear"></div>';
}
$('#cars-results').html(output);
$('#car_counter').html(json.car.length);
});
}
});
});
});
The json php returns results when u POST a query like car.results.php?company_id=1&model_id=1
car.results.php - Demo code (not basic yet)
<? include ('../config.php');
if (isset($_REQUEST['company_id']) && isset($_REQUEST['model_id'])) {
$company_id = $_REQUEST['company_id'];
$model_id = $_REQUEST['model_id'];
$car_category = $_REQUEST['car_category'];
$priceFrom = $_REQUEST['priceFrom'];
$priceTo = $_REQUEST['priceTo'];
$kmFrom = $_REQUEST['kmFrom'];
$kmTo = $_REQUEST['kmTo'];
$yearFrom = $_REQUEST['yearFrom'];
$yearTo = $_REQUEST['yearTo'];
$result = mysql_query("SELECT * FROM `cars` WHERE `company_id` = '$company_id' AND `model_id` = '$model_id'") or die("Couldn’t get data from database");
} else {
$result = mysql_query("SELECT * FROM `cars` ORDER BY `datetime` DESC LIMIT 3") or die("Couldn’t get data from database");
}
// Create JSON
$json = array();
while($row = mysql_fetch_array($result)) {
$car = array('car_image' => $row['car_image'],
'car_link' => "car.php?id=".$row['car_id'],
'car_company' => $row['company_id'],
'car_model' => $row['model_id'],
'car_cc' => $row['car_cc'],
'car_category' => $row['car_category'],
'car_combustible' => $row['car_combustible'],
'car_bhp' => $row['car_bhp'],
'car_description' => $row['car_description'],
'car_month' => $row['car_month'],
'car_year' => $row['car_year'],
'car_km' => $row['car_km'],
'car_price' => $row['car_price']);
array_push($json,$car);
}
// header('Content-type: application/json');
echo "{\"car\":".json_encode($json)."}";
ob_flush(); ?>
Any suggestions ?

Related

Error in console output for json_encode to display the result in console?

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);

jQuery.Deferred exception: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined

$.post("#", params).then(function (response) {
if (obj['error'] != 1) {
var html = '';
for (var i = 0; i < response['data'].length; i++) {
console.log('data' + i, response['data'][i]);
html += '<tr>';
html += '<td>' + response['data'][i]['wallet_type'] + '</td>';
html += '<td>' + response['data'][i]['balance'] + '</td>';
html += '<td>' + response['data'][i]['wallet_address'] + '</td>';
html += '</tr>';
}
}
});
I found
Uncaught TypeError: Cannot read property 'length' of undefined
in the console for that i cannot able to display my result.
First you need to check your response array in console something missing in your response.i think your response array does not set.
ex. console.log(response);
<script>
var response={"data":[{"id":556,"user_id":333,"email":"alokkr#dispostable.com","name":"alokkr#dispostable.com","wallet_id":"5ab7dfaa39062807cc3d0659a5ee9634","wallet_address":"QNqpGLNDhsCLWsqbz4joJHnh7QBQYhWQhz","wallet_type":"ltc","balance":0,"is_custom":false,"is_test":"0","created":"2018-03-25T17:44:50","updated":null},],"error":0,"msg":[]}
//console.log(response['data'].length);
var html='';
for (var i = 0; i < response['data'].length; i++) {
console.log('data' + i, response['data'][i]);
html += "<table border='1'>";
html += "<tr>";
html += '<td>' + response['data'][i]['wallet_type'] + '</td>';
html += '<td>' + response['data'][i]['balance'] + '</td>';
html += '<td>' + response['data'][i]['wallet_address'] + '</td>';
html += '</tr>';
html += '</table>';
}
document.write(html);
</script>

Change the way time is displayed in query

I fetch a series of times from the database which represent competitors lap times. I have got the database set as TIME which shows 00:00:00. It also adds up the total at the end.
I am wanting to change it so that it does not show all the 0's if for example a time of 53 seconds is entered (0:53) would be shown. I want to do this just to tidy the webpage up. Same for the total that shows 00:00:53 for the above example I would prefer it to be 0:53. If there is a minutes included to show 1:53, ten minutes 10:53, hour 1:10:53 etc.
<?php
//MySqli Select Query
$results = $mysqli->query("SELECT *, TIME(r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9 + r10 + r11 + r12 + r13 + r14 + r15 + r16 + r17 + r18 + r19 + r20 + r21 + r22 + r23 + r24 + r25 + r26 + r27 + r28 + r29 + r30 + r31 + r32 + r33 + r34 + r35 + r36 + r37 + r38 + r39 + r40 + r41 + r42 + r43 + r44 + r45 + r46 + r47 + r48 + r49 + r50) AS total FROM test");
$title = $mysqli->query("SELECT * FROM test_info");
$all_cols=array("rt1" => "r1","rt2"=> "r2","rt3"=> "r3","rt4"=> "r4","rt5"=> "r5","rt6" => "r6","rt7"=> "r7","rt8"=> "r8","rt9"=> "r9","rt10"=> "r10","rt11" => "r11","rt12"=> "r12","rt13"=> "r13","rt14"=> "r14","rt15"=> "r15","rt16" => "r16","rt17"=> "r17","rt18"=> "r18","rt19"=> "r19","rt20"=> "r20","rt21" => "r21","rt22"=> "r22","rt23"=> "r23","rt24"=> "r24","rt25"=> "r25","rt26" => "r26","rt27"=> "r27","rt28"=> "r28","rt29"=> "r29","rt30"=> "r30","rt31" => "r31","rt32"=> "r32","rt33"=> "r33","rt34"=> "r34","rt35"=> "r35","rt36" => "r36","rt37"=> "r37","rt38"=> "r38","rt39"=> "r39","rt40"=> "r40","rt41" => "r41","rt42"=> "r42","rt43"=> "r43","rt44"=> "r44","rt45"=> "r45","rt46" => "r46","rt47"=> "r47","rt48"=> "r48","rt49"=> "r49","rt50"=> "r50",);
while ($t = $title->fetch_assoc()){
// remember empty cols
$empty_cols=array();
echo "<table width=\"100%\" cellpadding=\"5\" cellspacing=\2\" class=\"entrywriting\" align=\"center\">
<tr align=\"center\">
<td>Overall</td>
<td>Competitor</td>";
foreach ($all_cols as $col => $value) {
if (!empty($t[$col])) {
echo "<td>" . $t[$col] . "</td>";
} else {
// set this column as empty for later
$empty_cols[]=$col;
}
} unset($col); unset($value);
echo "
<td>Total</td>
</tr>";
}
//set counter
$counter = 1;
while($row = $results->fetch_assoc()) {
echo "<tr align=\"center\">";
echo "<td>" . $counter . "</td>";
echo '<td>'.$row["driver"].'</td>';
foreach ($all_cols as $col => $value) {
if (!in_array($col, $empty_cols)) {
// echo non-empty values
echo '<td>'.$row[$value].'</td>';
}
} unset($col); unset($value);
echo '<td>'.$row["total"].'</td>';
$counter++; //increment count by 1
}
echo "</table>";
?>
So I need r1 - r50 to only show times entered in brief rather than full 00:00:00 and total to do the same.
So I have added just under select * from test_info
function timeformat($time) {
// Convenience identifiers
$hh = 0; $mm = 0; $ss = 0;
// Explode the time
$timecomp = explode($time);
// Analyse and return
if ($timecomp[$hh] = "00" && $timecomp[$mm] = "00") {
return '0:'.$ss;
} else
// Continue remaining tests from hereon
if ($timecomp[$hh] = "00" && $timecomp[$mm] = "01") {
return ':'.$mm.$ss;
}
}
I have replace two lines in the code to
echo '<td>'.timeformat($row[$value]).'</td>';
echo '<td>'.timeformat($row["total"]).'</td>';
I am getting
explode() expects at least 2 parameters, 1 given in
You could write a function which takes the time in the hh:mm:ss format and returns a string in the format you want.
Code for the function:
function formattime($time) {
$timecomp = explode(':', $time);
$hh = (int) $timecomp[0]; // Cast as integer
$mm = (int) $timecomp[1]; // Cast as integer
$ss = $timecomp[2]; // Keep '00' format
if ($hh == 0) {
return $mm.':'.$ss;
} else {
return $hh.':'.$mm.':'.$ss;
}
}
Executing:
echo (formattime('00:00:53')); echo '<br>';
echo (formattime('02:00:53')); echo '<br>';
echo (formattime('00:07:53')); echo '<br>';
gives:
0:53
2:0:53
7:53

Data tabulation table

basically I need help to display data in a table using the "td" and "tr" tags.
html += '<table class="table table-striped">';
for(var i in value){
if(!number_regex.test(i)){
html += '<tr>';
html += '<td>' + i + '</td>';
if(i == 'image_link'){
html += '<td> : ' + '<img src=' + value.image_link + ' alt>' + '</td>';
}
else{
html += '<td> : ' + value[i] + '</td>';
}
html += '</tr>';
}
}
html += '</table><br/>';
This is my current code where the value is an object. This outputs one "td" in each "tr". I'm trying to align 2 "td"s in one "tr". However, this cannot be accomplished through next(i) or (i+1) as it isn't a number.
This is what I have tried so far to no avail:
html += '<td>' + next(i) + '</td>';
if(next(i) == 'image_link'){
html += '<td> : ' + '<img src=' + value.image_link + ' alt>' + '</td>';
}
else{
html += '<td> : ' + value[next(i)] + '</td>';
}
and:
html += '<table class="table table-striped">';
html += '<tr>';
for(var i in value){
if(!number_regex.test(i)){
html += '<td>' + i + '</td>';
if(i == 'image_link'){
html += '<td> : ' + '<img src=' + value.image_link + ' alt>' + '</td>';
}
else{
html += '<td> : ' + value[i] + '</td>';
console.log(data);
}
for(var counter = 0; counter <= 8; counter++){
//8 because there are 9 fields in the query I want to display
if(counter % 2 == '0'){
html += '</tr>';
html += '<tr>';
}
}
}
Any idea guys?
These are the additional information that some of you requested:
A picture of the table I have atm:
https://www.dropbox.com/s/kmhkwturtmcxovh/lala.png
and as for the html, this is a javascript syntax, which is why I'm using html in this manner.
Take a variable and place it in the loop, which does the job of ending the rows by adding </tr>...something like :
This is what you have right now :
html += '</tr>';
amend it to something like :
$var = 0; /* initiaize it somewhere outside for(var i in value) */
if(++$var < 2)
{
/* do not echo </tr> if 2 td's haven't been added */
}
else /* 2 td's have been added, end this row */
{
$var = 0; /* reset counter*/
html += '</tr>'; /* end rows */
}

php json jquery and select box

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");

Categories