How do I display this array correctly in html? - javascript

I'm sending array from Php to Javascript, then I try to generate a div for each value of that array to display them in html, but instead of making a div for each independent value it stacks them all on a single one. It seems the array I'm making in php arranges all the values from my database into single string.
How can I separate them?
Here's how the error looks upfront
Here's part of my code:
Php:
$query= "SELECT titulo FROM notas WHERE usuario_idusuario = '".$ide."'";
//Runs the search
$resultado = $conn->query($query);
if($resultado->num_rows>0){
while($row = $resultado->fetch_assoc()){
//inserts result in an array
$contenido= array('titulo'=> $row['titulo']);
//json_encode
$objJson = json_encode($contenido["titulo"]);
//sends the array to javascript
echo "$objJson\n";
}
}else{
echo "Error";
}
$conn->close();
?>
javascript:
//response receives the array
success: function(response){
console.log(response);
console.log(response.length);
var contenidoInt = new Array();
contenidoInt = [{
"titulo":response
}];
console.log(contenidoInt);
console.log(contenidoInt[0].titulo);
}
I hope someone can help me, thanks.

Related

Return data from PHP to JavaScript using AJAX - data type error?

I am using AJAX to return a query to my JavaScript function, but I am having an issue returning the json_encode. I might have an error in the data type somewhere, but thought to check here for some advice.
This is my AJAX request:
$.ajax({
url: 'testajax.php',
method: 'POST',
data: {value},
dataType:'json',
success: function(data){
console.log(data);}
});
This is my PHP script:
<?php
require 'login.php';
$connection = new mysqli($host, $user, $pword, $database, 3306);
$insertquery = $connection->prepare("SELECT tracking_type, tracking_change_date, vessel_fcm_new, vessel_hull_id_new, vessel_name_new, vessel_length_new, vessel_manufacturer_new, vessel_manufacturer_id_new, vessel_year_new, vessel_value_new, owner_id_new, loss_payee_id_new, policy_id_new, policy_start_date_new, policy_end_date_new FROM tracking WHERE tracking_type = ?");
$insertquery->bind_param("i", $trackingtype);
//$trackingtype = $_POST['value'];
$trackingtype = 1;
$insertquery->execute();
$insertquery->bind_result($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
while ($insertquery->fetch()){
$data = array($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
echo json_encode($data);
}
If I only have 1 row matching this query, then it works fine. But as soon as I add another row that matches the select query, it does not return properly to the JavaScript function, but does display fine in the browser (if you visit testajax.php).
This is currently how the data is being returned. Maybe I have an error in the data type being usesd:
["Insert","2018-05-26","JBL5693",null,"Makers Mark","22","sdgfsg3","256632asdasd",2014,263,"217","11",null,null,null]["Insert","2018-05-27","fFH465","FDDEE453","GIIGE","22","Shippers","2432465we",2014,205222,"Smith Jones","Capital One",null,null,null]
This bit might have given you a clue If I only have 1 row matching this query, then it works fine
So save your rows in an array and then send the whole array like this
while ($insertquery->fetch()){
$data[] = array($tracking_type, $tracking_change_date, $vessel_fcm_new,
$vessel_hull_id_new, $vessel_name_new, $vessel_length_new,
$vessel_manufacturer_new, $vessel_manufacturer_id_new,
$vessel_year_new, $vessel_value_new, $owner_id_new,
$loss_payee_id_new, $policy_id_new, $policy_start_date_new,
$policy_end_date_new);
}
echo json_encode($data);
EDIT:
A simple test of this code would be
$data[] = array('Insert','2018-05-26', 1);
$data[] = array('Insert','2018-05-26', 2);
echo json_encode($data);
This will generate
[
["Insert","2018-05-26",1],
["Insert","2018-05-26",2]
]
and not the sample output you suggest.
The problem is that you're printing an array of columns for each pass through the loop and therefore the JSON is not be correctly encoded as an array of arrays; you can modify your code as follows:
$results = array();
while ($insertquery->fetch()) {
$newResult = array($tracking_type, $tracking_change_date, ...);
array_push($results, $newResult);
}
$encoded = json_encode($results);
echo $encoded;
Will print something like this:
[
["Insert","2018-05-26","JBL5693", ...],
["Insert","2018-05-27","JBL5694", ...],
...
]
Note that it's better to design a client<>server interface to use an array of objects, something like:
[
{"tracking_type": "Insert", "tracking_change_date": "2018-05-26", "vessel_fcm_new": "JBL5693", ...},
{"tracking_type": "Insert", "tracking_change_date": "2018-05-26", "vessel_fcm_new": "JBL5693", ...},
...
]
This approach has the advantage that the client client does not need to know the order of the columns, rather it can directly access the properties it cares about.
What you should be doing is return an array of objects. Not multiple objects.
$to_return = [];
while ($insertquery->fetch()){
$data = array($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
$to_return[] = $data;
}
echo json_encode($to_return);
Make sure to keep
echo json_encode($data);
outside of the while loop.

How to return the elements of an array from my database into my php as Ajax links

Basically I have a database and I'm making a webpage with PHP.
I get a row of Elements from my database and put them into an array.
I need to display this array in my webpage, and the elements out of it have to be ajax links that display more information.
$sql = "SELECT * FROM categories";
$categories1 = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($categories1)) {
$id = $row["name"];
$echo "$id";
This is my array where i have a list of names and i print it there, i want my prints to be links.
Any help? I'm pretty desperate
Make the datatype of AJAX call as JSON in the javascript and return a json encoded string from php. Then in the success block of the AJAX call , parse it by JSON.parse()
$sql = "SELECT * FROM categories";
$categories1 = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($categories1)) {
$categoryDetails[] = $row;
}
echo json_encode( $categoryDetails );

JQuery GET request won't get correct data from php echo

I am trying to fill a table using a jquery .get request, the url being a php file. The php gets data from a database, then it should return a json array back to the jquery, array which will fill the table. While the length of the array is returned as it should, the table cells are empty.
Here is my get.php function:
<?php
$mysqli=new mysqli("localhost:3306","root","","leagues");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$return_arr = array();
$query = "SELECT * FROM league";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row())
{
$return_arr[] = $row;
}
}
$mysqli->close();
header('Content-Type: application/json');
echo json_encode($return_arr);
?>
And here is my jquery get function
$.get('php/get.php',function(responseJson)
{
if(responseJson!=null)
{
$("#tableleague").find("tr:gt(0)").remove();
var table1 = $("#tableleague");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['teams']);
rowNew.children().eq(1).text(value['playedgames']);
rowNew.children().eq(2).text(value['wongames']);
rowNew.children().eq(3).text(value['tiegames']);
rowNew.children().eq(4).text(value['lostgames']);
rowNew.children().eq(5).text(value['scoredgoal']);
rowNew.children().eq(6).text(value['receivedgoal']);
rowNew.children().eq(7).text(value['points']);
rowNew.appendTo(table1);
});
}
});
Here is how my webpage looks, with the php file response shown.
Since the response is ok, what am I doing wrong that the cells aren't filled? Thank you.
If you look at your JSON data, you can see that there are no keys such as teams or playedgames. This is because you used fetch_row() in the PHP. Change that to fetch_assoc():
while ($row = $result->fetch_assoc())
This will give you $row with the field names as keys instead of using numerical keys that fetch_row() provides.
You can turn the php json into javascript object
obj = JSON.parse(json);
es:
var json='{"ex1":"test","ex2":[{"sub1":"test"},{"sub2":""s2test}],"ex3":true}';
var obj = JSON.parse(json);
after you can acces to data with :
obj.ex1 // test
obj.ex2[0].sub2 //s2test

bring data from a JSON and show in a popup

I have a leaderboard where if you click on a name a popup is displayed : https://jsfiddle.net/pvwvdgLn/1/
In practice, I will pull the list of the leaderboard from a DB.What you see here in the list are static names of employees,just for reference. So,how do I assign names using data attributes and search for that name in the JSON?
There are various fields in the popup like: Name,Email,Date of birth etc which I want to display for the respective person whose name is clicked by the user.
I have below JSON which is fetching me the array which contains all these data of all the people in the list :
<?php
session_start();
$servername = "xxxxx";
$connectioninfo = array(
'Database' => 'xxxxxxxxxxxxx'
);
$conn = sqlsrv_connect($servername, $connectioninfo);
if (!$conn) {
echo 'connection failure';
die(print_r(sqlsrv_errors() , TRUE));
}
$q1 = "select top 10 *
from pointsBadgeTable
WHERE WeekNumber ='week51'
order by pointsRewarded desc";
$stmt = sqlsrv_query($conn, $q1);
if ($stmt == false) {
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors() , TRUE));
}
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
}
while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
//Set content type to json
header('Content-Type: application/json');
//Echo a json object to the browser
echo json_encode($result);
?>
As can be seen in the query,it fetches JSON for all the top10 ,whose names can be seen in the list.
the html and JS related to the popup is here : https://jsfiddle.net/woef5mn6/
How can I display the respective data in the popup from the JSON only for the person whose name is clicked ?
please help me.
I have edited your fiddle to show how your problem can be solved. This is just a simple solution. It needs to modified according to your requirement.
Here is the fiddle
I am creating the employee list from your JSON and populating the ordered list
function employeeList() {
$("#myOL").empty();
$.each(employee, function(i,o) {
$("#myOL").append("<li><mark>" + o.EmployeeName + "</mark><small>" + o.score + "</small></li>");
});
}
Then onclick of the individual employee, i am getting his details from JSON by his name and then populating the popup details (as a best practice here - you should get the employee details by calling a service through ajax using a unique identifier [employeeId] ):
function getEmployeeByName(name) {
var index = -1;
var filteredObj = employee.find(function(item, i) {
if(item.EmployeeName === name){
index = i;
}
});
return employee[index];
}
Hope this helps!

How to insert a PHP 'while loop' into JavaScript code?

I need to display the values of an SQL table in a D3 map for each US state. Below is code excerpts from my file.php:
Here is the SQL query:
$sql = "SELECT COUNT(State) FROM `mytable`";
$sql_result= mysqli_query($cnx,$sql) or die('Could not execute' . mysqli_error()) ;
Here is how I pass the result into an array
<? while($myvar=mysqli_fetch_array($sql_result)) { **need to add both php and javascript below..** }
<?php $js_array = json_encode($myvar['0']);?>
Here is where I need to pass the data:
.forEach(function(d){
var kpi01=<?php echo "var nbcustomers = ". $js_array . ";\n";?>, // No of customers in that state
kpi02= .....
sampleData[d]={kpi01, kpi02};
});
Can anyone help me with suggestions to properly insert the JavaScript code after the while loop within the .forEach?
Don't mess around with trying to generate a bunch of variables with numbers in their names.
Just construct the data structure you need (an array of your SQL query results) in PHP, then use json_encode to convert it to JavaScript.
<?php
$my_array = [];
while($myvar=mysqli_fetch_array($sql_result)) {
$my_array[] = $myvar;
}
$js_array = json_encode($my_array);
?>
<script>
var javascript_array = <?php echo $js_array; ?>;
</script>

Categories

Resources