Display JSON result in Table Format - javascript

$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
var txt = "";
if (len > 0) {
for (var i = 0; i < len; i++) {
if (data[i].die_no && data[i].status && data[i].location) {
txt += "<tr><td>"+data[i].die_no+"</td><td>"+data[i].status+"</td><td>"+data[i].location+"</td></tr>";
}
}
if (txt != "") {
$("#table").append(txt).removeClass("hidden");
}
}
}
}
Controller page
$die_no = array();
$status = array();
$location = array();
while ($row = mysql_fetch_array($query)) {
$die_no[] = $row["die_no"]; // or smth like $row["video_title"] for title
$status[] = $row["status"];
$location[] = $row["location"];
}
$res = array($die_no, $status, $location);
echo json_encode($res);
HTML page
<p>
<table id="table" class="hidden">
<tr>
<th>die_no</th>
<th>Status</th>
<th>Location</th>
</tr>
I would like to display result in HTML table format, so I have passed my result in array format to Json but the results are not displayed in HTML page.
I could see the response by using chrome Inspect element under network option . Please help me to display the retrieved results in HTML tabular format.

If you add console.log(data) in your succes response,you can see how the object is structured.
To access the desired json value you should try data['die_no'][i],data['status'][i],data['location'][i].
You can insert the response like this:
<table id="tbl">
</table>
Javascript:
$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
if (len > 0) {
for (var i = 0; i < len; i++) {
$('$tbl').append("<tr><td>"+data['die_no'][i]+"</td><td>"+data['status'][i]+"</td><td>"+data['location'][i]+"</td></tr>");
}
}
}
}
}); //you missed this in your question

Use this
$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
var txt = "";
if (len > 0) {
for (var i = 0; i < len; i++) {
if (data[0][i] || data[1][i] || data[2][i]) {
txt += "<tr><td>" + data[0][i] + "</td><td>" + data[1][i] + "</td><td>" + data[2][i] + "</td></tr>";
}
}
if (txt != "") {
$("#table").append(txt).removeClass("hidden");
}
}
}
}
});
Actually your php code is not returning key value pair. So in your js you cannot use data.die_no etc
Use this like just I did:
data[0][i]

You have syntax error:
use
txt += <tr><td>
instead of
txt += tr><td>
after if condition

Related

str_replace inside js from Ajax call data

i want to replacement character from data loop ajax (data[i]) to some values,
i have this js
<script type="text/javascript">
$(document).ready(function() {
$('select[name="parameter"]').on('change', function() {
var idpar = $(this).val();
var subdir = $('input[name="subdirid"]').val();
var year = $('input[name="added_year"]').val();
var i = 0;
if (idpar != '') {
$.ajax({
url: "{{URL::to('myform/myformColaborate')}}/" + idpar + "/" + subdir + "/" + year,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (key, city2) {
$('select[name="type2"]').empty();
$('select[name="type2"]').append(
'<option disabled selected>Select Request Colaborate</option>'
);
for (var i = 0; i < data.length; i++) {
$('select[name="type2"]').append(
'<option value="'+ data[i] +'">Request Colaborate with '+ data[i] +'</option>'
);
}
});
}
});
}
});
});
</script>
and the controller
public function myformColaborate($idpar, $subdir, $year) {
$cities = DB::table("pra_kpis")
->where('subdir_colaborate','like','%'.$subdir.'%')
->where('added_year',$year)
->where('kpi_parameters_id',$idpar)
->distinct()
->pluck("subdirs_id");
return response()->json($cities, 200);
}
for example , i have script replacement outside js like this, how to define it inside js
<?php
$roles = DB::table('pra_kpis')->where('id','=',$l->id)->pluck('subdir_colaborate');
$dir2 = DB::table('subdirs')->select('name')->pluck('name');
$iddir = DB::table('subdirs')->select('id')->pluck('id');
?>
#foreach($roles as $drop)
{{$drop = str_replace($iddir, $dir2, $drop)}}
#endforeach
Try this:
Do it from front-end only,
Use data[i].replace('search string', 'replace string');

Set JSON values to HTML Table in Java Script?

function loadUserTable(userType){
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
alert(response);
},
});
}
Im still working on it,
I print alert for output and got as below
[{
"userId":1,
"email":"santosh.jadi95#gmail.com",
"mobile":"9900082195",
"gender":"male",
"qualification":"1",
"dob":"2016-01-01",
"login":{
"loginId":1,
"userName":"santosh",
"password":"santosh",
"userType":"admin"
}
}]
I want the above JSON values in an HTML Table, is it Possible?
If yes, then i just want to know that, how it can be done?
Got the Solution,, Thank u all for the kind support
function loadUserTable(userType){
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
var obj = JSON.parse(response);
$("#tableId").html("");
var tr+="<tr><th>User ID</th><th>User Name</th></tr>";
for (var i = 0; i < obj.length; i++){
tr+="<tr>";
tr+="<td>" + obj[i].userId + "</td>";
tr+="<td>" + obj[i].login.userName + "</td>";
tr+="</tr>";
}
$("#tableId").append(tr);
}
});
}
Yes it is possible. if you want to print json data in simple html table then just iterate (use loop) till your json length and construct your table inside loop.
But i will suggest you to use dataTable / bootstrap table plugin there you just need to pass json at the initialization time.
for Example,
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').append(tr);
}
});
});
You'd simple just create a for loop inside success as following:
the obj[i] down below is just a placeholder. You'd have to get the correct value you want to place there.
HTML table container:
<div id="tableContainer">
<table>
<tbody class="tableBody">
<tbody>
</table>
</div>
JSON to append to table:
function loadUserTable(userType)
{
var TableHTML = '';
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
alert("eeee: "+response);
var obj = JSON.parse(response);
for (i = 0; i < obj.length; i++)
{
TableHTML += '<tr><td>' + obj[i].userId + '</td></tr>';
}
},
});
$(".tableBody").append(TableHTML);
}

getting 2 JSON arrays from php to js

I returned from PHP array with two elements through JSON , but the " data.length " does not work . How can I get the size of the array in JS ? If I turn it to one of the elements in the array ( data.name.length ) returns the number of elements in STRING .
for ($i = 0; $i < $result; $i++) {
$img_name ['id'] = $get_img_id[$i]['id'];
$img_name ['name'] = $get_img_id[$i]['id'];
}
return json_encode($img_name);
js:
$.ajax({
url: "upimage",
dataType: "json",
type: "POST",
data: formData,
success: function(data) {
//$.each(data, function(i) {
$("#all_files").val(data + " ,");
for ( var i = 0, l = data.length; i < l; i++ ) {
$(".returns_img").append("<div class='img_ls' id='" + i + "'><img src='/img/" + data['name'][i] + "'><button class='dell_img' id='"+ i +"'>מחק</button><br><button class='add_img' id='"+ i +"'>הוסף לכתבה</button></div>");
}
},
cache: false,
contentType: false,
processData: false
});
You are returning not array, but a single object from php code, to get what you need try this:
$result = array();
for ($i = 0; $i < $result; $i++) {
$img_name ['id'] = $get_img_id[$i]['id'];
$img_name ['name'] = $get_img_id[$i]['id'];
$result[] = $img_name;
}
return json_encode($result);
Use like this,
var arr = [], len;
for(key in data) {
arr.push(key);
}
len = arr.length;
console.log(len)

For loop in Ajax or PHP?

I have code which return loop from php to ajax via json_encode()
Let me know what I want to do.
there is one table call SMTP. Assume that it has 3 value and I want to fetch that 3 value from table, store in array () and Display it to HTML via AJAX in table format.
So I'm confused where I place my loop, in AJAX or PHP ?
Here is my code.
PHP
$result=mysql_query("select * from ".$db.".smtp WHERE id = '$user' ");
if($result === FALSE) {
die(mysql_error());
}
while($data = mysql_fetch_row($result))
{
$array = array($data[2],$data[3]);
}
echo json_encode($array);
JS
$(document).ready(function() {
GolbalURL = $.session.get('URL');
$.ajax({
type: "GET",
url: GolbalURL+"smtp.php",
dataType: "html",
success: function(response){
$("#divsmtp").html(response);
}
});
});
HTML
<div id = "divsmtp"></div>
This code return only last value. inarray like ["data2","data3"]
My Longest way to do
success: function(response){
resultObj = eval (response);
var i = Object.keys(resultObj).length;
i /=2;
//$("#divsmtp").html(i);
var content = "<table>"
for(j=0; j<i; j++){
k = j+1;
if (j % 2 === 0)
{
alert("j="+j+" k="+k );
content += '<tr><td>' + resultObj[j] + resultObj[k] + '</td></tr>';
}
else
{
k = k+1;
var m = j+1;
alert("m="+m+" k="+k );
content += '<tr><td>' + resultObj[m] + resultObj[k] + '</td></tr>';
}
}
content += "</table>"
$('#divsmtp').append(content);
}
Because you are always overwrite the $array variable with an array.
Use: $array[] = array($data[2], $data[3]);
Use json decoding at jquery end
EDIT Small way
$.each($.parseJSON(response), function( index, value ) {
//Loop using key value LIKE: index => value
});
//Old
success: function(response){
var jsonDecoded = $.parseJSON(response);
console.log(jsonDecoded );
$.each(jsonDecoded, function( index, value ) {
//Loop using key value LIKE: index => value
});
$("#divsmtp").html(response);
}
Create the array on the PHP side like this -
$array = array();
while($data = mysql_fetch_row($result))
{
array_push($array, $data);
}
echo json_encode($array);

Adding JSON data to table in AJAX

Ok i have some search results from input box. I used keyup to get results. Then tis results send to AJAX, and i want to append it to table. My problem is because i use append i will get more than one table headers if i have more results, on the other side i cant use html() because script use for loop so i will only get one result. Can someone help me to solve this problem. I try something like this...
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);;
$('#result').html('');
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
$('#result').append('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody><tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr> </tbody></table> ' );//dodavanje rezultata u div
}
}
})
}
});
Just create the table once and then append trs in the loop to its tbody
$('#warning').html(response.msg);
if (response.result.length) {
var $table = $('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody></tbody></table>').appendTo($('#result').html(''));
var $tbody = $table.find('tbody');
for (var i = 0; i < response.result.length; i++) //petlja za pristup json
{
$tbody.append('<tr><td>' + response.result[i].id + '</td><td>' + response.result[i].naslov + '</td><td>' + response.result[i].autor + '</td><td>' + response.result[i].cena + '</td><td>' + response.result[i].valuta + '</td></tr> '); //dodavanje rezultata u div
}
} else {
$('#result').html('')
}
Try this :
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);
// Store jQuery objects if used more than once
var $table = $('<table class="page-list">').appendTo($('#result')),
$thead = $('<thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead>').appendTo($table),
$tbody = $('<tbody>').appendTo($table);
innerHTML = '';
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
innerHTML += '<tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr>' );//dodavanje rezultata u div
}
// Append to HTML only once, when you have the full HTML to append
$tbody.append(innerHTML);
}
})
}
});

Categories

Resources