How to load numbers into MySQLi fetch_array() function - javascript

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.

Related

ajax not work and not show php data

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
}
}

Dynamically Create JavaScript Object From MySQL Table

Lets say I have this table mytable
id | name | x | y
I pull the the rows from mytable and create JavaScript objects with it like so:
PHP
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<script type="text/javascript">';
echo "new Object({$row["id"]}, '{$row["name"]}', {$row["desk_x"]}, {$row["desk_y"]});";
echo '</script>';
}
}
JS
function Object(id, name, x, y) {
var obj = {
id:id,
name:name,
x:x,
y:y
};
}
At the moment this is fine but lets say I want to add another column color to mytable
Basically I'm asking what do I write in PHP and JS to make this object dynamically, so you can have any columns and the Object object will just add a new property with the name of the column?
You can use AJAX to send data from serverside to clientside. Lets say you have a PHP file called script.php with your code:
if(isset($_GET['action']) && $_GET['action'] == 'testing'){
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo json_encode($result);
}
}
And lets say you have a JS file called script.js. Here you will do your AJAX call towards the PHP script file like this:
$.ajax({
type: 'GET',
url: 'script.php',
data: { action: 'testing' },
success: function(response){
console.log(response); //here you will have access to the object returned from the PHP script
}
})
I guess what you're looking for is how to do this without AJAX (which you don't really need here).
Put the objects in an array, then output your JS variable:
PHP:
$rows = [];
if ($result->num_rows)
while($row = $result->fetch_assoc()) $rows[] = $row; // append to array
echo "<script> var objArray = " . json_encode($rows) . "; </script>";

convert php array to js selectpicker array format

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

ajax function not working fine

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.

How to get my data back

I'm new to dynamic data and trying to
read data from a mysql database using PHP
turning this data to JSON
fetching the data through javascript (jQuery)
Inserting it into my page.
As far as I can see, 1) and 2) work fine, 3) seems to kind of work and 4) is where it breaks.
I've set up the database and the table, query & echo the data like so (api.php)
<?php
include 'db.php';
$con = new mysqli($host,$user,$pass,$databaseName);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM $tableName";
$myArray = array();
if ($result = $con->query($query)) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$con->close();
?>
Now I get it through javascript...
jQuery(function($) {
$.ajax({
url: 'php/api.php',
data: "json",
dataType: "",
success: function(data) {
var r = new Array(), j = -1;
for (var key=0, size=data.length; key<size; key++){
r[++j] ="<tr><td>";
r[++j] = data[key][0];
r[++j] = "</td><td>";
r[++j] = data[key][1];
r[++j] = "</td><td>";
r[++j] = data[key][2];
r[++j] = "</td></tr>";
}
var joined = r.join('');
console.log(joined);
$('#maintable tbody').html(joined);
}
});
});
... and throw it in the tbody element of my table.
The result is absolutely not what I expected:
See http://i.imgur.com/hRNrmdC.jpg (sorry for the partly german interface)
The Answer to the GET request is valid JSON, at least in theory (checked by http://jsonlint.com/ ), but to me it seems the data is treated as a string and split into an array of chars (each char a "key" in data[]), therefore "data[key][1] returns nothing.
var json = JSON.stringify(eval("(" + data + ")"));
and continuing with json[key][0] didn't help...
Now I wonder why and especially, what went wrong and how its fixed.
You have mixed up the keys in your ajax call:
data: "json",
dataType: "",
Should be:
dataType: "json",
as you are not sending or using any data at all.

Categories

Resources