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
}
});
Related
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);
});
});
});
};
In another post I was able to get some help with dynamically creating dropdowns using AJAX.
I have a table that displays (in an HTML table) all the information contained in a mySQL table - above that there are 3 dropdowns which pertain to particular rows of the table. Right now I'm trying to get the table to 'refresh' with the data selected from the dropdowns (i.e. if user selects a dropdown - the table refreshes showing data filtered by their selection).
my client.php looks like this (this is what the user loads):
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
//SEND HTTP REQUEST WITH AJAX INITIALLY
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(response) //on recieve of reply
{ //Do the following on Success
//Set the filtering for "Creative"
var creatives = response.CREATIVE;
for (var i in creatives)
{
var creative = creatives[i];
var creativeID = creative[0];
$('#creative-select').append("<option value=\""+creativeID+"\">"+creativeID+"</option>");
}
//Set the filtering for "Stations"
var stations = response.STATION_NETWORK;
for (var i in stations)
{
var station = stations[i];
var stationID = station[0];
$('#station-select').append("<option value=\""+stationID+"\">"+stationID+"</option>");
}
//Set the filtering for "Verticals"
var verticals = response.VERTICAL;
for (var i in verticals)
{
var vertical = verticals[i];
var vertID = vertical[0];
$('#vertical-select').append("<option value=\""+vertID+"\">"+vertID+"</option>");
}
//Set the Table Content Initially
var rows = response.rowdata;
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];
//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>");
}
} // End of 'for' loop for the table data
} //End of 'do this on success'
}); //End of AJAX call
}); //End of Function
function showCreative (creativeVal)
{
//-----------------------------------------------------------------------
//Send the Creative filter criteria
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: "creative="+creativeVal, //insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(response) //on recieve of reply
{ //Do the following on Success
alert ("this never fires!");
} //end of on success
}); //End Ajax call
}; //End Creative Function
</script>
</head>
<body>
<h2> Media Call Reports </h2>
<h3>Media Analysis: </h3>
<div id="instruction">Select how you would like the data selected using the dropdowns below</div>
<!--DROPDOWNS-->
<div id="dropdowns">
<div id="creativesel">
Creative -
<select name="creative-select" id="creative-select" onChange ="showCreative(this.value);">
<option value="all">All</option>
</select>
</div>
<div id="stationsel">
Station -
<select name="station-select" id="station-select" onChange ="showStation(this.value)">
<option value="all">All</option>
</select>
</div>
<div id="verticalsel">
Vertical -
<select name="vertical-select" id="vertical-select" onChange ="showVertical(this.value)">
<option value="all">All</option>
</select>
</div>
</div> <!--Dropdowns ending-->
<!--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>
</table>
</body>
</html>
What I currently have in my api.php looks like this:
<?php
//--------------------------------------------------------------------------
// Connect to DB
//--------------------------------------------------------------------------
include 'DB.php';
$con = mysql_connect($host,$user,$pass) ;
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// Initial Page Load - get data from DB
//--------------------------------------------------------------------------
//Dropdown Filter Function
function dropdownFilter($filterColumn)
{
global $finalarray;
$filterSQL = "SELECT $filterColumn FROM media_analysis GROUP BY $filterColumn";
$filterResult = mysql_query($filterSQL);
$filterColumnData = array();
while ($filterRow = mysql_fetch_row($filterResult))
{
$filterColumnData[] = $filterRow;
}
$finalarray[$filterColumn] = $filterColumnData;
}
//Dropdown for Stations
dropdownFilter("STATION_NETWORK");
//Dropdown for Verticals
dropdownFilter("VERTICAL");
//Dropdown for Creative
dropdownFilter("CREATIVE");
//Rows of table-data in media-analysis
$result = mysql_query("SELECT * FROM $tableName"); //Initial Query
$data = array();
while ($row = mysql_fetch_row($result) )
{
$data[] = $row;
}
$finalarray['rowdata'] = $data;
//----------------------------------------------
//AFTER USER SELECTS FILTERS - IF ANY SELECTED
//----------------------------------------------
//Get variables from subsequent calls in URL if any
if (isset($_GET['creative']) and !empty($_GET['creative']))
{
$creativeFilter = $_GET['creative'];
echo $creativeFilter;
$result = mysql_query("SELECT * FROM $tableName WHERE CREATIVE = '$creativeFilter'");
$data = array();
while ($row = mysql_fetch_row($result) )
{
$data[] = $row;
}
$finalarray['rowdata'] = $data;
}
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($finalarray);
?>
The initial load works fine - the table is created and so are the dropdown selections.
Right now I'm just trying to get the 'creative' dropdown to work (hence why I'm focused on that).
When the user selects something from the creative dropdown - I see the AJAX call to the api.php with the appropriate addition (api.php?creative="whatever_user_selected") and the response comes back with all the correct data in the array (I can see it in the console) - but the table never updates.
Where do I need to put the code to update that table? What's the best way to go about getting that updated??
I'm a noob at this and there's a lot of tutorials around - each one specifying something different to do - so I've been on here looking but unable to find something similar.
All help is appreciated!!
I think your data part should look more like this:
data: { name: "John", location: "Boston" }
or
data: { creative: creativeVal }
I have a datatable that I am attempting to put drill-downs into based on the output of a php file, but I am having a few issues I can't seem to figure out. I am using http://datatables.net/blog/Drill-down_rows as a guide. So far this is my code:
Javascript:
<script type="text/javascript">
$("tr").live("click", function(){
var nTr = this;
var i = $.inArray(nTr, anOpen);
//oTable = my datatable
var oData = oTable.fnGetData(nTr);
if(i === -1) {
$(this).addClass('row_selected');
//THIS IS WHERE I AM GETTING A LITTLE LOST
//I WANT THE VALUE OF response.details TO BE STORED IN nDetailsRow
//oData.url is a mDataProp stored in the datatable row that contains the PHP link (this works okay)
var nDetailsRow = $.get(oData.url, function(response) {
//I don't really understand exactly what this is doing... but response.details is what I want to display from PHP
oTable.fnOpen(nTr, response.details, 'details');
});
//THIS LINE DOES NOT WORK CORRECTLY BECAUSE nDetailsRow IS NOT WHAT I WANT IT TO BE
$('div.innerDetails', nDetailsRow).slideDown();
anOpen.push(nTr);
else {
...
}
}
</script>
PHP:
<?PHP
$tableOut = '<div class="innerDetails">
<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">
<tr><td>Test Cell:</td><td>This is a test</td></tr>
</table>
</div>';
$data = array();
$data['details'] = $tableOut;
echo json_encode($data);
?>
I feel like I am almost there, but I don't quite understand the ajax $.get and am not sure if I am actually getting the JSON correctly from the PHP file. I also don't quite understand how to store that JSON in the active jquery code. Any ideas on how to accomplish these tasks and how to get my drill-down to display the PHP JSON data response.details?
I figured it out almost immediately after posting, I needed to use $.getJSON and include the last two lines inside that function. I am now using the following code which appears to work correctly:
<script type="text/javascript">
$(document).on("click", "tr", function(){
var nTr = this;
var i = $.inArray(nTr, anOpen);
//oTable = my datatable & oData.url is the mDataProp link to the PHP page
var oData = oTable.fnGetData(nTr);
if(i === -1) {
$(this).addClass('row_selected');
$.get(oData.url, function(response) {
oTable.fnOpen(nTr, response.details, 'details');
$('div.innerDetails', response.details).slideDown();
anOpen.push(nTr);
});
else {
...
}
}
</script>
Edit: Added/changed code from suggestions
<script type="text/javascript">
$("tr").live("click", function(){
var nTr = this;
var i = $.inArray(nTr, anOpen);
//oTable = my datatable
var oData = oTable.fnGetData(nTr);
if(i === -1) {
$(this).addClass('row_selected');
//THIS IS WHERE I AM GETTING A LITTLE LOST
//I WANT THE VALUE OF response.details TO BE STORED IN nDetailsRow
//oData.url is a mDataProp stored in the datatable row that contains the PHP link (this works okay)
var nDetailsRow = $.get(oData.url, function(response) {
try{
eval(response);
delete response;
//I don't really understand exactly what this is doing... but response.details is what I want to display from PHP
oTable.fnOpen(nTr, req.details, 'details');
}catch(e){
// error
}
});
//THIS LINE DOES NOT WORK CORRECTLY BECAUSE nDetailsRow IS NOT WHAT I WANT IT TO BE
$('div.innerDetails', nDetailsRow).slideDown();
anOpen.push(nTr);
else {
...
}
}
</script>
PHP:
var req = { details : '<?php echo str_replace('%', '\\x', urlencode('
<div class="innerDetails">
<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">
<tr>
<td>Test Cell:</td>
<td>This is a test</td>
</tr>
</table>
</div>')); ?>' };
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 />");
}
});
});
Please see website.
My database has a table with values 'name' (the event under step 2 on the left), 'price', 'date' etc and I'd like to display them dynamically in the dark box on the right depending on which event is chosen.
I'm currently displaying the event itself with the code below, but I'm unsure as to how to develop it to grab database values based on this choice. I'm guessing some sort of .get().
<script type="text/javascript">
$(document).ready(function() {
$('#right_inside').html('<h2>' + $('#club').val() + '</h2>');
});
$('#club').change(function(event) {
$('#right_inside').html('<h2>' + $('#club').val() + '</h2>');
});
</script>
This has had me stumped for ages, so any help would be much, much appreciated!
EDIT
Thanks for your replies. Here's what I now have, but it isn't working.
jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#right_inside').html('<h2>' + $('#club').val() + '</h2>');
});
$('#club').change(function(event) {
$.ajax({
type: "post",
url: "eventinfo.php",
data: $(this).serialize(),
success: function(data) {
$('#right_inside').html('<h2>' + $('#club').val() + '</h2>Price'+data.price);
},
dataType: "json"
});
});
</script>
eventinfo.php:
<?php
// the name of the input text box is 'club'
$night = $_POST['club'];
$night = mysql_real_escape_string($night);
// one of the columns values included in * is 'price'
// this line was previously: $query = mysql_query("SELECT * FROM nights WHERE name = '$night'");
$query = "SELECT * FROM nights WHERE name = '$night'";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$items[] = array($row[0]);
}
}
mysql_close();
// convert into JSON format and print
echo json_encode($items);
?>
The best course of action would be to use an xmlhttp object to load your PHP page that echos the data out. From that xmlhttp object you can assign the responseText (which will be the output contents of your PHP page) to a Javascript variable.
In other words, you probably want to use AJAX.
This is a good place to use client side templating. Use jQuery.tmpl and make a template for the right side (example below):
<script id="infoTemplate" type="text/html">
<div>
<span>${price}</span>
<span>${information}</span>
</div>
</script>
Then, make a method in PHP that takes in something like eventId and passes back a JSON object that looks something like this: {"price":"123.34","information":"some info here"}.
To load up your template, do this:
$(document).ready(function(){
// ... other stuff
$.template("infoTemplate", $("#infoTemplate").html());
});
Then, in your change event handler, do this:
$('#club').change(function(event) {
$.get('/yourNewPHPMethod', $('#club').val(), function(data){
$('#right_inside').html($.tmpl('infoTemplate', data));
});
});
Sorry, didn't have time to test any of this but it's the main idea and should help you establish a good pattern for any of this type of work in the future.
See jQuery.tmpl documentation below:
http://api.jquery.com/jquery.tmpl/
If I understand you right, you want an AJAX call to get the price. So something like
$('#club').change(function(event) {
$.ajax(
{type: "post",
url: "/path/to/price",
data: $(this).serialize(),
success: function(data)
{
$('#right_inside').html('<h2>' + $('#club').val() + '</h2>Price'+data.price);
},
dataType: "json"
});
Then since you are using PHP get the values you want and load them into an array and use json_encode.
update
For the PHP try changing
if($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$items[] = array($row[0]);
}
}
to
if($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$items[] = array("price"=>$row['price']);
}
}
update #2
Try adding the following to your PHP file, near the top:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');