PHP Arrays with Datatables - php

I have been playing around with datatables and now have a requirement to filter a table via select/dropdown which should filter one of my columns. My code is:
<?php
$urlPriority = $_GET['priority'];
if (empty($urlPriority)) {
$urlPriority = 'High';
}
$priorityStatus = array('Low'=>'Low Priority', 'Medium'=>'Medium Priority', 'High'=>'High Priority');
echo createSelectControl('Priority', $priorityStatus, $urlPriority, -1, false, 'reload();')
?>
<script type="text/javascript">
function reload() {
var priority = $("#Priority").val();
location.search = '?priority=' + priority;
}
</script>
I added the line of code to my sql query:
$sql = "SELECT * from [table_name]
WHERE ... AND
Priority = '" . mssql_escape($urlPriority) . "' AND
etc AND
etc ";
This works great when selecting one of the options.
All I need now is for the user to be able to select all options, including Low, Medium and High, I have tried all methods i can think of but it just returns an empty table?
Thanks for any suggestions.

Use this,
if($urlPriority!="")
{
//query with priority filter
}
else
{
//query without priority filter
}
if user select priority value assign it to $urlPriority, else make it empty. then it will retrieve every result

Found a solution which does exactly what i needed, thought i'd share the JSFiddle
initComplete: function() {
var column = this.api().column(2);
var select = $('<select class="filter"><option value=""></option></select>')
.appendTo('#selectTriggerFilter')
.on('change', function() {
var val = $(this).val();
//column.search(val ? '^' + $(this).val() + '$' : val, true, false).draw();
column.search(val).draw()
});
var offices = [];
column.data().toArray().forEach(function(s) {
s = s.split(',');
s.forEach(function(d) {
if (!~offices.indexOf(d)) {
offices.push(d)
select.append('<option value="' + d + '">' + d + '</option>'); }
})
})
}
http://jsfiddle.net/m1Ly9uxf/15/

Related

Passing a JSON array from PHP to JQuery is not working

I am having trouble accesssing a jquery array which is getting JSON data from a PHP script. If I hard coded the array in jquery it worked fine. I checked using cosole.log. Both nproducts and products array giving the same values. Please note that nproduct has hard coded values where are product is getting from a PHP script. Can someone put my in the right direction. Thanks
here is the PHP Code
while ($row = oci_fetch_array($result,OCI_ASSOC)) {
$shop[$row['WH_DESCRIPTION']] = array(
'pic' => $row['WH_PIC'],
'price' => $row['WH_PRICE']
);
}
echo json_encode($shop);
here is the jquery. If I use nproduct then productsRendering function works fine but if I use product then it print containsValue for name and pic and undefined for price. It seems that the product array does not have any values in the productRendering function where as getJSON is returning values.
<script type="text/javascript">
var cart = (function ($) {
var productsOffset = 3, products = [],
nproducts = {
'Black T-shirt': {
pic: 'black-controller.png',
price: 15
},
'Green T-shirt': {
pic: 'green-kentucky.png',
price: 18
},
'Brown T-shirt': {
pic: 'brown-computer.png',
price: 25
}
};
$.getJSON('shop.php', function(data) {
products = data;
console.log(data); //showing values here
console.log(products); //showing values here
console.log(nproducts); //showing values here
});
function render() {
productsRendering();
};
function productsRendering() {
var catalog = $('#catalog'),
imageContainer = $('</div>'),
image, product, left = 0, top = 0, counter = 0;
console.log(products); //does not have values here
for (var name in products) {
product = products[name];
image = createProduct(name, product);
image.appendTo(catalog);
if (counter !== 0 && counter % 3 === 0) {
top += 147; // image.outerHeight() + productsOffset;
left = 0;
}
image.css({
left: left,
top: top
});
left += 127; // image.outerWidth() + productsOffset;
counter += 1;
}
$('.draggable-demo-product').jqxDragDrop({ dropTarget: $('#cart'), revert: true });
};
function createProduct(name, product) {
return $('<div class="draggable-demo-product jqx-rc-all">' +
'<div class="jqx-rc-t draggable-demo-product-header jqx-widget-header-' + theme + ' jqx-fill-state-normal-' + theme + '">' +
'<div class="draggable-demo-product-header-label"> ' + name + '</div></div>' +
'<div class="jqx-fill-state-normal-' + theme + ' draggable-demo-product-price">Price: <strong>$' + product.price + '</strong></div>' +
'<img src="images/t-shirts/' + product.pic + '" alt='
+ name + '" class="jqx-rc-b" />' +
'</div>');
};
function init() {
render();
};
return {
init: init
}
} ($));
$(document).ready(function () {
cart.init();
});
</script>
productsRendering() gets called before ajax request completes. Consider calling productsRendering() inside the ajax callback.
This is because the browser does not interpret the response body as JSON. Try setting Content-Type header in php before echoing response:
header('Content-Type', 'application/json');

Ajax and php when inserting into MySQL

Simple question guys , i have AJAX that pickup all data from page and it suppose to open new php page to update MySQL database , its only updating last row of data , BUT when i use alert from javascript just to check all data i got he does update whole table ... is there any chance that AJAX is not working fast enough or something?
here is my code
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var MatchID = '';
var HomeTeam = '';
var AwayTeam = '';
var TipID = '';
var arrayMaxValues = 3;
var myArray = new Array(3);
var i = 0;
$('#teams_table input[type=text]').each(function () {
myArray[i] = $(this).val();
if (!!myArray[2])
{
MatchID = myArray[0];
HomeTeam = myArray[1];
AwayTeam = myArray[2];
if (HomeTeam > AwayTeam) {
TipID = 1;
}
else if (HomeTeam == AwayTeam) {
TipID = 2;
}
else if (HomeTeam < AwayTeam) {
TipID = 3;
}
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' +
TipID + '&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, true);
http.send(null);
myArray = new Array(3);
i=0;
}
else
{
i++;
}
});
It is kinda odd to me when i use
alert('MatchID = ' + MatchID + ' HomeTeamScore = ' + HomeTeam + ',
AwayTeamScore = ' + AwayTeam)
Inside of AJAX code i get whole table updated , without it just last row
And my php page
<?php
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$HomeScore = $_GET['HomeTeam'];
$AwayScore = $_GET['AwayTeam'];
$query="update probatip1.matches set ResultTipID=".$tipID.",HomeTeamScore = "
.$HomeScore.",AwayTeamScore= ".$AwayScore." where MatchID =".$matchID;
$UpdateGame= mysql_query($query) or die(mysql_error());
mysql_close()
?>
Try encoding the data. i.e:
MatchID = encodeURIComponent(myArray[0]);
HomeTeam = encodeURIComponent(myArray[1]);
AwayTeam = encodeURIComponent(myArray[2]);
in php use
function escapedata($data) {
if(get_magic_quotes_gpc()) {
$data= stripslashes($data);
}
return mysql_real_escape_string($data);
}
to escape your data before updating the table. i.e:
$query="update probatip1.matches set ResultTipID=".escapedata($tipID).",HomeTeamScore = ".escapedata($HomeScore).",AwayTeamScore= ".escapedata($AwayScore)." where MatchID =".escapedata($matchID);
Hope this works.
Not really a direct answer, just something that you can base your answer from. What the code does is to submit a whole object using the $.post method in jquery which takes in 2 parameters and a callback function which is executed once the request is done.Not really sure by: open new php page to update MySQL database but I assume that you're simply using that page to update the database and not actually open it.
<script src="js/jquery.min.js"></script>
<script>
var obj = {
'teams' : [
{'name' : 'teamA', 'grade' : 'A'},
{'name' : 'teamB', 'grade' : 'B'}
]
};
$.post('access.php', {'obj' : obj}, function(data){
var d = JSON.parse(data);
for(var x in d){
console.log(d[x].name);
}
});
</script>
access.php:
<?php
$post = $_POST['obj']['teams'];
$array = [];
foreach($post as $row){
$name = $row['name'];
$grade = $row['grade'];
$array[] = ['name'=>$name, 'grade'=>$grade];
}
echo json_encode($array);
?>
So you only have to modify the php page, and put your database query inside the loop. This way you won't need to perform so many ajax request by putting it inside $.each
Then utilize $.each to build the object that you're going to submit via ajax through $.post method:
var obj = {};
$().each(function(index){
var myArray[i] = $(this).val();
var MatchID = myArray[0];
var HomeTeam = myArray[1];
var AwayTeam = myArray[2];
obj[index] = [];
obj[index]['match_id'] = MatchID;
});
The problem is with your logic in the way you are sending requests to php file to update the MYSQL. Actually you are running the ajax request in a loop and the loop is too fast that kills the previous update request.
Solution
You can compose an array and send it to the php outside the loop. That will work for you.
Guys with your help i managed to fix my problem
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' + TipID +
'&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, false);
http.send(null);
var response = http.responseText;
So basicly with this line i told http request not to go for next line of code until update in table is not completed , when http has done his job then it moves on next line of code.
Thank you for help

Minimize jQuery Function

I have a function that adds change events for form items based on the row name(uses the database to get these).
Heres the current function:
$sql = "SELECT * FROM product WHERE storeno = '1' ORDER BY descript";
$result = mssql_query($sql, $msConnection);
if ($result && mssql_num_rows($result) > 0) {
while ($row = mssql_fetch_object($result)) {
$sku = trim($row->mas90sku);
$JQueryReadyScripts .= "
$('#newCount_" . $sku . "_row .cases').change(function() {
var count = 0;
$('#newCount_" . $sku . "_row .cases').each(function () {
count += parseFloat($(this).val());
});
$('#cases_total_" . $sku . "').text(count);
});
$('#newCount_" . $sku . "_row .units').change(function() {
var count = 0;
$('#newCount_" . $sku . "_row .units').each(function () {
count += parseFloat($(this).val());
});
$('#units_total_" . $sku . "').text(count);
});";
}
mssql_free_result($result);
}
How can I consolidate this into a call that affects every row so that I can get rid of the DB portion and have just 2 pieces (or 1) of code instead of 2 for every row.
You could do something like this for both cases and units (Just note, you will need to change the id's of the total counts appropriately)
$('.cases').change(function() {
var id = $(this).attr('id');
var count = 0;
$('#'+id+' .cases').each(function() {
count += parseFloat($(this).val());
});
$('#count_'+id).text(count);
});
$('*[id^=newCount_]').each(function () {
var $row = $(this),
sku = this.id.replace(/newCount_(.*?)_row/, '$1');
function sumValues($elems) {
var sum = 0;
$elems.each(function () { sum += parseFloat(this.value) });
return sum;
}
$.each(['cases', 'units'], function (i, type) {
$row.on('change', '.' + type, function () {
$('#' + type + '_total_' + sku).text( sumValues($row.find('.' + type)) );
});
});
});
This has no dependency on PHP, just use it as a regular script.
It uses .on() event delegation, so it requires jQuery 1.7+. For earlier versions of jQuery you can use .delegate() for the same effect.
I'd recommend giving all your rows a common CSS class, so that the not-so-nice $('*[id^=newCount_]') can be replaced with something simpler, but that's a cosmetic change.
The main difference between class selectors and id selectors is where id selectors are expected to be unique, class selectors are not.
Using $(this) in the body of your change events, so the operations are relative, you could write one single change event that handles all cases.
<input class="cases" id="newCount_123"></input>
<input class="cases" id="newCount_345"></input>
$('.cases').change(function() {
var count = 0;
var sku = $(this).attr("id");
count += parseFloat($(this).val());
$('#cases_total_' + sku).text(count);
});
This also keeps JavaScript out of your PHP, which is hard to maintain and violates MVC principles. Your server-side code does its job of retrieving data and sending it to the client, while your client-side code does its job of dealing with the view.
I'm not sure if this works for both of your functions or not. Not sure of the exact markup. but might be worth trying.
$('#newCount_' + $sku + '_row .cases, #newCount_' + $sku + '_row .units').change(function() {
var count = 0,
thisClass = ( $(this).hasClass('cases') ) ? 'cases' : 'units';
$('#newCount_" . $sku . "_row .'+thisClass).each(function () {
count += parseFloat($(this).val());
});
$('#'+thisClass+'_total_" . $sku . "').text(count);
});

how to get result from mysql and display using jquery when radio button is clicked?

I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);

How to put my JSON info into a jQuery Array

I have a project where I've created JSON data for Project Prices/Prices I've gotten this far and pretty much ran into a wall, any help at all would help! I've checked all over the web and on jQuery.getJSON but I wound up getting super confused.
$data = mysql_query("SELECT * FROM xxx")
or die(mysql_error());
$arr = array();
$rs = mysql_query("SELECT product, price FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"products":'.json_encode($arr).'}';
I need to get the product price and product name into this jquery script
$(document).ready(function() {
/*** CONSTANTS ***/
var KEY = 0;
var VALUE = 1;
/*** DEFINE DATA SETS ***/
var POINTS = [ ["$productA", $PRICE ], ["$productB", $PRICE], ["$productC", $PRICE], ["$productD", $PRICE], ["$productE", $PRICE], ["$productF", $PRICE] ];
var SHIPPING_COSTS = [ ["Pickup", 0], ["Next Day Delivery", 30], ["Same Day Print/Same Day Delivery", 65] ];
for (var i = 0; i < POINTS.length; i++) {
$("#quantity").append("<option value='" + POINTS[i][VALUE] + "'>" + POINTS[i][KEY] + "</option>");
}
for (var i = 0; i < SHIPPING_COSTS.length; i++) {
$("#shipping").append("<option value='" + SHIPPING_COSTS[i][VALUE] + "'>" + SHIPPING_COSTS[i][KEY] + "</option>");
}
$("select.autoUpdatePrice, input.autoUpdatePrice").bind("mousedown click change", function(event) {
Calculate();
});
Calculate();
});
function Calculate() {
var net = parseFloat($("#quantity").val());
/* Calculate the magical # by adding the form fields*/
var designFee = $("#abcDesignFee").attr("checked") ? $("#abcDesignFee").val() : 0.0;
var proofFee = $("#abcProofFee").attr("checked") ? $("#abcProofFee").val() : 0.0;
var MyPrice;
MyPrice = parseFloat( parseFloat(proofFee) + parseFloat(designFee) + net + parseFloat($("#shipping").val()));
$("#DumpHere").html("Your Price: $" + formatNumber(MyPrice));
$("#abcName").val($("#quantity").find(":selected").text() + " " + ProductNamePlural);
$("#abcPrice").val(MyPrice);
}
In your PHP script, can you just json_encode() your array of objects without wrapping it in the string? And instead encode the JSON object like so:
<?php
// your script ...
echo json_encode($arr);
This creates an array of JSON encoded objects:
[{"name":"item 1","price":4.99},{"name":"item 2","price":9.99}]
Make an AJAX request in your JS to query your PHP script, and use jQuery's $.each() and $.parseJSON() methods to iterate over the returned JSON data:
$.post('get_products.php', { data: foo }, function(json) {
$.each($.parseJSON(json), function(key, product) {
console.log(product.name + ' ' + product.price);
});
});
Hope this helps :)
When I was learning - I had exactly the same problem - but it got answered here
What I didn't realise at the time was that you can use object notation (which is the ON of json) to access the data you sent.
If you look at my question and the answer I selected, once you have sent the data back to javascriot you can access it easily. In my example it would be as straitforward as using data.catagory_desc in javascript to find the data that was encoded.

Categories