Multiple fields with the same name in AJAX and PHP - javascript

Everyone.
I got some good help a couple of days ago, so I'm hoping that someone can show me where I'm going wrong here. Basically, what I'm trying to do is update a MySQL database in the background when a user clicks a button. The form is a series of records, and the records have common field names (ID, DSA_Number, Manager_Review, etc.) Right now, the code doesn't even seem to return success or failure messages.
Here's the script on the main page:
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("#Manager_Review").val();
var RID=$("#RID").val();
var Services=$("Services").val();
var Dues_List=$("Dues_List").val();
var ID=$("ID").val();
var myrid=$("myrid").val();
var Manager_Comments=$("Manager_Comments").val();
var President_Comments=$("President_Comments").val();
var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review+'&RID='+RID+'&Services='+Services+'&Dues_List='+Dues_List+'&Manager_Comments='+Manager_Comments+'&President_Comments='+President_Comments;
$.ajax({
type: "GET",
url:'baseupdater-test.php' + dataTosend,
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
});
</script>
Here's the code that draws the rows on the table:
<?php
/* This code writes the rows in the table for baserecord.php */
$n = 0;
$o = $n + 1;
$firstday = date('m/1/Y');
if(isset($_GET['MR'])) // If $_GET['MR'] is set ...
{
$MR = $_GET['MR']; // Set the variables.
$PR = $Pres_Rev;
}
else // If not, select the maximum (latest) Manager Review Date.
{
$getmr = "select max(STR_TO_DATE(Manager_Review_Date, '%m/%d/%Y')) as Manager_Review_Date,
President_Review_Date from clientdb.MRS2_test
inner join clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where SCID = '$ID';";
$rs2 = mysqli_query($con,$getmr);
$rvd = mysqli_fetch_assoc($rs2);
$MR = date('m/d/Y', strtotime($rvd['Manager_Review_Date']));
echo "MR: $MR<br>";
$PR = date('m/d/Y', strtotime($rvd['President_Review_Date']));
}
// The following query select the data for the row and orders it by the latest Manager Review Date.
$cliselect = "select distinct clientdb.Plans.Client_ID, clientdb.clients_MRS.DSA_Status, clientdb.clients_MRS.DSA_Status_Date, clientdb.clients_MRS.First_Name, clients_MRS.Last_Name, clientdb.clients_MRS.County, clientdb.Plans.DDD_Case, RID, Plans.Program, max(Plans.Plan) as MPlan, Tier, Plan_End_Date, clientdb.MRS2_test.RID, clientdb.MRS2_test.President_Comments, clientdb.MRS2_test.Manager_Comments, clientdb.MRS2_test.Services_Issues, clientdb.MRS2_test.Dues_List
from clientdb.Plans
inner join clientdb.clients_MRS on clientdb.clients_MRS.DDD_Case = clientdb.Plans.DDD_Case
inner join clientdb.MRS2_test on clientdb.MRS2_test.DDD_Number = clientdb.Plans.DDD_Case
where SCID = '$ID' and (DSA_Status = 'Active' OR (DSA_Status <> 'Active' AND STR_TO_DATE(DSA_Status_Date, '%d/%m/%Y') > STR_TO_DATE($firstday, '%m/%d/%Y'))) AND (Manager_Review_Date = '$MR')
group by clientdb.Plans.DDD_Case order by STR_TO_DATE(clientdb.MRS2_test.Manager_Review_Date, '%m/%d/%Y') DESC, clientdb.Plans.Last_Name;";
//echo "cliselect $cliselect<br>";
$cres = mysqli_query($con, $cliselect);
while ($dddr = mysqli_fetch_assoc($cres)) {
$DDD_Case = $dddr['DDD_Case'];
$First_Name = $dddr['First_Name'];
$Last_Name = $dddr['Last_Name'];
$County = $dddr['County'];
$Tier = $dddr['Tier'];
if($ddr['Plan_End_Date'] <> '')
{
$Plan_End_Date = $dddr['Plan_End_Date'];
}
$Pres_Comments = $dddr['President_Comments'];
$Mgr_Comments = $dddr['Manager_Comments'];
$Dues = $dddr['Dues_List'];
$Services = $dddr['Services_Issues'];
$RID = $dddr['RID'];
$mxselect = "select max(Plan) as MPlan from clientdb.Plans where clientdb.Plans.DDD_Case = '$DDD_Case';";
$rens = mysqli_query($con, $mxselect);
$rmm = mysqli_fetch_assoc($rens);
$MPlan = $rmm['MPlan'];
$endsel = "select Plan_End_Date, Program from clientdb.Plans where clientdb.Plans.DDD_Case = $DDD_Case and clientdb.Plans.Plan = $MPlan;";
$rsel = mysqli_query($con, $endsel);
$end = mysqli_fetch_assoc($rsel);
$Plan_End_Date = $end['Plan_End_Date'];
$Program = $end['Program'];
//The purpose of ths quer s to get the RID for each row.
$mrselect = "select * from MRS2_test where DDD_Number = '$DDD_Case' and Manager_Review_Date = '$MR'
group by DDD_Number, RID
order by RID DESC
Limit 1 ;";
$run = mysqli_query($con,$mrselect);
$mrss = mysqli_fetch_assoc($run);
$Manager_Review_Date = $mrss['Manager_Review_Date'];
$President_Review_Date = $mrss['President_Review_Date'];
$myRID = $mrss['RID'][$n];
echo "<tr><td>$o</td><td sorttable_customkey='$DDD_Case'><input class='ddd' type = 'text' value = '$DDD_Case' name = 'DDD_Number[]' size='6'></td><td sorttable_customkey='$Last_Name'>$First_Name $Last_Name</td><td>$County</td><td>$Program</td><td>$Tier</td><td sorttable_customkey='";
?>
<?php echo strtotime($Plan_End_Date);
echo "'>$Plan_End_Date</td><td><textarea class='expnd' name='Services[]'>$Services</textarea></td><td><input name='Dues_List[]'' type = 'text' value = '$Dues'></td><td><textarea class='expnd' name='Manager_Comments[]'>$Mgr_Comments</textarea></td><td><textarea class='expnd' name='President_Comments[]'>$Pres_Comments</textarea></td><td><input type='text' size='4' name = 'myrid[]' value='$RID' readonly></td><input type='hidden' name = 'manreview-orig' value='$Manager_Review_Date'></tr>";
$n = $n++;
$o++;
}
?>
And finally, this is the code that does the update:
<?php
include 'config.php';
$con = mysqli_connect($DB_server, $DB_user, $DB_password, $DB_database);
$Manager_Review = $_GET['Manager_Review'];
$Old_MR = $_GET['manreview-orig'];
//echo "OLD MR: $Old_MR<br>";
if($_GET['President_Review'] == '12/31/1969')
{
$President_Review = '';
}
if($_GET['President_Review'] <> '')
{
$President_Review = $_GET['President_Review'];
}
else
{
$President_Review = '';
}
$ID = $_GET['ID'];
$Services = $_GET['Services'];
echo "New Content!<br>";
$n = 0;
while ($n <= sizeof($_GET)) {
$ridselect = "select clientdb.MRS2_test.RID, clientdb.clients_MRS.DDD_Case, clientdb.clients_MRS.SCID from clientdb.MRS2_test
inner join clientdb.clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where Manager_Review_Date = '$Old_MR' and clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
order by RID;";
$rsc = mysqli_query($con, $ridselect);
$rowrid = mysqli_fetch_assoc($rsc);
$RID = $_GET['myrid'][$n];
// echo "RID: $RID<br>";
$MDD = $_GET['RID'];
$myrid = $_GET['myrid'][$n];
$DDD_Case = $_GET['DDD_Number'][$n];
$Period = ltrim(substr($Manager_Review,0,2), "0");
$Services = mysqli_real_escape_string($con, $_GET['Services'][$n]);
$Manager_Comments = mysqli_real_escape_string($con, $_GET['Manager_Comments'][$n]);
$President_Comments = mysqli_real_escape_string($con, $_GET['President_Comments'][$n]);
$Dues_List = mysqli_real_escape_string($con, $_GET['Dues_List'][$n]);
$DDD_Case = $_GET['DDD_Number'][$n];
$updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Services_Issues = '$Services',
clientdb.MRS2_test.Manager_Comments = '$Manager_Comments', clientdb.MRS2_test.President_Comments = '$President_Comments',
clientdb.MRS2_test.Dues_List = '$Dues_List', Period = '$Period' where DDD_Number = '$DDD_Case' and RID = '$RID';";
echo $updater . "<br>";
$date_updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Manager_Review_Date = '$Manager_Review',
clientdb.MRS2_test.President_Review_Date = '$President_Review' where RID = '$RID';";
echo "dateupdater: $date_updater<br>";
if(!mysqli_query($con, $date_updater))
{
echo "That failed miserably.<br>";
}
else
{
$rws = mysqli_affected_rows($con);
echo "affected rows: $rws<br>";
echo "Success.<br>";
}
mysqli_query($con, $updater);
$datestamp = date('Y-m-d h:i:s');
$upstamp = "update clientdb.MRS2_test set Update_Time = '$datestamp' where DDD_Case = '$DDD_Case' and RID = '$RID';";
mysqli_query($con,$upstamp);
$n++;
}
echo "<script language='Javascript'>document.getElementById('stuffhere').InnerHTML = '<?php echo $updater; ?>';</script>";
?>
I've tried serializing the form, and I haven't had any success there. Any suggestions would be greatly welcome. Sorry for the long post, but I'm just not sure where the error is at this point.

Your code
var data= [DDD_Number,Manager_Review,RID,Services,Dues_List,ID,myrid,Manager_Comments,President_Comments];
var datatosend = JSON.stringify(data);
$.ajax({
type: "GET",
url:'baseupdater-test.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
As i can see you are trying to send the data twice, first through url and second with the ajax data method please fix that i think its a wrong approach to do that you should send it only once.
And moreover you must convert the data into json format to make the ajax request work
and now what's happening is as your data is not in the correct format your code must be stuck at the data in ajax you can see it in console the ajax request would not show you any value passing to another and that is the main reason the Success or Failure are not being show.

Related

refresh multiple classes every n secs from php backend

I have some code in jquery that connects to php and refreshes the class with latest data. This is working ok. However, I need to update 3 classes and when it refreshses the values are empty.
Is there a way I can query db and update 3 classes with fresh data every n sec. Many thanks
js
// Update server with latest actions,destructions and return requests
setInterval(function() {
$.get('/domain/admin/refreshBox.php', function(data) {
$(".actions").text(data);
$(".retrievals").text(data);
$(".returns").text(data);
});
}, 10000);
php
$sql= mysqli_query($conn,"SELECT count(*) as total FROM act WHERE new = '1'");
$rows = mysqli_fetch_assoc($sql);
$num = $rows['total'];
//echo $num;
$ni = $num;
if($ni < 1) {
$ni = '0';
}
echo $ni;
$nisql= mysqli_query($conn,"SELECT count(*) as ni FROM act WHERE activity='New Intake' AND new = '1'");
$niintknum_row = mysqli_fetch_assoc($nisql);
$niintknum = $niintknum_row['ni'];
//echo $num;
$niintk_num = $niintknum;
if($niintk_num < 1) {
$niintk_num = '0';
echo $niintk_num;
$brtvsql= mysqli_query($conn,"SELECT count(*) as rtrv FROM act WHERE activity='Box Retrieval' AND new = '1'");
$brtv_row = mysqli_fetch_assoc($brtvsql);
$brtvnum = $brtv_row['rtrv'];
//echo $num;
$brtv_num = $brtvnum;
if($brtv_num < 1) {
$brtv_num = '0';
echo $brtv_num;
$brtnsql= mysqli_query($conn,"SELECT count(*) as brtn FROM act WHERE activity='Box Return' AND new = '1'");
$brtn_row = mysqli_fetch_assoc($brtnsql);
$brtnnum = $brtn_row['brtn'];
//echo $num;
$brtn_num = $brtnnum;
if($brtn_num < 1) {
$brtn_num = '0';
}
echo $brtn_num;

check duplicate rand function value in database and generate it again

i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
index.php
<html>
<head>
<title>Untitled Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name, course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" onChange="my_validate_func()">
<input type="text" name="phone" id="phone" onChange="my_validate_func()">
<input type="text" name="course" id="course" onChange="my_validate_func()">
<input type="text" name="center" id="center" onChange="my_validate_func()">
<input type="text" name="roll" id="roll" value="">
</form>
</body>
</html>
roll.php
<?php
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
$roll =$branch_name.$name.$course.$year.$rand;
//return $roll;
echo $roll;
}
function isValidRoll($roll) {
mysql_connect("localhost","root","");
mysql_select_db("sigma");
$sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
?>
I suggest to use md5 function and/or time() function such as:
$rand = md5(time() + rand(100000,999999));
Your updated code should be:
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = md5(time() + rand(100000,999999));
$roll = $branch_name.$name.$course.$year.$rand;
echo $roll;
This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.
Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
return $branch_name.$name.$course.$year.$rand;
}
function isValidRoll($roll) {
$result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
or die("Query not valid: " . mysql_error());
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
when ever you save the data of the form store rand function value too means in second time you can retrieve the rand function value and compare with current rand function generating value.

How to add an array from the data attribute and id using javascript and combine them in array php?

I just want to ask if how to merge this two array from all id value and data-rate value on my list order? there is too many ul li, so i need to get them all and store it into array.
this is my code in javascript:
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("ul.reorder-photos-list li").each(function() { x.push($(this).attr('data-rate').substr(9)); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {
ids: " " + h + "",
rate: " " + x + ""
},
success: function(html)
{
window.location.reload();
/*$("#reorder-helper").html( "Reorder Completed - Image reorder have been successfully completed. Please reload the page for testing the reorder." ).removeClass('light_box').addClass('notice notice_success');
$('.reorder_link').html('reorder photos');
$('.reorder_link').attr("id","");*/
}
});
and this is my html code:
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?= $row['rate']?>" data-rate="<?php echo $row['rate']; ?>" >
and then in my order_update.php this is my code.
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n], "data" => $rates[$n]);
$n++;
}
and this is my insert query from orderArray
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$update = mysqli_query($this->connect,"UPDATE `test` SET `order` = $count, `rate`=$array[rate] WHERE id = $array[id]");
$count ++;
}
return true;
}
hope someones helps me. :)thanks in advance!
When setting up your data, you don't need to have multiple loops. You can loop through the data once:
var dataArray = [];
$("ul.reorder-photos-list li").each(function() {
var el = $(this),
input = el.children(':input'); // This gets the input decendent of the li
// When adding one item at a time to an array, array[array.length] = item is better
dataArray[dataArray.length] = {
id: el.attr('id').substr(9),
rate: input.val(),
};
});
$.ajax({
type: "POST",
url: "order_update.php",
data: { items: dataArray }, // items gives the PHP something to use as a key in the POST data
success: function(html) {...}
});
Your PHP will look like this:
// The data passed from the Ajax call is already an array
$itemsArray = $_POST['items'];
// Your function to process the array
function updateOrder($orderArray) {
foreach ($orderArray as $index => $array) {
// $index will already have a count, you need to +1 because it's 0-based
mysqli_query($this->connect, "UPDATE `test` SET `order` = " . ($index + 1) . ", `rate`=" . $array['rate'] . " WHERE id = " . $array['id']);
}
return true;
}
var rates;
$("ul.reorder-photos-list li").each(function() {
rates.id.push($(this).attr('id').substr(9));
rates.rate.push($(this).attr('data-rate').substr(9));
});
This will create your JSON object of h/x pairs.
$.ajax({
type: "POST"
, url: "order_update.php"
, data: { JSON.stringify(rates); }
, success: function(html) {
window.location.reload();
/* $("#reorder-helper").html(
* "Reorder Completed - Image reorder have been successfully completed.
* Please reload the page for testing the reorder."
* ).removeClass('light_box').addClass('notice notice_success');
* $('.reorder_link').html('reorder photos');
* $('.reorder_link').attr("id","");
*/
}
});
This should fix your call to send the correct data.
Your PHP side is going to want to have something similar to this:
if(isset($_POST['rates'])) {
$ratesString = $_POST['rates'];
$rates = json_decode($ratesString);
}
// Do other things with $hx`
Your insert query is off, too. You need to declare each value as a variable or your compiler is going to hate your PHP, too. You also have some unnecessary quotes in your query.
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$rate = $array['rate'];
$id = $array['id'];
mysqli_query($this->connect,"UPDATE test SET order = $count, rate = '$rate' WHERE id = '$id'");
$count ++;
}
return true;
}
For your HTML, I think this is what you were going for, but not sure since it's not really explained all that well...Feel free to comment on your intentions.
<ul>
<?php foreach($orderArray as $array) : ?>
<li id="image_li_<?php echo $array['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?php echo $array['rate']?>" data-rate="<?php echo $array['rate']; ?>" ></li>
<?php endforeach; ?>
</ul>
Hope this helps.
-C§
I got the code now. thanks for your help guys!
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("input").each(function() { x.push($(this).val()); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {ids: " " + h + "",rate: " " + x + ""},
/*data: { items: dataArray },*/
success: function(html)
{
...
}
});
In Php side:
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n] , "rate" => $rates[$n]);
$n++;
}
$db->updateOrder($orderArray);
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
mysqli_query($this->connect, "UPDATE `test` SET `morder` = " . $count . ", `mtoursrate`=" . $array['rate'] . " WHERE id = " . $array['id']);
$count ++;
}
return true;
}

create chart with oracle query

i am trying to create a chart pie with a query from oracle database.
i have already connect to the data base and echo the results,but i cant create a chart.any suggestion about this?
<?php
$tns = "
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = xxx.xxxx.xxx.xxx)(PORT = xxxx))
)
(CONNECT_DATA =
(SERVICE_NAME = XE)
)
)
";
$db_username = "xxx";
$db_password = "xxxxR";
try{
$conn = new PDO("oci:xxxx=".$tns,$db_username,$db_password);
}catch(PDOException $e){
echo ($e->getMessage());
}
if (!$conn) {
$m = oci_error();
echo $m['message'], "\n";
exit;
}
else {
echo "Connected to Oracle!";
}
$query = "SELECT T71.C_C1003000015, COUNT (T71.C1)
FROM ICT_DATABASE.T71 T71
WHERE (T71.C_C1003000015 NOT IN (exelllllllllxx.xxxx.xxx'))
AND trunc(T71.ARRIVAL_DATE) = trunc(sysdate)
GROUP BY T71.C_C1003000015";
$stmt = $conn->prepare($query);
if ($stmt->execute()) {
echo "<h4>$query</h4>";
echo "<pre>";
while ($row = $stmt->fetch()) {
print_r($row);
}
echo "</pre>";
}
?>
that code is working and export data how can i create a chart now?
ok, here goes.
you need to add Google's scripts to your page.
<script src="https://www.google.com/jsapi"></script>
Add this div where you want the chart...
<div id="piechart" style="width: 900px; height: 500px;"></div>
then add this JavaScript, assuming you leave the output in the <pre> element
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var googleArray = [];
googleArray.push(['Department', 'Value']);
var testRow = document.getElementsByTagName('PRE')[0].innerHTML;
var testArr = testRow.split('IT-EXT-COSMOTE-');
var deptSplit;
for (var i = 0; i < testArr.length; i++) {
if (testArr[i] !== '') {
deptSplit = testArr[i].split(' - ');
googleArray.push([deptSplit[0], Number(deptSplit[1])]);
}
}
var dataTable = new google.visualization.arrayToDataTable(googleArray, false);
var chartOptions = {title: 'Department Totals'};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(dataTable, chartOptions);
}
let me know if you need further help...

Magento Images switcher for custom options

I have created a custom options image switcher for Magento, script compares value from options in drop-down with all image names related to product, and finds the most similar one, you can see an example here
The problem is how to add the "selected" option image to the cart, or better to say how to apply that image instead of the default thumbnail in the cart?
anyway here is the complete code - maybe someone can even find this part useful :)
<?php
// load all images related to product
$product = $this->getProduct();
$galleryData = $product->getData('media_gallery');
$images_array = array();
foreach ($galleryData['images'] as $image) {
array_push($images_array, $image['file']);
}?>
<?php
$colour_select_id = '';
$custom_options_arr = array();
foreach ($_options as $_option) {
if ($_option->getTitle() == 'Helmet Color/Design' || $_option->getTitle() == 'Color') {
$colour_select_id = 'select_' . $_option->getId();
$values = $_option->getValues();
foreach ($values as $value) {
$current_option = ($value->getData());
$custom_options_arr[$current_option['option_type_id']] = $current_option['title'];
}
}
}
// $custom_options_arr now holds key=>value pairs of option_type_id => title
$custom_images_to_output = array();
foreach ($custom_options_arr as $key => $value) {
$best_match = $images_array[0];
for ($i = 1; $i < count($images_array); $i++) {
if (similar_text(strtoupper($images_array[$i]), strtoupper($value)) > similar_text(strtoupper($best_match), strtoupper($value))) {
$best_match = $images_array[$i];
}
}
$custom_images_to_output[$key] = $best_match;
}
$base_url = Mage::getBaseUrl('media') . 'catalog/product';
?>
<?php if ($colour_select_id) { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
var opt_object = <?php echo json_encode($custom_images_to_output); ?>;
var base_path = '<?= $base_url;?>';
jQuery("#<?= $colour_select_id ?>").change(function() {
var optionValue = jQuery(this).attr('value');
if (optionValue) {
var optionValueText = jQuery.trim(jQuery('#<?= $colour_select_id ?> :selected').text());
if (opt_object.hasOwnProperty(optionValue)) {
optionValueText = opt_object[optionValue];
}
jQuery("#image").fadeOut(function() {
jQuery(this).load(function() {
jQuery(this).fadeIn(); });
jQuery(this).attr("src", base_path + optionValueText);
jQuery('#image-zoom').attr("href", base_path + optionValueText);
});
}
});
});
</script>

Categories

Resources