How to add rows to jquery table from mysql query with ajax? - php

I need insert rows into a jQuery DataTable from AJAX. In AJAX I call a PHP file when I make a query to my mySql database, but I get show only a character in rows. It is because the format returned is incorrect, but I can't to parse the correct format.
$query = "..myquery..";
if ($row = mysql_fetch_array($sql)) {
do {
$arr []= $row['name'];
} while ($row = mysql_fetch_array($sql));
echo json_encode($arr); // Here I tried return array without json_encode and a lot of things...
}
I know that the format to add the rows with .DataTable().row.add() is the below, but I do not get the desired format.
[["Element software"], ["Software dist"],["Global envir"], ["Software"], ["Software list"]]
How can I get this format in the echo to returned this??
Thanks!

It is array of arrays, so you need to push an array to $arr, not a string:
$query = "..myquery..";
$arr = []; // init an empty array
// no need to do if() and do{}while() inside. You can just while(){} it
while($row = mysql_fetch_array($sql)){
$arr[]= [$row['name']]; // <== these square brackets do the trick
}
echo json_encode($arr); // still need to json_encode

do{
$arr[]= array($row['name']);
} while ($row = mysql_fetch_array($sql));
echo json_encode($arr);
Note the
$arr[]= array($row['name']);
instead of
$arr []= $row['name'];

One:two run mysql_fetch_array($sql) because php return null;
Two:code ajax for insert table .
$.ajax({
dataType:"json",
url:"recive.php",
type:"POST",
data:{id:id},
success: function(res){
for(var j=0;j<res.length;j++)
{
$("#tabel").append("<table ><tr><td style='width:100%;' > "+res[j].id+"</td></tr></table>");
}
}

Related

save table records in associative array in php

I have an associative array. After I select my records from my table (with two columns: objName,objCost), I want to save them in my array like this:
array(
'objName'=>$row['objName'],
'objCost'=>$row['objCost']
)
How should I do this?
This is my code:
$output = '';
$arr = array();
$sql = "SELECT * FROM obj WHERE objName LIKE '%" . $_POST["search"] . "%'";
$result = $db->query($sql) or die(mysql_error());
if ($result->rowCount() != 0) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
//here i should insert my rows into my array
}
$json_arr = json_encode($arr,JSON_UNESCAPED_UNICODE);
echo $json_arr;
} else {
echo 'Data Not Found';
}
According to your code,
$arr[] = ['objName'=>$row['objName'],'objCost'=>$row['objCost']];
Then you can encode the array and pick up the object on the other side with javascript or php. Which ever suits you
json_encode($arr);
In you Ajax success, get the objects and use the values as you deem fit
success: function (data) {data = JSON.parse(data);
for(var i = 0; i < data.length; i++){
alert(data[i].objName);
}
}
see jQuery loop over JSON result from AJAX Success? on how to loop through your results in jquery

Returning an array from a PHP query

I query my database with a PHP script that looks like this:
$query = "SELECT * FROM JKFactory WHERE ronde = '$ronde' AND moment = '$moment' AND klas = '$klas'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['afzetAG'];
echo ",";
}
This gives a result something like this:
10000,20000,30000,
I need this data to build a piegraph with chart.js.
chart.js works with arrays for the data. So the numbers should be returned as an array which I can put into an JavaScript variable which I can use with chart.js.
Another problem is the last comma. I have no idea how I can get rid of this comma.
Maybe these question are straightforward but I am relatively new in this field I really get stuck on this part.
You have the array and you'd put the comma after the results yourself. so try to declare an array like $arr before while and use array_push($arr,$row['afzetAG']) inside the while
To print your result like 1000,2000,3000... You can save the content into an Array and print it using implode:
$data = array();
while($row = mysql_fetch_array($result))
{
array_push($data, $row['afzetAG']);
}
echo implode(",",$data);
But if you want to use an Array from PHP to JavaScript you can do this:
<script type="text/javascript">
<?php
$data = array();
while($row = mysql_fetch_array($result))
{
array_push($data, $row['afzetAG']);
}
?>
var obj = <?php echo json_encode($data); ?>;
</script>
So now obj contains the Array ready to use in your JavaScript code.
$types = array();
while(($row = mysql_fetch_assoc($result))) { $types[] = $row['type']; }
ok i made it. To echo the result i used this:
$a = array();
while($row = mysql_fetch_array($result))
{
$b = $row['afzetAG'];
array_push($a,$b);
}
echo implode(",",$a);
This gives not an array i can use in javascript. In javascript i put the result in a variable myResult and than i used:
myResult = myResult.split(',');
this i could use in chart.js to build a pie chart.
Thanks guys. Now i can sleep.

How to dynamically save two associated values into an array and access them in js?

I'm currently saving $row 'id' from my database into an array. This array is then sent using json_encode back to my JS file, where I access it. This is working fine.
My issue is that I'm struggling to figure out how to add $row['vote_fb_name'] (string) to the same json callback array (in this case my callback is saved into $feedback)? $row['vote_fb_uid'] and $row['vote_fb_name'] appear in the same record.
My PHP - here I save my id's into the array:
while ($row = mysql_fetch_assoc($res))
{
$savedResultsInNewArray[] = $row['vote_fb_uid'];
}
$feedback = $savedResultsInNewArray;
I then do my callback which is received by my js file:
echo json_encode(array('returned_val' => $feedback));
In my JS I then run a for loop to access the id's:
for( var i = 0; i < data.returned_val.length; i++ ){
var returnedId = data.returned_val[i];
console.log("IDS HERE "+returnedId);
}
In this same for loop I'm looking to access the associated 'name'.
In PHP I figure I need to save my data as a two dimensional array, but how do I do that and afterwards how do I access it in my JS?
Try this method,
In PHP code
while ($row = mysql_fetch_assoc($res))
{
$feedback[] = array($row['vote_fb_uid'], $row['vote_fb_name']);
}
echo json_encode(array('returned_val' => $feedback));
In JS
for (i in data.returned_val) {
console.log("IDS HERE "+data.returned_val[i][0]);
console.log("NAME HERE "+data.returned_val[i][1]);
}
as a matter of fact, $feedback is already a 2-d array
$feedback = array();
while ($row = mysql_fetch_assoc($res))
{
$feedback[] = $row;
}
echo json_encode(array('returned_val' => $feedback));
or, in case of using PDO
echo json_encode(array('returned_val' => $stmt->fetchAll()));
of course you need to se
You could have your $row['vote_fb_uid'] be your array keys
while ($row = mysql_fetch_assoc($res)){
$savedResultsInNewArray[$row['vote_fb_uid']] = $row['vote_fb_name'];
}
$feedback = $savedResultsInNewArray;

ñ returns null - jQuery en PHP

I use jQuery to run a function in PHP to get data from the database.
$.ajax({
url: 'service.php',
data: { functie: type, param: radiobutton },
dataType: 'json',
success: function (data) {}
});
Everything works. Except the strings with special characters return as null in the succes function. For example: ñ
The answer for this is here explained:
Special characters break json returned to jQuery
But it doesn't work for me.
In php I tried:
$result = mysql_query("SELECT * FROM wines");
$array = array();
while($row = mysql_fetch_assoc($result)){
$array[]=htmlentities($row);
}
Who knows how to make sure everything returns in a good way?
In your while statement you're using htmlentities on an array, not a string (each key in the array is a column in the database).
You could do either of the following:
Use array_map:
while($row = mysql_fetch_assoc($result)){
$array[] = array_map("htmlentities", $row);
}
or change your while loop:
while($row = mysql_fetch_assoc($result)){
foreach ($row as $key => $value) {
$row[$key] = htmlentities($value);
}
$array[] = $row;
}

parse json in javascript

I load a php/json file. This is my json file:
echo '{';
echo '"position":[';
while($inhoud = mysql_fetch_array($result))
{
echo '{';
echo '"lat":"'.$inhoud['lat'].'",';
echo '"long":"'.$inhoud['long'].'",';
echo '}';
}
echo ']}';
This works. I want to load it in my javascript and do it like this:
$.getJSON('req/position.php', function(data) {
$.each(data, function(key, val) {
newLatLng = key;
});
});
but this doesn't work. It loads the file but i don't get this data. What should i do?
Thanks,
I think you have some syntax errors in the JSON output.
When you output "long" data, you append a comma , at the end, but you should not, because "long" is the last key of the object.
You print out an object in a while cycle. These objects are part of an array. So, except for the last one, you have to append a comma , after the closing }.
And, if I can ask, why you are not using the json_encode() PHP function, instead of build all the JSON string manually? With it, you build all the data as normal PHP array, and then encode (translate) it in JSON. You will avoid all these annoying syntax stuffs.
Just try it:
$data = array();
$data['position'] = array();
while($inhoud = mysql_fetch_array($result))
{
$data['position'][] = array(
"lat" => $inhoud['lat'],
"long" => $inhoud['long']
);
}
echo json_encode($data);
You have your co-ordinates defined in the array named position. You need to iterate through that. The Array contains objects with the properties lat and long. If you want to use the values, you should try something like:
$.getJSON('req/position.php'), function(data){
$.each(data.position, function(index, value){
var newLatLng = { latitude: value.lat, longitude: value.long };
});
});
Return proper header in PHP script
header('Content-type: application/json');
And it should work.
Also use json_encode to encode PHP values into valid JSON.
Constructing JSON in php through strings works but is primitive. Start constructing an array and use json_encode().
$arr = array();
while($inhoud = mysql_fetch_array($result)){
$temp = array();
$temp['lat'] = $inhoud['lat'];
$temp['long'] = $inhoud['long'];
$arr[] = $temp;
}
echo json_encode($arr);
If all that you select in your mysql query is 'lat' and 'long' you could also just place $inhoud into $arr inside your while loop like so.
while($inhoud = mysql_fetch_array($result)){
$arr[] = $inhoud;
}
If you do this just make sure you only select columns in your mysql query that you would want to output in JSON.
$.getJSON('req/position.php', function(data) {
var obj = JSON.parse(data);
// At this point, obj is an object with your JSON data.
});
Source: MDN

Categories