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');
});
});
Related
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>");
});
I struggling print all my data from DB to webpage using JSON.
But I not understand logical how it should work.
My JSON script:
<script>
$("document").ready(function() {
$.getJSON("test1.php", function(data) {
$("#div-my-table").text("<table>");
$.each(data, function(i, item) {
$("#div-my-table").append("<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
});
$("#div-my-table").append("</table>");
});
});
</script>
And test1.php file
<?php
require_once 'connection.php';
$sql = $conn -> prepare("SELECT * FROM DB_NAME");
$sql -> execute();
while ($row = $sql -> fetch(PDO::FETCH_ASSOC))
{
$values = array('code'=>$row['code'],
'line'=>$row['line']);
}
echo json_encode($values);
?>
and part of HTML:
<body>
<table id="div-my-table">
</table>
</body>
And system return back only:
<table>
undefined undefined
undefined undefined
First make below correction in your code
$values[] = array('code'=>$row['code'],'line'=>$row['line']);
Above change will append all database value to $value variable and will show all records instead of last record of db
Also Please check with your table name in below query
$sql = $conn -> prepare("SELECT * FROM DB_NAME");
It seems that you are taking db name constant here instead of table name as mentioned below.
$sql = $conn -> prepare("SELECT * FROM TABLE_NAME");
If you're expecting multiple rows, you need to gather the results properly. The $values gets overwritten every iteration.
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
// add another dimension
$values[] = array(
'code'=>$row['code'],
'line'=>$row['line']
);
}
echo json_encode($values);
Or for just one line:
echo json_encode($sql->fetchAll(PDO::FETCH_ASSOC));
So that they are properly nested.
Then on your JS:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("test1.php", function(data) {
var table_rows = '';
$.each(data, function(i, item) {
table_rows += "<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
});
$("#div-my-table").html(table_rows);
});
});
</script>
You're overwriting the same $values variable each time through the loop. At the end, it will just contain a single row, not an array of all the rows. You need to add each row to $values, not replace it. It should be:
$values = array();
while ($row = $sql -> fetch(PDO::FETCH_ASSOC))
{
$values[] = $row;
}
echo json_encode($values);
Also, your jQuery is wrong. You shouldn't use .text() when you're creating HTML, you should use .html(). And you don't need to append </table> -- these functions operate on the DOM, not the HTML, and the DOM always has complete elements.
$("document").ready(function() {
$.getJSON("test1.php", function(data) {
var table = $("<table>");
$("#div-my-table").empty().append(table);
$.each(data, function(i, item) {
table.append("<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
});
});
});
Use last.after();
Instead of append();
I have a simple array from a php file (the reason for not using a json file is cause this info comes from a mysql database)
$array[0] = array('id' => 1,'price' => '325');
$array[1] = array('id' => 2,'price' => '486');
header('Content-type: application/json');
echo json_encode($array);
and it echos as:
[{"id":1,"price":"325"},{"id":2,"price":"486"}]
now what I want to do is take the id and add it to a variable called counterval so that JavaScript will read it as
counterval1 = 325;
counterval2 = 486;
but I can't seem to get it to read that way. Here is the script at the current moment.
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval + data[i].id = data[i].price;
console.log (counterval2);
});
$('#results').html(counterval2);
});
var counterval1 = 0;
var counterval2 = 0;
any help on this would be greatly appreciated.
you can't do that... but you can do this...
var counterval = [];
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval[data[i].id] = data[i].price;
console.log (counterval[2]);
});
$('#results').html(counterval[2]);
});
counterval[1] = 0;
counterval[2] = 0;
See my comment on your post. If you really want the vars to look like you explained:
eval("counterval" + data[i].id + " = data[i]..price");
alert(counterval1);
I am trying to populate a selected menu when the page is created but there are no options that show.
$(document).ready(function() {
$.ajax('patientlist.php', function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option value="' + data[i].patient_id + '">' + data[i].patient_firstname + data[i].patient_lastname + '</option>';}
$('#patientselect').append(html);
});
});
my patientlist.php
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname` FROM `patients` WHERE `company_id` = " . $user_data['company_id'] . " ORDER BY `patient_firstname`");
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
echo json_encode( $data );
}
My result from the php page
[{"patient_id":"9","patient_firstname":"Adam","patient_lastname":"Steve"}] etc...
Really appreciate any help, been stuck on this for a week!
So, posting again.
First of all, you should put the echo json_encode( $data ); out of your while loop
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode( $data );
Second, your $ajax syntax isn't correct, change this to $.post and tell the $.post request you are expecting a 'json' response from patientlist.php
$(document).ready(function() {
$.post('patientlist.php', {}, function(data){
/* code */
}, 'json'); // <= set data type json here
});
When retrieving a valid json string, you can iterate over data by using the $.each method
$.each(data, function(index, patient) {
console.log(patient.patient_id); // or use patient['patient_id']
});
At least you will now receive a valid request.
Noticing your HTML, do not use .append if it is not a DOM element, you are just building html elements as a string, so use instead
$('#patientselect').html(html);
I have a project where I've created JSON data for Project Prices/Prices I've gotten this far and pretty much ran into a wall, any help at all would help! I've checked all over the web and on jQuery.getJSON but I wound up getting super confused.
$data = mysql_query("SELECT * FROM xxx")
or die(mysql_error());
$arr = array();
$rs = mysql_query("SELECT product, price FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"products":'.json_encode($arr).'}';
I need to get the product price and product name into this jquery script
$(document).ready(function() {
/*** CONSTANTS ***/
var KEY = 0;
var VALUE = 1;
/*** DEFINE DATA SETS ***/
var POINTS = [ ["$productA", $PRICE ], ["$productB", $PRICE], ["$productC", $PRICE], ["$productD", $PRICE], ["$productE", $PRICE], ["$productF", $PRICE] ];
var SHIPPING_COSTS = [ ["Pickup", 0], ["Next Day Delivery", 30], ["Same Day Print/Same Day Delivery", 65] ];
for (var i = 0; i < POINTS.length; i++) {
$("#quantity").append("<option value='" + POINTS[i][VALUE] + "'>" + POINTS[i][KEY] + "</option>");
}
for (var i = 0; i < SHIPPING_COSTS.length; i++) {
$("#shipping").append("<option value='" + SHIPPING_COSTS[i][VALUE] + "'>" + SHIPPING_COSTS[i][KEY] + "</option>");
}
$("select.autoUpdatePrice, input.autoUpdatePrice").bind("mousedown click change", function(event) {
Calculate();
});
Calculate();
});
function Calculate() {
var net = parseFloat($("#quantity").val());
/* Calculate the magical # by adding the form fields*/
var designFee = $("#abcDesignFee").attr("checked") ? $("#abcDesignFee").val() : 0.0;
var proofFee = $("#abcProofFee").attr("checked") ? $("#abcProofFee").val() : 0.0;
var MyPrice;
MyPrice = parseFloat( parseFloat(proofFee) + parseFloat(designFee) + net + parseFloat($("#shipping").val()));
$("#DumpHere").html("Your Price: $" + formatNumber(MyPrice));
$("#abcName").val($("#quantity").find(":selected").text() + " " + ProductNamePlural);
$("#abcPrice").val(MyPrice);
}
In your PHP script, can you just json_encode() your array of objects without wrapping it in the string? And instead encode the JSON object like so:
<?php
// your script ...
echo json_encode($arr);
This creates an array of JSON encoded objects:
[{"name":"item 1","price":4.99},{"name":"item 2","price":9.99}]
Make an AJAX request in your JS to query your PHP script, and use jQuery's $.each() and $.parseJSON() methods to iterate over the returned JSON data:
$.post('get_products.php', { data: foo }, function(json) {
$.each($.parseJSON(json), function(key, product) {
console.log(product.name + ' ' + product.price);
});
});
Hope this helps :)
When I was learning - I had exactly the same problem - but it got answered here
What I didn't realise at the time was that you can use object notation (which is the ON of json) to access the data you sent.
If you look at my question and the answer I selected, once you have sent the data back to javascriot you can access it easily. In my example it would be as straitforward as using data.catagory_desc in javascript to find the data that was encoded.