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>')); ?>' };
Related
I have a code here
<h2>Click blue button</h2>
<button id="open_btn" class="btn btn-primary">Open dialog</button>
<div id="output"></div>
<script src="src/bootstrap.fd.js"></script>
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
its a drag and drop upload using jquery and boostrap layout from http://www.jqueryscript.net/demo/Drag-Drop-File-Upload-Dialog-with-jQuery-Bootstrap. Its working, but the problem is, I don't know how to pass the data uploaded to php for processing and put the file into the server.
Anyone can help me with this?
you can try using ajax. Setup ajax in your project from tons of tutorials available on the net.
After that in your javascript function i suppose you want to pass variable text to php. So here's what you can do when you get a little hang about ajax by going through the tutorials
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$.ajax({
url: "'your php function name'?name ="+text,
success: function( data ) {
if(data == "retn value") { //return value of the php function
// alert("");
} else {
}
}
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
create a function in php which will take your data as an argument.
hope this helps.
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
}
});
I'm totally new to jquery and AJAX, After trying hard for 5-6 hours and searching the solution I'm asking for the help.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit").live('click',(function() {
var data = $("this").serialize();
var arr = $("input[name='productinfo[]']:checked").map(function() {
return this.value;
}).get();
if(arr=='')
{
$('.success').hide();
$('.error').show();
}
else
{
$.ajax({
data: $.post('install_product.php', {productvars: arr}),
type: "POST",
success: function(){
$(".productinfo").attr('checked', false);
$('.success').show();
$('.error').hide();
}
});
}
return false;
}));
});
</script>
and HTML+PHP code is,
$json = file_get_contents(feed address);
$products = json_decode($json);
foreach(products as product){
// define various $productvars as a string
<input type="checkbox" class="productvars" name="productinfo[]" value="<?php echo $productvars; ?>" />
}
<input type="submit" class="submit" value="Install Product" />
<span class="error" style="display:none"><font color="red">No product selected.</font></span>
<span class="success" style="display:none"><font color="green">product successfully added to database.</font></span>
As I'm pulling the product information from feed, I don't want to refresh the page, that's why I'm using AJAX post method. Using above code "install_product.php" page is handling the string properly and doing its job properly.
The problem I'm facing is, when first time I check the check box and install the product it works absolutely fine, but after first post "Sometimes it work and sometimes it won't work". As new list is pulled from feed every first post is perfect after that I need to click install button again and again to do so.
I tested the code on different browsers, but same problem. What may be the problem?
(I'm testing the code on live host not localhost)
$.live is deprecated, consider using $.on() instead.
Which function is not executing after it executes once? $.live?
Also, it should be:
var data = $(this).serialize();
not
var data = $("this").serialize();
In your example, you are looking for an explicit tag called 'this', not a scope.
UPDATE
$(function () {
$(".submit")
.live('click', function(event) {
var data = $(this).serialize();
var arr = $("input[name='productinfo[]']:checked")
.map(function () {
return this.value;
})
.get();
if (arr == '') {
$('.success')
.hide();
$('.error')
.show();
} else {
$.ajax({
data: $.post('install_product.php', {
productvars: arr
}),
type: "POST",
success: function () {
$(".productinfo")
.attr('checked', false);
$('.success')
.show();
$('.error')
.hide();
}
});
}
event.preventDefault();
});
});
Is it possible, it is missing the value at arr and showing up the error or is it like it is making call but not returning or it is not reaching the call at all?
Do a console.log to deal with debuging and check things out in firefox / chrome and see what and where is the issue.
I got a page with a form to fill it with custormers info. I got previous custormers data stored in a php array. With a dropdownlist users can fill the form with my stored data.
what i have is a jquery function that triggers when the value changes and inside that function i whould like to update the form values with my stored data (in my php array).
Problem is that i dont know how to pass my php array to the jquery function, any idea ??
this is how i fill the array:
$contador_acompanantes = 0;
foreach ($acompanantes->Persona as $acomp)
{
$numero = $acomp->Numero;
$apellidos = $acomp->Apellidos;
$nombre = $acomp->Nombre;
$ACOMPANANTES[$contador_acompanantes] = $ficha_acomp;
$contador_acompanantes++;
}
got my select object:
<select name="acompanante_anterior" id="acompanante_anterior">
<option value="1" selected>AcompaƱante</option>
<option value="2">acompanante1</option>
<option value="2">acompanante2</option>
</select>
and this is my code for the jquery function (it is in the same .php page)
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
});
});
</script>
var arrayFromPHP = <?php echo json_encode($phpArray); ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
You'll likely want to use json_encode, embed the JSON in the page, and parse it with JSON-js. Using this method, you should be aware of escaping </script>, quotes, and other entities. Also, standard security concerns apply. Demo here: http://jsfiddle.net/imsky/fjEgj/
HTML:
<select><option>---</option><option>Hello</option><option>World</option></select>
<script type="text/javascript">
var encoded_json_from_php = '{"Hello":[1,2,3], "World":[4,5,6]}';
var json = JSON.parse(encoded_json_from_php);
</script>
jQuery:
$(function() {
$("select").change(function() {
$(this).unbind("change");
var val = json[$(this).val()];
var select = $(this);
$(this).empty();
$.each(val, function(i, v) {
select.append("<option>" + v + "</option>");
});
});
});
try this one..
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
my_array = new Array();
<?php foreach($array as $key->val)?>
my_array['<?php echo $key?>'] = '<?php echo $val;?>';
<?php endif; ?>
});
});
</script>
Hello this is code snippet which i get from Jquery Ajax based search
I am done with everything, just the problem is the following script may not be sending the POST variable and its values or may be i am not properly fetching it.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {
contentVar: data
}, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
In php file i have the following code:-
if (isset($_POST['cv']))
{
// My Conditions
}
else
{
// Show error
}
And its showing error, This means everything is correct just the post is not working properly, maybe.
Do the var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables will do the needful or we need to do any modifications. I know questions like this really annoy people, but what should i do i am stuck up.. #userD has really helped me a lot just, this part is left.
Since you're using $.post instead of $.ajax, your call should be:
$.post(url, data, function(response) {
/// ...
});
data must be a Javascript object, like this:
data = { "cv" : cv, "cvtwo" : cvtwo };
Check Jquery's documentation for more info:
http://docs.jquery.com/API/1.1/AJAX#.24.post.28_url.2C_params.2C_callback_.29