Update div dynamically with database values depending on dropdown - php

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');

Related

Wordpress ajax call is returing the html of the page

I am getting the data from the sql table and storing the results inside the associative array after that i have encoded into json but the problem is that it is returning the html of the page along with the results
this is my php code
<?php
add_action('wp_ajax_nopriv_my_loadmore','my_loadmore');
add_action('wp_ajax_my_loadmore','my_loadmore');
function my_loadmore(){
global $wpdb;
$table_name="wpnn_tweets";
$paged=$_POST['page'];
$page=$paged*10;
$results = $wpdb->get_results("SELECT * FROM $table_name LIMIT 1 OFFSET $page");
$arr = array();
foreach($results as $row){
$arr['userScreen']=$row->userScreen;
$arr['userName']=$row->userName;
$arr['tweetCreated']=$row->tweetCreated;
$arr['tweetText']=$row->tweetText;
$arr['tweetRetweetCt']=$row->tweetRetweetCt;
$arr['tweetFavoriteCt']=$row->tweetFavoriteCt;
}
echo json_encode($arr);
wp_die();
}
?>
this is how i am retrieving the json in the front end
$ = jQuery;
function scroller() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
$(this).off("scroll.ajax");
var page=parseInt($(this).data('page'));
var ajaxurl=$(this).data('url');
$.ajax({
url:ajaxurl,
type:"POST",
data:{
page:page,
action:"my_loadmore"
},
error:function(response){
console.log("error");
},
success:function(data){
for(i = 0; i < data.length; i++) {
console.log(data[i]);
}
}
});
}
}
$(window).on("scroll.ajax", scroller);
var ajaxurl = $(this).data('url');
This returns null unless you explicitly set it in your HTML. The easiest solution is to replace it with something like the following.
var ajaxurl = 'my-cool-endpoint';
This was not the solution to this particular problem, but I feel like it's a good thing to check for others coming to this page with the same problem. Replace wp_die() with die(). See the documentation for more details, but here is the relevant line.
A call to this function complements the die() PHP function. The difference is that HTML will be displayed to the user in the case of a typical web request.

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
}
});

Unable to navigate Dynamically created pages in DOM

After so many trials, I have finally managed to create pages dynamically using PHP, JSON and AJAX and load them into DOM. But the problem now is I'm unable to call/navigate those pages dynamically, but manually i.e gallery.html#page1 ...etc.
I seek guidance rather than burdening you, as I'm here to learn.
**PHP - photos.php **
$photos = array();
$i=0;
while ($row = mysqli_fetch_array($query)){
$img = $row["fn"];
$photos[] = $img;
$i++;
}
$count = count($photos);
echo json_encode(array('status' => 'success', 'count' => $count, 'items' => $photos));
JSON array
{
"status":"success",
"count":3,
"items":
[
"img1.jpg",
"img2.jpg",
"img3.jpg"
]
}
I use the below method to fetch and store ID of the desired gallery,
<input type="hidden" value="<?php echo $id; ?>" id="displayid" />
and then I call it back to use it in AJAX.
var ID = $('#displayid').val();
AJAX and JQM
$.ajax({
Type: "GET",
url: 'photos.php',
data: { display: ID }, // = $('#displayid').val();
dataType: "json",
contentType: "application/json",
success: function(data) {
var count = data.count;
var number = 0;
$.each(data.items, function(i,item) {
var newPage = $("<div data-role=page data-url=page" + number + "><div data-role=header><h1>Photo " + number + "</h1></div><div data-role=content><img src=" + item + " /></div></div");
newPage.appendTo( $.mobile.pageContainer );
number++;
if (number == count) { $.mobile.changePage( newPage ); }; // it goes to last page
I got this code from here thanks Gajotres to dynamically navigate between pages. It's within the same code.
$(document).on('pagebeforeshow', '[data-role="page"]', function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.activePage.find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'b'}).addClass('ui-btn-right').html('Next').button());
}
}); // next button
}); // each loop
} // success
}); //ajax
I found your problem.
This part of code can't be used here like this:
$(document).on('pagebeforeshow', '[data-role="page"]', function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.activePage.find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'b'}).addClass('ui-btn-right').html('Next').button());
}
});
This is the problem. First remove pagebeforeshow event binding, it can't be used here like that. Rest of the code is not going to do anything because currently there are any next page (next page is going to be generated during then next loop iteration), so remove this whole block.
Now, after the each block ends and all pages are generated (that is the main thing, all pages should exist at this point), add this code:
$('[data-role="page"]').each(function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$(this).find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'a'}).addClass('ui-btn-right').html('Next').button());
}
});
This is what will happen. Each loop will loop through every available page (we have them all by now) and in case it is not the last one it will add next button.
Here's a live example: http://jsfiddle.net/Gajotres/Xjkvq/
Ok in this example pages are already there, but point is the same. They need to exist (no matter if you add them dynamically or if they are preexisting) before you can add next buttons.
I hope this helps.

getting info from json with jquery

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 />");
}
});
});

How do I send and receive vars with jquery and AJAX?

so lets say this is my jquery portion of the code:
$.ajaxSetup ({
cache: false
});
load() functions
var loadUrl = "load.php";
$("#load_basic").click(function(){
$("#result").load(loadUrl + "?language=php&version=5");
});
});
and this is "load.php"
<?php $_GET['language'] .= "cool"; $_GET['version']+=2; ?>
How do I return the processed language and version vars back to my #result div?
Sorry if I'm doing this wrong. Pretty comfortable in php and jquery, but ajax sort of confuses me and I haven't found any tutorials that really clicked.
I know I can echo these vars out, and that will return the contents of load.php into my div.. but that seems clunky, and I doubt that's the way people actually do it..
JQuery
$("#load_basic").click(function(){
$.get(loadUrl + "?language=php&version=5", function(data){
var obj = eval(data)
$("#result").html(obj.language + " " + obj.version)
});
});
PHP
<?php $_GET['language'] .= "cool"; $_GET['version']+=2;
echo "{\"language\" : \"".$_GET['language']."\",\"version\" : \"".$_GET['version']."\"" ?>
not tested and not bullet-proof, but the concept is here. Return somthing in your PHP that you can read back (i choose JSON)
" What If I'm echoing out two or three vars in php, and I want them to be seperated and echoed out to different divs.. "
I'm ASP and not PHP but I think the prinicple is the same.
I have this is my requesting page:
<script type="text/javascript">
$(document).ready(function(){
$("#list").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#list option:selected").val();
var bob = $("#list option:selected").text();
if (selected.length > 0) {
$.post("twopart.asp", { thing: selected, bob: bob }, function(data) {
var dataraw= data;
var dataarray = (dataraw).split("~~~");
var outone= dataarray["0"];
var outtwo= dataarray["1"];
var outthree= dataarray["2"];
$("#output1").html(outone);
$("#output2").html(outtwo);
$("#output3").html(outthree);
});
}
}
</script>
and this is in my processing page:
response.write bunch of stuff and ~~~
response.write bunch of stuff and ~~~
response.write more stuff
Sorry is the formatting is off- still learning how to do it.
Anyway, the "echoing page" echos its content with the three tildes stuck in there. Then I parse the return on the tildes and write different places.
Hope this is helpful.
The JSON answer by Grooveek is probably better.
try
$.ajax({
url:YOUR_URL,
dataType:'json',
type:'POST',
data:'&var1=value1&var2=value2',
beforeSend:function(){
//
},
success:function(response){
//complete
$('#container').html(response.result + ' ' + response.other);
}
});
in your php
$var1 = $_POST['var1'];
//your proccess
$result = array(
'result' => 'ok',
'other' => 'value'
);
echo json_encode($result);

Categories