This is how I build sql data and send back to ajax call:
(...)
$sql = "SELECT id_option FROM options WHERE id_win = '{$id_win}'";
$result = mysqli_query($conn, $sql);
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
$data["win_data"] = $rows;
echo json_encode($data);
This is my ajax function to get options for selectpicker from DB:
$.ajax({
type: "POST",
url: ...,
data: ...,
dataType: "json",
success: function(data) {
$("#id_win").selectpicker("val", data.win_data);
// $("#id_win").selectpicker("val", [1,3];
}
});
data.win_data variable should be: [1,3]
but if I do:
console.log(JSON.stringify(data.win_data));
I get:
[{"0":"1","id_option":"1"},{"0":"3","id_option":"3"}]
What is the simplest way to get proper format array for selectpicker?
It is because $row is an array. Look: https://secure.php.net/manual/pt_BR/mysqli-result.fetch-array.php
You have to use like this:
(...)
$sql = "SELECT id_option FROM options WHERE id_win = '{$id_win}'";
$result = mysqli_query($conn, $sql);
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row['id_option'];
}
$data["win_data"] = $rows;
echo json_encode($data);
forget about mysqli and use PDO, it has everything you need.
$stmt = $pdo->prepare("SELECT id_option FROM options WHERE id_win = ?");
$stmt->execute([$id_win]);
$data["win_data"] = $stmt->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($data);
this code is 2 times shorter and 100 times more secure
Related
I want a dependent select box I can load the data from my database into the select box however, when I click the show all countries when all select boxes have data only the province will return to the default data. What I need to do is when I click show all countries all the data from select box will reset to its default data and so on and so forth.
AJAX Script:
$(document).ready(function(){
//Show Province
$("#sort-country").change(function(){
var country = $(this).val();
$.ajax ({
url:"fetch_province.php",
method: "POST",
data: {country:country},
dataType: "text",
success: function(data){
$("#sort-province").html(data);
}
});
});
//Show Town
$("#sort-province").change(function(){
var country = $("#sort-country").val();
var province = $(this).val();
$.ajax ({
url:"fetch_town.php",
method: "POST",
data: {country:country, province:province},
dataType: "text",
success: function(data){
$("#sort-town").html(data);
}
});
});
//Show Barangay
$("#sort-town").change(function(){
var country = $("#sort-country").val();
var province = $("#sort-province").val();
var town = $(this).val();
$.ajax ({
url:"fetch_barangay.php",
method: "POST",
data: {country:country, province:province, town:town},
dataType: "text",
success: function(data){
$("#sort-barangay").html(data);
}
});
});
});
Fetch Province:
<?php
require "connect.php";
$output = "";
$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' ORDER BY province";
$result = mysqli_query($conn, $sql);
$output = "<option value=''>Show All Province</option>";
while ($row = mysqli_fetch_array($result)) {
$output .= "<option value='".$row['province']."'>".$row['province']."</option>";
}
echo $output;
?>
Fetch Town:
<?php
require "connect.php";
$output = "";
$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' AND province='".$_POST['province']."' ORDER BY town";
$result = mysqli_query($conn, $sql);
$output = "<option value=''>Show All Town</option>";
while ($row = mysqli_fetch_array($result)) {
$output .= "<option value='".$row['town']."'>".$row['town']."</option>";
}
echo $output;
?>
Fetch Barangay:
<?php
require "connect.php";
$output = "";
$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' AND province='".$_POST['province']."' AND town='".$_POST['town']."' ORDER BY barangay";
$result = mysqli_query($conn, $sql);
$output = "<option value=''>Show All Barangay</option>";
while ($row = mysqli_fetch_array($result)) {
$output .= "<option value='".$row['barangay']."'>".$row['barangay']."</option>";
}
echo $output;
?>
when one record then show data when multiple record come then not show data other site.
ajaxx.php
<?php
include 'database.php';
session_start();
$post = $_POST;
$search = $post['search'];
$searchType = $post['searchType'];
if ($searchType == 'all')
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND (type='Bukhari' OR type='Muslim') ";}
else
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND type='$searchType' ";}
$result = mysqli_query($db,$sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row['title'];
echo json_encode($row);
}
} else
{ echo "Not Found Result" ; }
?>
when data record is one then append the data successfully when multiple record come then not show data and append not work
javascript code
function searchh()
{
var type = $("input[name='type']:checked").val();
var searchhh = $( ".myButton option:selected" ).text();
debugger;
$.ajax({
url: 'ajaxx.php',
type: "POST",
data: {'searchType':type, 'search':searchhh},
success: function (data) {
var duce = jQuery.parseJSON(data);
alert(duce.title);
}
});
}
I think your issue is in the while loop. You don't want to encode each row one-by-one, but as a whole like this.
$myResults = [];
while($row = $result->fetch_assoc()) {
$row['title'];
$myResults[] = $row;
}
echo json_encode($myResults);
You are producing invalid JSON by using echo json_encode($row); within a loop.
Try to craft an array of rows, and then display it.
if($result->num_rows > 0)
{
$output = array();
while($row = $result->fetch_assoc())
{
output[] = $row;
}
if($searchType == 'all')
{
echo json_encode($output);
}
else
{
echo json_encode(current($output)); // print just one
}
}
I have a text field in which i am getting a string like that
say name / contact / address
and i get this value on button click function when i pass this value to php function via ajax. it returns nothing, i don't know what is wrong with my code.
here is the ajax function:
$("#load").click(function()
{
//alert("this comes in this");
var data1 = $("#country_id").val();
$.ajax({
alert("ajax start");
url: 'ajax_submit.php',
type: 'Post',
dataType: 'json',
data:{getRespondents:"getRespondents", data:data1},
success: function(e){
alert(e);
$("#rCategory").val(e.respondents[0]['category']);
$("#gender").val(e.respondents[0]['gender']);
$("#rAddress").val(e.respondents[0]['address']);
$("#rContact").val(e.respondents[0]['contact']);
alert("In this");
}
});
});
and in ajax_submit.php function is like that:
if($_POST["getRespondents"] == "getRespondents"){
$regionID= $_POST["data"];
$obj = new controller();
$result = $obj->getRespondents($regionID);
$json = array("respondents"=>$result);
echo json_encode($json);
exit();
}
In class function is written as:
function getRespondents($a){
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("demon", $connection); // Selecting Database
list($number1, $number2, $number3) = explode('/', $a);
//$sql = "SELECT r.id, r.name, r.contact, r.address from respondent as r ORDER BY r.name";
$sql = "SELECT * FROM respondent as r WHERE r.name = '".$number1."' and r.contact = '".$number2."' and r.address = '".$number3."' "
$rsd = mysql_query($sql);
$row= array();
$i=0;
while($rs = mysql_fetch_array($rsd)) {
$row[$i]["id"] = $rs ['id'];
$row[$i]["name"] = $rs ['name'];
$row[$i]["contact"] = $rs ['contact'];
$row[$i]["address"] = $rs ['address'];
$row[$i]["category"] = $rs ['category'];
$row[$i]["gender"] = $rs ['gender'];
$i++;
}
return $row;
}
I want to populate those values in given select boxes when user selects something from autocomplete function.
what are possible soultions to this problem? thanks
First of all why you use alert at the beginning of ajax? remove that alert because it might give you JavaScript error.
Using following MySQLi and PHP snippet I can export the result in a numeric array as:
["8","188.396496","7.876766","69885005.45"]
Now I need to have the output in exact numeric format like (removing " " from the items)
[8,188.396496,7.876766,69885005.45]
and here is the code I have in PHP part
$query = "SELECT project, powerline, road, cost FROM `charts_econo_new`" ;
$results = $con->query($query);
if($results) {
while($row = $results->fetch_array(MYSQLI_NUM)) {
$json=json_encode($row);
}
}
$con->close();
echo $json;
?>
How can I do that?
Update
var req2 = $.ajax({
type: "POST",
data: data,
dataType: 'json',
url: "assets/tempchart.php"
});
req2.done(function(data) {
var cars = [];
cars.push(data)
console.log(cars[0]);
in this case the out out is [8,188.396496,7.876766,69885005.45] but I need to get ONLY 8 as cars[0] is 8.
if ($results) {
$row = $results->fetch_array(MYSQLI_NUM);
$row = array_map('floatval', $row); // Convert strings to numbers
echo json_encode($row);
}
The Javascript should be:
req2.done(function(data) {
var cars = [];
cars.push(data[0]);
console.log(cars[0]);
});
You just have to cast your results to float before calling json_encode :
$query = "SELECT project, powerline, road, cost FROM `charts_econo_new`" ;
$results = $con->query($query);
if($results) {
while($row = $results->fetch_array(MYSQLI_NUM)) {
// Cast to float
foreach($row as &$item) {
$item = (float) $item;
}
$json=json_encode($row);
}
}
$con->close();
echo $json;
(And you are only getting the last row of your table, because you overwrite the content of $json each time but if you only have one row in your table that can be ok)
Please try to use floatval() function to convert string from DB in float values.
filePHP.php
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$json = array('id' => $row['id_kategori'], 'nama' => $row['nama_kategori']);
echo json_encode($json);
}
and index.php
$.post('filePHP.php', function(data){
console.log(data);
},'json');
but this not working, what would solve this problem?
Try this in PHP
$query = $kon->prepare("SELECT id_kategori,nama_kategori FROM t_kategori");
$query->execute();
$json=array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$arr=array('id'=>$row['id_kategori'],'nama'=>$row['nama_kategori']);
array_push($json,$arr);
}
echo json_encode($json);
Read array-push
try something like this , your code will echo json in wrong format whereas below code will give you json array.
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
$json_arr =array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$temp_arr = array();
$temp_arr['id'] => $row['id_kategori'];
$temp_arr['nama'] => $row['nama_kategori'];
array_push($json_arr,$temp_arr);
}
echo json_encode($json_arr);