Passing a JSON array from PHP to JQuery is not working - php

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

Related

PHP Arrays with Datatables

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/

Pass Pagination data to Page

I have a page that I'm trying to get AJAX thumbnail replacement & pagination to work. The page loads the initial thumbs: http://www.partiproductions.com/vault_test/1-a-b.php
But when clicking nav buttons, it should change the thumbnails, but doesn't.
My click function (forward button):
$('#gort').mouseup (function() {
var curpg = parseInt($('.thumbwrap').attr('data-cpg'),10);
console.log('Cur Pg: ' + curpg);
var newpg = curpg + 1;
console.log('New Pg: ' + newpg);
var $totpgs = parseInt($('.thumbwrap').attr('data-tpgs'),10);
console.log('Total Pages: ' + $totpgs);
if (newpg > 1) {$('#goleft').show(200)}
if (newpg == $totpgs) {newpg = $totpgs; $('#gort').hide()} // limit page to total pages
if (newpg < $totpgs) {$('#gort').show(200)}
$('.thumbwrap').attr('data-cpg', newpg);
var $start = (newpg - 1) * 15;
console.log('Start: ' + $start);
// my attempt to pass $start to pagination.php
$.ajax({
url:'pagination.php',
type:'POST',
data:{start:$start},
dataType:'JSON'
success: function(response) {
thumbparse(response);
}
});
});
Currently simple thumbparse function:
function thumbparse(response) {
alert(response);
console.log('Thumbparse output: ' + $navresults);
}
Pagination.php:
<?php
$thumbst = $_POST['start']; // capture input from AJAX
echo "Inside Pagination: $thumbst";
require_once 'meekrodb.2.2.class.php';
require_once 'dconnect.php';
// pull from database using specific page items
$navresults = DB::query("SELECT substr(theme, 1, 1) as Alphabet, theme, developer, thumb, thumb_lg FROM gallery ORDER BY (CASE Alphabet
WHEN '1' THEN 1
WHEN '2' THEN 2
WHEN '3' THEN 3
WHEN 'A' THEN 4
WHEN 'B' THEN 5
ELSE 6
END), theme
LIMIT $thumbst,15");
if(isset($_POST['start']) && !empty($_POST['start'])) {
echo json_encode($navresults);
}
// my attempt to loop through assigned variables that are echoed in main pg
$x = 0;
foreach ($navresults as $row) {
$x++;
if ($x == 1) {
$t1 = $row['theme'];
$d1 = $row['developer'];
$th1 = $row['thumb'];
$thlg1 = $row['thumb_lg'];
}
... other x's
}
I'm not seeing the echoes from pagination.php How do I get the new thumb data ($navresults) passed back to main page and get that data into the DOM? Code please, as I'm just learning - thanks.
Update 1:
function thumbparse(response) {
alert(response);
var obj = JSON.parse(response);
alert(obj.count);
console.log('Thumbparse results: ' + $navresults);
}
Update 2:
function thumbparse(response) {
alert(response);
console.log(response);
var x = 0;
var obj = response;
$.each(obj, function(key, val) {
x++;
var y = x - 1;
$('ul.thumbwrap .thumb:nth-of-type(y) img').attr({
alt: obj.theme,
src: obj.thumb,
'data-retina': obj.thumb_lg
});
$('ul.thumbwrap .thumb:nth-of-type(y) p.hname').text(obj.theme);
$('ul.thumbwrap .thumb:nth-of-type(y) p.hdev').text(obj.developer);
});
}
Update 3:
function thumbparse(response) {
alert(response);
console.log(response);
var x = 0;
var obj = response;
$.each(obj, function(key, val) {
x++;
var y = x - 1;
console.log('Exist. src: ' + $('.thumb').eq(y).find('img').attr('src')); // correct
console.log('New src: ' + obj.thumb); // undefined
$('.thumb').eq(y).find('img').attr({
alt: obj.theme,
src: obj.thumb,
'data-retina': obj.thumb_lg
});
$('.thumb').eq(y).find('p.hname').text(obj.theme);
$('.thumb').eq(y).find('p.hdev').text(obj.developer);
});
}
Update 4:
function thumbparse(response) {
alert(response);
console.log(response);
var x = 0;
var obj = response;
$.each(obj, function(key, val) {
x++;
var y = x - 1;
console.log('Exist. src: ' + $('.thumb').eq(y).find('img').attr('src'));
console.log('New src: ' + obj[key].thumb);
$('.thumb').eq(y).find('img').attr({
alt: obj[key].theme,
src: obj[key].thumb,
'data-retina': obj[key].thumb_lg
});
$('.thumb').eq(y).find('p.hname').text(obj[key].theme);
$('.thumb').eq(y).find('p.hdev').text(obj[key].developer);
if (obj[key].theme == '') {$('.thumb').eq(y).hide()}
});
}
Try this:
function thumbparse(response) {
console.log(response);
var x = 0;
var obj = response;
$.each(obj, function(key, val) {
x++;
var y = x - 1;
console.log('Exist. src: ' + $('.thumb').eq(y).find('img').attr('src'));//Actual src
console.log('New src: ' + obj[key].thumb); //new src from json response
$('.thumb').eq(y).find('img').attr({
alt: obj[key].theme,
src: obj[key].thumb,
'data-retina': obj[key].thumb_lg
});
$('.thumb').eq(y).find('p.hname').text(obj[key].theme);
$('.thumb').eq(y).find('p.hdev').text(obj[key].developer);
if (obj[key].theme == '') {$('.thumb').eq(y).hide()}
});
}

jquery autocomplete with php foreach generated results

I have been trying for days to get jquery autocomplete to work the way I need it to.
so far I have this which works fine:
<script>
$(function() {
var availableTags = [<?php
$taglist = Array();
foreach ($users as $user)
if ($user->getAttribute('first_name') == ''){
$taglist[] = '"'.$user->getUserName().'"';
}else{
$taglist[] = '"'.$user->getAttribute('first_name').' '.$user->getAttribute('last_name').'"';
}
echo join(',', $taglist);
?>];
$("#searchmem").autocomplete({
source: availableTags,
minLength: 2,
select: function(event, ui) {
$("#searchmem").val(ui.item.label);
$("#submit").click();
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='/files/avatars/1.jpg' />" + item.label + "</a>")
.appendTo(ul);
}
});
</script>
This will output the image /files/avatars/1.jpg next to the respective users username or full name.
The problem I'm having is trying to output the right users avatar. Each .jpg file corresponds with the username so I could have used $user->getUserID() in the src but this won't work because it's not inside the foreach $users as $user loop.
I have tried putting the whole autocomplete script inside the foreach which when tested did alert the right thing but autocomplete wouldn't work.
I have also tried creating two variables such as
availableTags1 = { label: .... $user->getUserName() etc... }
availableTags2 = { avatar: .... $user->getUserID() etc... }
availableTags = availableTags1 + availableTags2;
and
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src=' + item.avatar + ' />" + item.label + "</a>")
.appendTo(ul);
}
But again this didn't work. I'm completely lost! How can I get it to output the image alongside the relevant username? Help would be much appreciated.
In your case, you have to build an array like :
var availableTags = [
{label: '...', avatar: '...'},
{label: '...', avatar: '...'},
...
];
And use:
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.label + "</a>") // Note the additional double quotes
.appendTo(ul);
}
(see this example on jQuery UI for using custom data)
Then, for generating you array via PHP, you should use:
<?php
$taglist = Array();
foreach ($users as $user) {
$data = array();
if ($user->getAttribute('first_name') == ''){
$data["label"] = $user->getUserName();
} else {
$data["label"] = $user->getAttribute('first_name').' '.$user->getAttribute('last_name');
}
$data["avatar"] = $user->getUserID();
$taglist[] = $data;
}
?>
var availableTags = <?php echo json_encode($taglist); ?>;

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