Minimize jQuery Function - php

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

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/

JSONP and GET with callbacks - help needed correcting errors

This is my JSONP file:
<?php
header('Content-type: application/javascript;');
header("access-control-allow-origin: *");
header("Access-Control-Allow-Methods: GET");
//db connection detils
$host = "localhost";
$user = "test";
$password = "test";
$database = "myradiostation1";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT *, DATE_FORMAT(start, '%d/%m/%Y %H:%i:%s') AS start,
DATE_FORMAT(end, '%d/%m/%Y %H:%i:%s') AS end FROM radiostation1");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$shows[$x] = array("id" => $row["id"], "startminutes" => $row["startminutes"], "start" => $row["start"], "endminutes" => $row["endminutes"],"end" => $row["end"],"mediumname" => $row["mediumname"], "longname" => $row["longname"], "description" => $row["description"],"short_id" => $row["short_id"],"promomessage" => $row["promomessage"],"email" => $row["email"],"phonenumber" => $row["phonenumber"],"textnumber" => $row["textnumber"],"textprefix" => $row["textprefix"],"showimage" => $row["showimage"],"longdescription" => $row["longdescription"],"facebooklink" => $row["facebooklink"],"otherlink" => $row["otherlink"],"websitelink" => $row["websitelink"],"keywords" => $row["keywords"] );
}
//echo JSON to page
$response = $_GET["callback"] . "(" . json_encode($shows) . ");";
echo $response;
?>
It does work, up to a point, but getting the {"success":true,"error":"","data":{"schedule": as seen at this site before my json_encode is where I am.
However, I cannot get it to display any data in my table, although it DOES produce code on-screen when I view it at http://www.myradio1.localhost/onairschedule.php.
The actual code is stored at http://www.myradiostations.localhost/schedule.php
and the callback function works OK, one example being http://www.myradiostations.localhost/schedule.php?callback=?&name=Northern+FM and http://www.myradiostations.localhost/schedule.php?callback=?&name=Southern+FM but what do I need to do to make it change like in these examples:
this example and this example, and to generate an error message like this if no such file exists.
I'm halfway there, just need some advice on fixing my code!
Basically, what I'm trying to do... get a JSONP to work in my HTML table which will vary the content depending on the URL in my javascript file on my page, which is:
var doFades = true;
var LocalhostRadioStations = {
Schedule : {}
};
$(document).ready(function(){
LocalhostRadioStations.Schedule.days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
LocalhostRadioStations.Schedule.Show = function () {
_s = null;
_startDate = null;
_endDate = null;
this.days = LocalhostRadioStations.Schedule.days;
_selector = '';
this.setShow = function(s) {
this._s = s;
this._startDate = new Date( parseInt(s.startminutes, 10) * 1000);
this._endDate = new Date(parseInt(s.endminutes, 10) * 1000 );
};
this.getEndDate = function(){
return this._endDate;
}
this.getStartDate = function(){
return this._startDate;
}
this._getShowDay = function (){
return this.days[this.getStartDate().getDay()];
};
this._getShowUnitsTaken = function(){
// if it's the same day
return this._getEndUnits() - this._getStartUnits();
};
this._getEndUnits = function(){
if(this.getEndDate().getHours() == 0)
{
//console.log(this._s.longname +' ends at midnight');
return 48;
}
return this.getEndDate().getMinutes() !== 0 ? (this.getEndDate().getHours() * 2) : (this.getEndDate().getHours() * 2);
};
this._getStartUnits = function(){
if(this.getStartDate().getHours() == 0)
{
return 0;
}
return this.getStartDate().getMinutes() !== 0 ? (this.getStartDate().getHours() * 2) : (this.getStartDate().getHours() * 2);
};
this.getCellPositions = function() {
return {
'start' : this.getStartDate(),
'end' : this.getEndDate(),
'colIndex' : this.getStartDate().getDay() + 2,
'startUnits' : this._getStartUnits(),
'endUnits' : this._getEndUnits(),
'unitsTaken' : this._getShowUnitsTaken()
}
};
this.pad = function(number){
return number < 10 ? '0'+number : number;
};
// return the table cell html.
this.toHtml = function () {
var d = new Date();
var units = this._getStartUnits();
var rowspan = this._getShowUnitsTaken();
var desc = this._s.description;
var name = this._s.longname;
var starttime = this.pad(this.getStartDate().getHours()) + ':' + this.pad(this.getStartDate().getMinutes());
var endtime = this.pad(this.getEndDate().getHours()) + ':' + this.pad(this.getEndDate().getMinutes());
var site = this._s.websitelink;
var cls = this.isActive() ? 'current-program' : '';
var isToday = this.getStartDate().getDay() === d.getDay() ? 'active-program' : '';
var html = '<td class="schedule-show ' + isToday + ' ' + cls + '" rowspan="' + rowspan + '" data-start="' + this.getStartDate() + '" data-end="' + this.getEndDate() + '">';
html += '<div>';
html += '' + name + '';
html += '</div>';
if(doFades)
{
html += '<div class="schedule_details clearfix" style="display:none;">';
html += '<img width="105px" height="105px" alt="' + desc + '" src="' + this._s.showimage + '">';
html += '<strong>' + name + '</strong>';
html += '<p>' + desc + '</p>';
html += '<span>' + starttime + ' - ' + endtime +'</span>';
html += '</div>';
}
html += '</td>';
return html;
};
this.setTableSelector = function(sel){
this._selector = sel;
};
// check if we should add the active class.
this.isActive = function(){
var t = new Date();
return t >= this.getStartDate() && t <= this.getEndDate();
};
};
LocalhostRadioStations.Schedule.ScheduleGen = function(){
return {
insertShow : function(show) {
var p = show.getCellPositions();
$('tr#units-' + p.startUnits).append(show.toHtml());
},
init : function (stationName){
var self = this;
// load the schedule.
$.getJSON('http://www.myradiostations.localhost/schedule.php?callback=?&name=', {
name: 'Northern FM'
}, function(json){
// loop each show and append to our giant table.
// this is well sick.
if(json.success === false)
{
$('.content-inner table').remove();
$('<div>errors</div>').appendTo('.content-inner');
}
else
{
var currentDay = '';
var day = 0;
// highlight the current time..
var d = new Date();
var weekStart = new Date();
weekStart.setDate(d.getDate()-6-(d.getDay()||7));
$.each(json.data.schedule, function(i, broadcast){
var dStart = new Date( parseInt(broadcast.startminutes, 10) * 1000);
var dEnd = new Date(parseInt(broadcast.endminutes, 10) * 1000 );
/*// transform to a show object defined above, if the show spans 2 days we create two show objects.
// IF THE SHOW STARTS/ENDS AT MIDNIGHT, DON'T SPLIT IT.
if(dStart.getHours() !== 0 && dEnd.getHours() !== 0 && dStart.getDate() != dEnd.getDate())
{
var showOne = new LocalhostRadioStations.Schedule.Show();
showOne.setShow(broadcast);
// set to midnight
showOne.getEndDate().setHours(0);
showOne.getEndDate().setMinutes(dStart.getMinutes());
// append first half of show.
self.insertShow(showOne);
// handle second half.
var showTwo = new LocalhostRadioStations.Schedule.Show();
showTwo.setShow(broadcast);
showTwo.getStartDate().setDate(showTwo.getStartDate().getDate() + 1);
showTwo.getStartDate().setHours(0);
showTwo.getStartDate().setMinutes(dEnd.getMinutes());
//console.log('2nd Half Start: ' + showTwo.getStartDate());
//console.log('2nd Half End: ' + showTwo.getEndDate());
self.insertShow(showTwo);
}
else
{*/
var show = new LocalhostRadioStations.Schedule.Show();
show.setShow(broadcast);
show.setTableSelector('table#schedule');
// add the show to the table. Thankfully the order these come out the API means they get added
// in the right place. So don't change the schedule builder code!
self.insertShow(show);
//}
});
var days = LocalhostRadioStations.Schedule.days;
// apply the current day / time classes
$('th:contains('+ days[d.getDay()]+')').addClass('active');
$('td.time').each(function(i, cell){
// get the value, convert to int.
var hours = $(cell).html().split(':')[0];
// compare the hours with now, add class if matched.
if(parseInt(hours, 10) === d.getHours())
{
$(cell).addClass('current_time');
}
});
}
if(doFades)
{
// apply events to show info fade in / out.
$('td.schedule-show').hover(function(){
$(this).find('.schedule_details').fadeIn('fast');
}, function(){
$(this).find('.schedule_details').fadeOut('fast');
});
}
});
}
};
}();
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
});
It should change the schedule according to the JSONP, but what do I do to fix it?
Basically, I am trying to make my own localhost version of http://radioplayer.bauerradio.com/schedule.php?callback=&name=Rock+FM and its JSON / JSONP (I am not sure exactly what type the original is, but then again the site is experimental and on a .localhost domain) for testing purposes where the content is taken from the database, and changes according to station name, e.g. http://radioplayer.bauerradio.com/schedule.php?callback=&name=Metro+Radio and http://radioplayer.bauerradio.com/schedule.php?callback=&name=Forth+One etc.
Edit: The full code for my page can be seen at http://pastebin.com/ENhR6Q9j
I'm not sure exactly what's missing, but from the code you gave so far, I made a jsfiddle:
Demo
I modified some things to make it work (mostly appending stuff), because I don't know your original HTML file. But I also made some changes based on what you say you wanted. First of all I modified your $.getJSON call to be something like:
$.getJSON('http://radioplayer.bauerradio.com/schedule.php?callback=?', {
name: stationName //stationName is from the argument passed
}, function(json){...})
Which should give back the station based on what is passed to
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
To make it more interesting, I also added a bit of code that reads from the url. In this case if you go to the page with a domain.htm/page?Northern FM it will read the text after the ? and put it in twittiName.
var twittiName="Rock FM"; //default station
if(window.location.search){
twittiName=window.location.search.substring(1) //or window.location.hash
}
Tried to look for other stations that might be on your publics site, but so far I could only test with "?Rock+FM". But does mean you can show the errors, which your code can handle as it is.
?Rock+FM
?Random Name
So it seems that your code mostly works but do comment if I have missed anything.

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

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