getting info from json with jquery - php

Having trouble using ajax to retrieve info from a database. I was getting the code from here:
http://openenergymonitor.org/emon/node/107
the code from here worked but would only output 1 item
Simple Ajax Jquery script- How can I get information for each of the rows in the table?
I tried to add this to my code but I could not get it to work.
I am getting everything from a table with the following php:
$result = mysql_query("SELECT * FROM voterecords");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode($data);
which outputs the following if I navigate to that php page:
[["68","1234","0","1234",""],["69","added with ajax","0","this item was added using ajax",""]]
The format of the above is as follows:
id, title, votes, description, owner
I think that bit all works but I cant be sure because i dont know what JSON is supposed to look like.
Ok now here is the jquery which is supposed to retrieve the info from the JSON and put it into the html element #output
$(function ()
{
$.ajax({
url: 'retrieve.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var name = row[1];
var votes = row[2];
var info = row[3];
$('#output').append("<b>id: </b>"+id+"<b> name: </b>"+name+"<b> votes: </b>"+votes+"<b> info: </b>"+info)
.append("<hr />");
}
}
});
I was expecting this to output all the info but nothing happens.

Your code is fine except you have a missing closing ) from the callback function.
Also, in JavaScript, it's better to place opening braces on the same line, not on the next, as is common in some other languages.
Corrected/cleaned-up code:
$(function () {
$.ajax({url: 'retrieve.php', dataType: 'json'}).done(function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var votes = row[2];
var info = row[3];
$('#output')
.append("<b>id: </b>"+id+"<b> name: </b>"+name+"<b> votes: </b>"+votes+"<b> info: </b>"+info)
.append("<hr />");
}
});
});

Related

UPDATE table using php jquery ajax and in a MVC way

I have a HTML table and Edit - Delete - Save images are associated with each row. Now I want to edit any cell and when I'll click on Save-image it will be displayed on the HTML table with updated values, as well as the associated table in the database will also be changed. I want to do this using Jquery Ajax and PHP but in MVC way. I have tried but somehow database changes are not happening, while HTML table is showing the updated values.
Ajax Code:
function Save()
{
var par = $(this).parent().parent();
var tdCid = par.children("td:nth-child(2)");
var tdCname = par.children("td:nth-child(3)");
var tdCtype = par.children("td:nth-child(4)");
var tdRegno = par.children("td:nth-child(5)");
var tdFare = par.children("td:nth-child(6)");
var tdNightfare = par.children("td:nth-child(7)");
var tdButtons = par.children("td:nth-child(8)");
var Cid = $("#tdCid").val();
var Cname = $("#tdCname").val();
var Ctype = $("#tdCtype").val();
var Regno = $("#tdRegno").val();
var Fare = $("#tdFare").val();
var Nightfare = $("#tdNightfare").val();
$.ajax({
url:"cardetails.php",
type:"POST",
data:{cid:Cid, name:Cname, cartype:Ctype, regno:Regno,fare:Fare, nfare:Nightfare},
success: function(response){
if(response==1){
alert('Data Inserted / Modified Successfully');
}
else
{
alert('Error !! Data Insertion / Modification Failed');
}
}
})
tdCid.html(tdCid.children("input[type=text]").val());
tdCname.html(tdCname.children("input[type=text]").val());
tdCtype.html(tdCtype.children("input[type=text]").val());
tdRegno.html(tdRegno.children("input[type=text]").val());
tdFare.html(tdFare.children("input[type=number]").val());
tdNightfare.html(tdNightfare.children("input[type=number]").val());
tdButtons.html("<img src='delete.png' class='btnDelete'/><img src='edit.png' class='btnEdit'/>");
$(".btnEdit").bind("click", Edit);
$(".btnDelete").bind("click", Delete);
};
cardetails.php script:
include('helper.php');
$car = new Admin;
$r=$car->update($_POST['cid'],$_POST['name'],$_POST['cartype'],$_POST['regno'],$_POST['fare'],$_POST['nfare']);
if($r==1)
return 1;
else
return 0;
helper.php script:
class Admin extends connection
{
var $update;
var $insert;
var $delete;
function update($id,$name,$typ,$rno,$fare,$ncharge)
{
$this->update=mysqli_query($this->con,"UPDATE cars SET cname='$name',ctype='$typ',regno='$rno',fare='$fare',nightcharge='$ncharge' WHERE cid='$id'") or die(mysqli_error($this->con));
if($this->update)
{
return 1;
}
}
}
the path and connection class and all the names and id included within the AJAX query, PHP script and database table has been cross-checked twice.

Pass jquery - generated variable to php in same page

I have a script that gets tha data on the row of a button when that button is clicked. The id of the button is id='show-button'. This is the script:
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
var lecturer_id = names."_".surname;
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
});
</script>
The last two significant lines open a jquery dialog box.
With that, i mean these lines:
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
Now, I need to pass the value of var lecturer_id to a php script outside this code, but inside the same document. This php code will generate the content of the dialog crated by these two lines. Lets assume that I just want to echo the variable passed inside the dialog box (with the php).
Any idea on how to make it work?
Your question is not 100% clear, but, just an idea, if I got you right:
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
var lecturer_id = names."_".surname;
$.post( "test.php", { names: names, surname: surname; lecturer_id: lecturer_id })
.done(function( data ) {
$("#show_dialog")[0].innerHTML = data ;
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
});
});
</script>
And I agree with #JayBlanchard you don't even need any ajax call here, just generate your html like:
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
var lecturer_id = names."_".surname;
$("#show_dialog")[0].innerHTML = ' Name = '+names +'; Surname = '+surname ;
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
});
You can use jQuery post or ajax.
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
test.php will be the reciving end of php, where it expects data sent by jquery.
{ name: "John", time: "2pm" } will be the data you are wishing to send off to php.
data will be the the data output by php.
refer to http://api.jquery.com/jquery.post/ for more information

How to use loop for multiple arrays imported from Database

In server side I give table data from MySql and I send it with json_encode to JQuery:
<?php
include 'DB.php';
$result20 = mysql_query("SELECT * FROM Gallery WHERE Section = 'Chosen' AND ID = 19");
$array20 = mysql_fetch_row($result20);
$result19 = mysql_query("SELECT * FROM Gallery WHERE Section = 'Chosen' AND ID = 19");
$array19 = mysql_fetch_row($result19);
$data = array();
$data['Div20'] = $array20;
$data['Div19'] = $array19;
echo json_encode($data);
?>
json_encode export this arrays: {"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]}
but, in client side I need use a loop for use all arrays in events. When I use for, it's not work with multiple arrays, how to do it?
$(function() {
$.get('data.php' ,function(response)
{
var data = jQuery.parseJSON(response);
var array;
for(array in data)
{
var ImageID = data.array[0];
var ImageSrc = data.array[1];
$('#'+ImageID ).click(function(){
//some codes
})
}
})
})
Try this
$(function() {
$.get('data.php' ,function(response) {
var data = jQuery.parseJSON(response);
$.each( data, function( key, value) {
var ImageID = value[0];
var ImageSrc = value[1];
$("#"+ImageID ).click(function(){
//some codes
})
})
})
It will work if you add # to your imageid like,
$('#'+ImageID ).click(function(){
//some codes
});
I've tried some code for you,
var json={"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]};
for(div in json){
ImageID=json[div][0];
ImageSRC=json[div][1];
$('#'+ImageID)
.attr('src',ImageSRC)
.click(function(){
alert(this.src);
});
}
Demo
Replace .array with [array] in your for loop:
for(array in data)
{
var ImageID = data[array][0];
var ImageSrc = data[array][1];
}
"array" is not an attribute of your json object, it's just an argument of your for ... in loop. So you must use it as a dynamic value. Moreover you missed using a # to target properly the element id.
var data = {"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]};
for(array in data)
{
var ImageID = "#"+data[array][0];
var ImageSrc = data[array][1];
$(ImageID).on("click",function(){
//some codes
});
};
Avoid using $.each() loop as someone recommended above, jQuery loops are usually slower than native loops.
Try this..
$(function() {
$.get('data.php' ,function(response)
{
var data = jQuery.parseJSON(response);
$.each(data,function(k, v){
var ImageID = v[0];
var ImageSrc = v[1];
$('#'+ImageID ).click(function(){
//some codes`enter code here`
})
})
})

how to use two $.post methods very well for give data from 2 different database

function ChangeGallery(){
var GalleryName = $('.SubSubGalleryLock').text();
/*Send string to Data1.php and include Tags from Database*/
$.post("Data1.php", { Sections: GalleryName },
function(data){
$(".IncludeData").append(data);
});
/*send string to Data2.php and include Events data from Database*/
$.post("Data2.php",{ GallerySec: GalleryName },
function(response){
/*when i use alert method, this function works very well, why?*/
alert('SomeString');
var data = jQuery.parseJSON(response);
var ImageID = data[0];
var ImageSrc = data[1];
$(ImageID).click(function(){
$(".LargeImage").attr('src', ImageSrc);
});
});
};
in Data1.php
/*give data from database1 and print to HTML File*/
if ($_POST['Sections']) == "String")
{ $results = mysql_query("SELECT * FROM Table1");
while($row = mysql_fetch_array($results))
{ echo $row['Tags']; }
in Data2.php
/*give data from database2 and Use for events*/
if ($_POST['GallerySec']) == "String")
{ $results = mysql_query("SELECT * FROM Table2");
while($row = mysql_fetch_array($results))
{ echo json_encode($row); }
in Client side when i use it then Data1.php works very well but Data2.php only when i write an
alert('Some stringh');
after
var data = jQuery.parseJSON(response);
line, it's work well, why? what's due to this problem?
I'm going to guess that you need the second .post() to be processed AFTER the first .post() and when you put the alert() in, that guarantees that it will go in that order, but without the alert(), it is a race condition and depends upon which .post() returns quicker.
There are a couple ways to fix the sequencing. The most straightforward is to start the second .post() from the success handler of the first so that you know the first has already completed.
You can also use jQuery promises or you could use your own flags to keep track of which has finished and call the last bit of code only when both have finished.
Here's how you would start the second .post() from the success handler of the first to guarantee the order:
function ChangeGallery(){
var GalleryName = $('.SubSubGalleryLock').text();
/*Send string to Data1.php and include Tags from Database*/
$.post("Data1.php", { Sections: GalleryName },
function(data){
$(".IncludeData").append(data);
/*send string to Data2.php and include Events data from Database*/
$.post("Data2.php",{ GallerySec: GalleryName },
function(response){
var data = jQuery.parseJSON(response);
var ImageID = data[0];
var ImageSrc = data[1];
$(ImageID).click(function(){
$(".LargeImage").attr('src', ImageSrc);
});
});
});
};

PHP arrays with Ajax - Proper way to get the data?

I'm a complete ajax/php idiot - lets get that out of the way right now; but I've gotten to a point where I need some help. I've been following various tutorials here and there and kind of putting together a report.
Ultimately I have a table that contains all the data I need. I can get that data and display it appropriately in a table without issue. I'm trying to add 'drop-down' boxes that will allow filtering based on the criteria (there is a column called 'verticals' in this table - so a dropdown will contain all the different 'verticals' from the database column - and filter the table based on the selection of the vertical)
I have the following front-end snippet called "client.php" that the client loads to get a report:
Client.php:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/mediacallreport.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Generic Title</title>
</head>
<body>
<h2> Generic Reports </h2>
<h3>Report Formatting: </h3>
<div id="instruction">Select how you would like the data selected using the dropdowns below</div>
<!--DROPDOWNS-->
Vertical -
<select name="station" id="station">
<option value="all">All</option>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
dataType: 'json', //data format
success: function(verticals) //on recieve of reply
{
for (var i in verticals)
{
var vertical = verticals[i];
var verticalID = verticals[0];
$('station').append("<option value=\""+verticalID+"\">"+verticalID+"</option>");
}
}
});
});
</script>
</select>
<!--TABLE BEGINNING - TABLE HEADER ROW-->
<table id="output">
<tr>
<th>ID</th>
<th>Station_Network</th>
<th>Vertical</th>
<th>Creative</th>
<th>Tolls</th>
<th>States</th>
<th>Date Range</th>
<th>Week</th>
<th>Ordered</th>
<th>Credits</th>
<th>Credits Totals</th>
<th>Not Used</th>
<th>Cleared</th>
<th>Total Uniques</th>
<th>Cleared Each Unique</th>
<th>Total Unique Connect</th>
<th>Cleared Each Unique Connect</th>
<th>Unique Connect 8am - 8pm</th>
<th>Cleared Unique 8am - 8pm</th>
<th>Calls over 10 Min</th>
<th>Calls over 10 Min %</th>
</tr>
<!--JAVASCRIPT TO GET INFORMATION FROM DB, ASSIGN VARIABLES AND PUT INTO TABLE ROWS-->
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
// 2) SEND HTTP REQUEST WITH AJAX
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
for (var i in rows)
{
var row = rows[i];
var id = row[0]; //get id
var station_network = row[1]; //get name
var vertical = row[2]; //get vertical
var creative = row[3]; //get creative
var tolls= row[4]; //get tolls
var states= row[5]; //get states
var date_range= row[6]; //get date_range
var week= row[7]; //get week
var ordered= row[8]; //get ordered
var credits= row[9]; //get credits
var credit_totals= row[10]; //get credit_totals
var not_used= row[11];
var cleared= row[12];
var total_uniques= row[13];
var cleared_each_unique= row[14];
var total_unique_connect= row[15];
var cleared_each_unique_connect= row[16];
var unique_connect_8am_to_8pm= row[17];
var cleared_each_8am_to_8pm= row[18];
var calls_over_10= row[19];
var calls_over_10_pct= row[20];
//--------------------------------------------------------------------
// DISPLAY THE CONTENT
//--------------------------------------------------------------------
//TABLES (ALTERNATING ROWS)
if (id % 2 == 0){
$('#output').append("<tr id=\"evenrow\"> <td>"+id+"</td><td>"+station_network+"</td><td>"+vertical+"</td><td>"+creative+"</td><td>"+tolls+"</td><td>"+states+"</td><td>"+date_range+"</td><td>"+week+"</td><td>"+ordered+"</td><td>"+credits+"</td><td>"+credit_totals+"</td><td>"+not_used+"</td><td>"+cleared+"</td><td>"+total_uniques+"</td><td>"+cleared_each_unique+"</td><td>"+total_unique_connect+"</td><td>"+cleared_each_unique_connect+"</td><td>"+unique_connect_8am_to_8pm+"</td><td>"+cleared_each_8am_to_8pm+"</td><td>"+calls_over_10+"</td><td>"+calls_over_10_pct+"</td></tr>");
} else {
$('#output').append("<tr id=\"oddrow\"> <td>"+id+"</td><td>"+station_network+"</td><td>"+vertical+"</td><td>"+creative+"</td><td>"+tolls+"</td><td>"+states+"</td><td>"+date_range+"</td><td>"+week+"</td><td>"+ordered+"</td><td>"+credits+"</td><td>"+credit_totals+"</td><td>"+not_used+"</td><td>"+cleared+"</td><td>"+total_uniques+"</td><td>"+cleared_each_unique+"</td><td>"+total_unique_connect+"</td><td>"+cleared_each_unique_connect+"</td><td>"+unique_connect_8am_to_8pm+"</td><td>"+cleared_each_8am_to_8pm+"</td><td>"+calls_over_10+"</td><td>"+calls_over_10_pct+"</td></tr>");
}
}
}
});
});
</script>
</body>
</html>
That talks to my api.php
api.php:
<?php
//--------------------------------------------------------------------------
// Connect to DB
//--------------------------------------------------------------------------
include 'DB.php';
$con = mysql_connect($host,$user,$pass) ;
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
//Rows of data in media-analysis
$result = mysql_query("SELECT * FROM $tableName"); //query
$data = array();
while ($row = mysql_fetch_row($result) )
{
$data[] = $row;
}
//Dropdown for Verticals
$verticalSql = "SELECT VERTICAL FROM media_analysis GROUP BY VERTICAL";
$verticalResult = mysql_query($verticalSql);
$verticalData = array();
while ($verticalRow = mysql_fetch_row($verticalResult)){
$verticalData[] = $verticalRow;
}
$finalarray = array ('rowdata' => $data, 'verticaldata' => $verticalData);
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($finalarray);
?>
In Firebug I can see the data coming across and it looks something like this:
{"rowdata":[["1","canceled","canceled","canceled","canceled","canceled","03\/18\/2013-03-24\/2013","12","canceled","0","","","0.00","0","0.00","0","0.00","0","0.00","0","0.00"],["2","Station B","Vertical B","DEBIT","800-555-5555","CA","03\/18\/2013-03-24\/2013","12","$813.00","0","","","813.00","8","101.62","5","162.60","3","271.00","2","40.00"]],"verticaldata":[["canceled"],["Vertical B"]]}
Before I started including the 'dropdowns', I just had a simple json_encode ($data); and it would work fine and the table displayed exactly how I wanted it to. Since I've added another array to be passing, this is when things got crazy and I'm completely lost.
I know my coding is probably very poor, but I'm just trying to get a handle on this. All help appreciated.
The problem is that the code in your success handler expects an array to be returned:
success: function(verticals) //on recieve of reply
{
for (var i in verticals)
{
var vertical = verticals[i];
var verticalID = verticals[0];
$('station').append("<option value=\""+verticalID+"\">"+verticalID+"</option>");
}
}
However, as you showed in your example, verticals looks like this:
{"rowdata":[[...],[...]],"verticaldata":[["canceled"],["Vertical B"]]}
As you can see, verticals is an object, that contains two other objects (rowdata and verticaldata).
To make your current success handler work again, you first need to extract verticaldata from the AJAX response. Simply changing the code to this should work:
success: function(response) //on recieve of reply
{
var verticals = response.verticaldata;
for (var i in verticals)
{
var vertical = verticals[i];
var verticalID = verticals[0];
$('station').append("<option value=\""+verticalID+"\">"+verticalID+"</option>");
}
}
since you are using PHP and jQuery, you can use my library for that. Out-of-the-box dealing with any data that comes from PHP to Javascript, and vice-versa ;)
See here http://phery-php-ajax.net
in your case, it would be like this
<?php
include('Phery.php');
Phery::instance()->set(array(
'verticals' => function(data){
$r = new PheryResponse;
$verticalResult = mysql_query("SELECT VERTICAL FROM media_analysis GROUP BY VERTICAL");
$r->jquery('.station'); // Select it for subsequent chaining in the loop
$i = 0;
while ($verticalRow = mysql_fetch_row($verticalResult)){
$r->append('<option value="'.($i++).'">'.$verticalRow['VERTICAL'].'</option>'); // What is VERTICAL? Is that query the real one?
}
// every "append" call will happen to .station jquery selector automatically
return $r;
}
))->process();
?>
in your javascript code
$(function(){
phery.remote('verticals');
});
That's it. Why (re)generate data, when you can do it once in the server (where data generation belongs)
Of course, you could just return the JSON and use phery:json, but that's not practical in your case
return PheryResponse::factory()->json($verticalData);
And the Javascript side
phery.remote('verticals', null, null, false).on('phery:json', function(data){
for (var i in data){
// do your append here
}
});

Categories