I am getting the array through PHP and I want to append in in table but I tried to make it from last 2 days and uses all the function which available on stackoverflow but it not working...
Please developers , help me and teach me how i append out output data in table as below -
PHP Code :-
$result = $stmt->fetchAll();
foreach($result as $data => $value) {
//$QL QUERY HERE
$data = array('name' => $value["name"], 'amount' => $amount, 'invoice' => $Invoice, 'response' => '200');
echo json_encode($data);
}
exit();
My PHP response is :-
{"name":"AMAZON_FBA","amount":"1","invoice":"25","response":"200"}
{"name":"AMAZON_IN","amount":"12","invoice":"22","response":"200"}
{"name":"FLIPKART","amount":"42","invoice":"08","response":"200"}
{"name":"PAYTM","amount":"36","invoice":"03","response":"200"}
{"name":"Replacement","amount":"0","invoice":"17","response":"200"}
Ajax:-
$.ajax({
.
.
success: function (data) {
var my_orders = $("table#salesReturnTB > tbody.segment_sales_return");
$.each(data, function(i, order){
my_orders.append("<tr>");
my_orders.append("<td>" + data[i].order.name + "</td>");
my_orders.append("<td>" + data[i].order.invoice + "</td>");
my_orders.append("<td>" + data[i].order.amount + "</td>");
my_orders.append("<td>" + data[i].order.response + "</td>");
my_orders.append("</tr>");
});
});
});
in the PHP you need to define a $list variable (because you've already used the $data name as an input parameter in your loop), and move the echo outside the loop. Otherwise it echoes each individual data item, rather than creating a coherent JSON array. A list of individual items without the [..] at each end isn't valid JSON, so JavaScript can't read it.
$result = $stmt->fetchAll();
$list = array();
foreach($result as $data => $value)
{
$list = array('name' => $value["name"], 'amount' => $amount, 'invoice' => $Invoice, 'response' => '200');
}
header("Content-Type: application/json");
echo json_encode($list);
exit();
And, in the JavaScript/jQuery, you have a similar problem where you're using the data name to represent two different things - the list of items, and an individual item within the loop.
This should work better:
$.each(data, function(i, item) {
my_orders.append("<tr>");
my_orders.append("<td>" + item.name + "</td>");
my_orders.append("<td>" + item.invoice + "</td>");
my_orders.append("<td>" + item.amount + "</td>");
my_orders.append("<td>" + item.response + "</td>");
my_orders.append("</tr>");
});
Related
I am trying to display json_encode data from my back end controller to view using together with AJAX. The AJAX runs successfully and received the response that I needed. However, i am unable to display out on my HTML.
I have double-checked that there is certainly a response coming from the back end. Please do help me.
AJAX jQuery
$.ajax({
type: 'post',
url: 'index.php/Status/facility',
dataType: "json",
data: {id:id},
success: function (response) {
var len = response.length;
console.log(len);
for(var i=0; i<len; i++){
var id = response[i].facility_id;
var username = response[i].name;
var tr_str = "<li class='pointer' id='" + (i+1) + "' onclick='changeClass(this.id)'><a>" + name +"</a></li>";
$("#tabAjax").append(tr_str);
}
$('#exampleModalCenter').modal('show');
}
});
HTML
<ul class="nav nav-pills" id="tabAjax"></ul>
Controller
public function facility(){
echo json_encode($data);
//$this->load->view('templates/student/footer');
}
Response
{"facility_list":[{"facility_id":"1","name":"Table 1","facility_category":"1"}]}
I believe you need to access the data within facility_list so to do so firstly get a reference to that level of the response data and then iterate through it's child objects
var json=response.facility_list;
for( var n in json ){
var obj=json[n];
var id=obj.facility_id;
var name=obj.name;
var cat=obj.facility_category;
var tr_str = "<li class='pointer' data-category='"+cat+"' id='" + (n+1) + "' onclick='changeClass(this.id)'><a>" + name +"</a></li>";
$("#tabAjax").append( tr_str );
}
The best way to implement this handle it at backend. You can prepared html at backend and send prepared html in response(in any key of array) and append according that. That will be more easy to handle response and no need to reload page every time.
$response = array(array('facility_id' => 1, 'facility_category' => 2, 'name' => 'abc'));
$returnResponse = array('status' => 'false', 'data' => '');
$str = '';
foreach ($response as $key => $resp) {
$str .= '<li class="pointer" data-category="' . $resp['facility_category'] . '" id="' . ($key+1) . '" onclick="changeClass(this.id)"><a> ' . $resp['name'] . ' </a></li>';
}
$returnResponse['status'] = true;
$returnResponse['data'] = $str;
Now in js file you can use:-
var html = response.data;
and append above html where you want.
My Ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
$("#main_content").slideUp("normal",function(){
$(".the-return").html("<br />JSON: " + data);
//how to alter this part to display data for each record in one div?
});
}
});
return false;
});
My query
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
The result displayed currently in this form:
JSON: jack,55421894ab602,test,55439324cc43d
But I want to display like:
Name:jack,
Id:55421894ab602
.....and some other info-
Name:test
Id:55439324cc43d
.....and some other info-
This part:
$(".the-return").html("<br />JSON: " + data);
I tried: data[0];
But when I do this, only the first record displayed obviously.
What I'm trying is :
data[0] itself is an array. How to display that array together with other records fetched in nice html?
edited: WIth these edited code, i can only retrieve the last result, it's not looping through the array.
ajax
success: function (data) {
$("#main_content").slideUp("normal",function(){
//$(".the-return").html("<br />JSON: " + j_data);
for (i = 0; i < data.length; i++) {
$(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
}
console.log(data); // this shows nothing in console,I wonder why?
//alert(j_data);
});
}
php
$json = array();
while( $row = $statement->fetch()) {
//array_push($json, array($row['Name'], $row['PostUUID']));
array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
First, to get the names of the fields in your template, you need store them in your array:
array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
Result after json_encode -> {"name":"TheName","id":"TheID"}
Next, in your js code, if the json that it receives is valid, you can do a loop:
success: function (data) {
$("#main_content").slideUp("normal",function(){
for (i = 0; i < data.length; i++) {
$(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
}
}
}
Of course, you can add style or class to the div.
I hope it helps.
EL PROBLEMO
My JSON returns an associative array that I take elements from and display on the page. Sometimes one or more of the sub-arrays will be empty, and this is expected behavior. For those I want nothing displayed on the page. My problem is that currently anytime one of those sub-arrays is empty, I get a "parsererror". In my application, you switch between months, and this AJAX call is made when the dropdown selection is changed to a different month. On months where all the sub-arrays have values, I dont get an error. I only get it when one or more of the sub-arrays are empty.
PHP
first I perform the SQL queries, which I'm leaving out to keep this as short as possible, but these are the 3 resulting arrays:
$income = $results->fetchall(PDO::FETCH_ASSOC);
$expense = $results->fetchall(PDO::FETCH_ASSOC);
$recurring = $results->fetchall(PDO::FETCH_ASSOC);
Then I want to assign those to an array, which I then json_encode:
$array = array(
'income' => $income,
'expense' => $expense,
'recurring' => $recurring
);
echo json_encode($array);
AJAX
This is basically calling the previous php code, then displaying each record from the database in a table.
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
dataType: "JSON",
data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
$('#income tbody tr, #expense tbody tr').remove();
for(var i = 0; i < response.income.length; i++) {
$('<tr><td id="' + response.income[i].cat_id_PK + '">' + response.income[i].cat_name + '</td><td id="' + response.income[i].cat_id_PK +
'">$' + response.income[i].cat_amount + '</td></tr>').appendTo("#income");
}
for(var i = 0; i < response.expense.length; i++) {
$('<tr><td id="' + response.expense[i].cat_id_PK + '">' + response.expense[i].cat_name + '</td><td id="' + response.expense[i].cat_id_PK + '">$' + response.expense[i].cat_amount + '</td></tr>').appendTo("#expense");
}
for(var i = 0; i < response.recurring.length; i++) {
$('<tr><td id="' + response.recurring[i].cat_id_PK + '">' + response.recurring[i].cat_name + '</td><td id="' + response.recurring[i].cat_id_PK + '">$' + response.recurring[i].cat_amount + '</td></tr>').appendTo("#expense");
}
});
request.fail(function(jqxhr, textStatus){
alert("Request failed: " + textStatus);
});
};
JSON
Here's an example JSON response with two empty sub-arrays.
{
"income": [],
"expense": [],
"recurring": [
{
"cat_id_PK": 67,
"cat_name": "Grooming",
"cat_amount": "40.00",
"recur_begin": 1,
"recur_end": 12
}
]
}
Count the number of rows you get from sql query result.
if they are greater than 0 then send an extra field as
$d['status'] ='OK';
if no record exists then send the error handling as
$d['status'] ='ERR';
so check the status field in the data success
dataType: 'json',
data: you data,
success: function( data ) {
if(data.status == "OK"){
alert('success');
} else{
alert('failure');
}
}
});
try like this ,just to test and then use data
I am trying to get json data from php and when by using jquery json it show me undefined object. I don't know where is problem in my code. can any one help ?
Here is json code :
$("document").ready(function() {
$("body").css("background", "#ccc");
$(".sitebuttons").click(function() {
$("#subcat").html("");
$.getJSON("subcat.php", {catid: $(this).attr("id")}, function(data){
$.each(data, function(index, array) {
$("#subcat").append("<input type='button' class='subcat' id='" + data.subcat_id + "' value='"
+ data.subcat_name + "'></p>");
});
});
});
});
and Here is PHP Code
$select_subcat = mysql_query("SELECT * FROM wp_leadsubcat WHERE cat_id=" . $_GET['catid']);
$rows = array();
while ($result2 = mysql_fetch_assoc($select_subcat)) {
$rows[] = $result2;
}
echo json_encode($rows);
Please check screenshot here : http://imageshack.us/photo/my-images/560/screenshotqvl.png/
read documentation about jquery each.
in short jQuery.each( collection, callback(indexInArray, valueOfElement) )
index means index and valueOfElement means the current element from the collection. In your case row.
here is a fix.
$("document").ready(function() {
$("body").css("background", "#ccc");
$(".sitebuttons").click(function() {
$("#subcat").html("");
$.getJSON("subcat.php", {catid: $(this).attr("id")}, function(data){
$.each(data, function(index, row) {
$("#subcat").append(
"<input type='button' class='subcat' id='" + row.subcat_id + "' value='"+ row.subcat_name + "'>"
);
});
});
});
and the append part could be optimized like this (it's more readable as you can see)
$("#subcat").append($(
"<input/>"
, {
cssClass: 'subcat'
, id: row.subcat_id
, value: row.subcat_name
}
));
i think an index would solve the problem
$("#subcat").append("<input type='button' class='subcat' id='" + data[index].subcat_id + "' value='"
+ data[index].subcat_name + "'></p>");
Okay i change the script like this ! why it dont work ?!?
demo.php
while($row = mysql_fetch_array($result)){
$array[] = array(
'var1' => $row['var1'],
'var2' => $row['var2'],
'var3' => $row['var3'],
'var4' => $row['var4'],
);
}
print json_encode($array);
demo.js
$.getJSON("demo.php",function(result){
$.each(result, function(i, obj){
$(obj.var1).appendTo('div id="var1"');
$(obj.var2).appendTo('div id="var2"');
$(obj.var3).appendTo('div id="var3"');
$(obj.var4).appendTo('div id="var4"');
});
Firstly, the PHP:
As previously mentioned, you don't need quotes (") around the variables in your database connection, it's pointless.
You also need to get all the rows before JSON encoding.
Change:
echo json_encode(mysql_fetch_assoc($result));
To
$return = array();
while ($row = mysql_fetch_assoc($result))
{
$return[] = $row;
}
echo json_encode($return);
So that all the rows from the database are returned, instead of just the first.
Next for your jQuery:
Try changing: $('div').html(obj.attribute1+" "+obj.attribute2 ecc...);
To: $(obj.attribute1+" "+obj.attribute2 ecc...).appendTo('div');
Or: $('<div>' + obj.attribute1+" "+obj.attribute2 ecc... + '</div>').appendTo('body'); if you want each object in it's own container.
The way you are currently doing it will just overwrite the HTML for every div on the page for each iteration so that div elements will eventually only contain details for the last object in the collection.
Edit:
$.getJSON("demo.php",function(result){
var $id = 0;
$.each(result, function(i, obj){
$id ++;
$('<div id="obj' + $id + '"/>').appendTo('body');
$('<span class="var1">' + obj.var1 + '</span>').appendTo('div#obj' + $id);
$('<span class="var2">' + obj.var2 + '</span>').appendTo('div#obj' + $id);
$('<span class="var3">' + obj.var3 + '</span>').appendTo('div#obj' + $id);
$('<span class="var4">' + obj.var4 + '</span>').appendTo('div#obj' + $id);
});
});
Edit 2:
If you are trying to get each of the 'varX' from all elements into a single div, then just define the four divs (<div id="var1"/>, <div id="var2"/>, ...), and use this code:
$.getJSON("demo.php",function(result){
$.each(result, function(i, obj){
$(obj.var1).appendTo('div#var1');
$(obj.var2).appendTo('div#var2');
$(obj.var3).appendTo('div#var3');
$(obj.var4).appendTo('div#var4');
});
});