using items from php array to change css - javascript

UPDATE: I should add the overall goal is to change the background of a cell based on the 1st query and the border based on the second query then when the beacon stops being pulled in on the 1st query the background goes back to grey
I am trying to use data pulled in from mysql to change the background of table cells, after some modification to my code it no longer works all though the data is still being passed through via Ajax using code below:
before the modification i only used 1 array but since adding 2 arrays as an outer array i can't get it to work, also i i add an item to the console log i just get undefined e.g. item.beacon would normally return a number instead it returns undefined in the console log although it is in the array.
data
I have included the data as a picture to save using to much text
html
<script>
$(document).ready(function() {
for (var i = 0; i < 12; i++) {
var row = $('<tr>').appendTo("#zoning tbody");
for (var j = 1; j < 11; j++) {
$(`<td class='${i * 10 + j}'>${i * 10 + j}</td>`).appendTo(row);
}
}
$.get('php/test.php', function(response) {
console.log(response);
var row;
$.each(response, function(index, item) {
console.log(item);
$(`td.${beacon}`).css('background-color', location).toggleClass('coloured');
});
});
function updateTable() {
//console.log('function called');
$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
$.get('php/test.php', function(response) {
$.each(response, function(index, item) {
console.log(beacon);
//$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
$(`td.${beacon}`).css('background-color', location).toggleClass('coloured');
});
});
}
var updateTableInterval = setInterval(updateTable, 5000);
});
</script>
php
# header('Content-Type: applicaton/json');
$sql1 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result1 = $conn->query($sql1);
$rows1 = $result1->fetch_all(MYSQLI_ASSOC);
$sql2 = "SELECT beacon,location,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon";
$result2 = $conn->query($sql2);
$rows2 = $result2->fetch_all(MYSQLI_ASSOC);
$result = array(
'query1' => $rows1,
'query2' => $rows2,
);
echo json_encode($result);
$conn->close();

Here's example code that should solve this:
$.getJSON('php/test.php', function(response) {
$.each(response.query1, function(index, item) {
console.log(item);
// use first array's item.beacon, item.location, etc.
});
$.each(response.query2, function(index, item) {
console.log(item);
// use second array's item.beacon, item.location, etc.
});
});

Related

Can't send data to a php script via $.post()

I'm implementing a cart on my website. It works this way: On catalog page there's four products and each has its own "Add to cart" button. Every button has its own onClick attribute which is set to addToCart() function in mu JS file. User can click on the button, and when he does so, js script is initiated. It writes product's id and increase its amount in the sessionStorage in foramt like this: "1=1", or "5=2" where the frist number is index, i.e. product's id, and second one is amount of the product.
And the next thing that I got to do is transfer info about product id and its amount to the PHP's session. And for this purpose I'm using jQuery function post(). But it doesn't work for some reason
add_to_cart.js:
function addToCart(event) {
const PRODUCT_ON_PAGE = 4;
event = event || window.event;
const productId = Number(event.currentTarget.id);
const pageId = Number(document.querySelector(".page-num-highlight").textContent);
let index = Number((pageId - 1) * PRODUCT_ON_PAGE + productId);
let item;
const parseSign = "=";
let quantity = "";
item = sessionStorage.getItem(index);
if (item) {
for (let i = 0; i < item.length; i++) {
if (item[i] == parseSign) {
for (let j = i + 1; j < item.length; j++)
quantity += item[j];
quantity = Number(quantity);
quantity++;
quantity = String(quantity);
item = index + "=" + quantity;
sessionStorage.setItem(index, item);
}
}
}
else {
sessionStorage.setItem(index, String(index) + "=1");
}
$(() => {
let productIndex = index;
let productValue = quantity;
$.post("updateSession.php", {
index: productIndex,
value: productValue
});
})
}
As you can see I process the corresponding index and value of product on which addToCart() was triggered. Index of the product is index variable, amount of product is quantity variable.
And the next step is to send index and quantity variables to php processing script called updateSession.php in order to create/update info of product in PHP's session.
updateSession.php:
<?php
if (isset($_POST["index"]) && isset($_POST["value"])) {
$index = $_POST["index"];
$value = $_POST["value"];
$_SESSION[$index] = $value;
}
UPD1 jQuery part (unwrapped):
let productIndex = index;
let productValue = quantity;
$.post("updateSession.php", {
index: productIndex,
value: productValue
});
UPD2:
**What is not working**: when I go to cart.php var_dump() says that $_SESSION array is empty(). And I don't know where is problem: in add_to_cart.js jQuery part or in updateSession.php
UPD3:
In my console log there's two errors when addToCart() is initiated by clicking "Add to cart" button.
These 2 errors say that post() is not a function. First says jQuery.Deferred exception and second says Uncaught TypeError
Using id of object as key in JS is not a really good practice because JS reaffect key to not have lost indexes. Prefer to use full object with id key setted to your id object.
<button onclick="addToCart(6)">Add to cart</button>
In your HTML button, pass productId as element, it will be easier to use
function addToCart(productId) {
// Search if your object is already in your cart
let cartProductIndex = yourCart.map(p=>p.id).indexOf(productId)
if (cartProductIndex !== -1) { // If you have found it
cart[cartProductIndex].quantity++;
} else { // If you have not found it
// Construct your object like this
let newProduct = {
id: productId,
quantity: 1
}
// Then add it to your cart
cart.push(newProduct)
}
}
// Your cart will looks like this :
[
{
id: 3,
quantity: 1
},
{
id: 6,
quantity: 12
}
]
// Finally, you can send your post request
let datas = {
cart: cart
}
$.post("updateSession.php", datas)
// Your php file
$data = json_decode($_POST['cart']);
So your $data variable will looks like this :
$data = [
[
"id" => 3,
"quantity" => 1
],
[
"id" => 6,
"quantity" => 12
]
];

make an array with the values of similar keys from JSON array

I have an array in JSON array format. I want to extract the values of common keys and make a new array with this.
I've tried this
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
where sale_date and total are the keys.
but this code returned an array of undefined objects.
my array named data looks like
{"sale_date":"2017-12-26 11:05:05","total":"500"}{"sale_date":"2017-12-26 11:05:18","total":"500"}
I'm expecting two arrays date[2017-12-26 11:05:05, 2017-12-26 11:05:18 ] and amt[500, 500]
I'm getting data as a ajax response From the code below.
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$db_data = $row;
print json_encode($db_data);
}
}
And this how my ajax request looks like
$(document).ready(function(){
$.post("ajax-req-handler.php",
{
key: "draw-line-chart"
},
function( data ){
console.log(data);
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
});
});
var data = [
{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}
];
var date = [];
var amt = [];
for(var i in data){
console.log(i);
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
PHP Code :-
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
$data = array();
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$db_data[] = $row;
}
}
echo json_encode($db_data);
Ajax Request :-
$(document).ready(function(){
$.post("ajax-req-handler.php",
{
key: "draw-line-chart"
},
function( data ){
console.log(data);
data = JSON.parse(data);
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
});
});
You need to encapsulate your object between array
var data = [{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}]
var date = [];
var amt = [];
for(var i=0;i<data.length;i++){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
This is not a JavaScript but PHP issue.... you are sending invalid JSON. The following:
{"sale_date":"2017-12-26 11:05:05","total":"500"}{"sale_date":"2017-12-26 11:05:18","total":"500"}
Should actually look like:
[{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}]
You need to change your PHP code to this:
// Add content type so that jQuery knows you're sending JSON
header("Content-Type: application/json");
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
$db_data = array();
while ($row = $result->fetch_assoc()) {
$db_data[] = $row;
}
echo json_encode($db_data);
Sending Content-Type header should be enough but you should also change your jQuery code just to be sure:
$(document).ready(function() {
$.post("ajax-req-handler.php", {
key: "draw-line-chart"
}, function(data) {
console.log(data);
var date = [];
var amt = [];
for (var i in data) {
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
}, "json");
// the 4th parameter is dataType set to json
});
//Hope this will be of help.
var data = [ {"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"} ];
var date = amt = [];
X = 0;
while (x < data.length) {
date.push(data[x].sale_date);
amt.push(data[x].total);
x++;
};
console.log(date);
console.log(amt);
Explanation:
line 1 is the array of objects which represent the data u are pulling from ur json data.
Line 2 is the declaration of the two variable arrays which is assigned to and empty array. So, I used the short form of declaring multi-variable on the same line of statement.
Line 3 is the initialization of the counter "x" that will help break the While Loop once the it counts to the last Object in the array "data".
Line 4. Then the While Loop which keep iterating through the array " data". The conditional statement there always check if the counter "x" is < (less than) the length of the array In each iteration it.
Line 5. In the While Loop block code using the counter "x" as index of the array to access the property "sale_date" of the object in that array index and push it to the array "date" (I.e adding it at the end of the array "date").
Line 6. The same as line 5, accessing the property total in that index of the array " data" and push it to array "amt".
Line 7 increment the counter " x" by 1 and assign it to back to x which is used to reevaluate the While Loop.
Line 8 & 9 is just a console log that displays what's in date and amt respectively.
Thanks
Hope this makes sense to u... Please, Let me know your feedback.

How to iterate through javascript object and run a function on each value

I am new to JS.
I set up a Saved Search in NetSuite that gives us the image fields (containing URLs) of our items. I am now setting up a script in NS which tests these fields to see what item fields return 404 (i.e. need to be fixed).
My question is, how to set up function imageURLValidator to iterate through the field values of function searchItems?
Below is my start to the process but obviously has much incorrect syntax.
function imageURLValidator() {
var searchResults = searchItems('inventoryitem','customsearch529');
var url = '';
var item = '';
var field = '';
//insert loop here to iterate over items in searchResults array
//loop through items
for (var i = 0, i > searchResults[inventoryObject].length, i++) {
item = searchResults.[inventoryObject].[i];
//loop through fields in item
for (var f = 2, f > item.length, f++) {
field = item[f];
//check URL via item field's value
var code = checkURL(item[field].getvalue([field]));
//generate error based on code variable
createErrorRecord(code,item,field)
}
}
}
function searchItems(type, searchid) {
//defining some useful variables that we will use later
var inventoryArray = [];
var count = 0;
//loading the saved search, replace the id with the id of the search you would like to use
var inventoryItemSearch = nlapiLoadSearch(type, searchid);
//run the search
var inventoryItemResults = inventoryItemSearch.runSearch();
//returns a js array of the various columns specified in the saved search
var columns = inventoryItemResults.getColumns();
//use a do...while loop to iterate through all of the search results and read what we need into one single js object
do {
//remember the first time through the loop count starts at 0
var results = inventoryItemResults.getResults(count, count + 1000.0);
//we will now increment the count variable by the number of results, it is now no longer 0 but (assuming there are more than 1000 total results) will be 1000
count = count + results.length;
//now for each item row that we are on we will loop through the columns and copy them to the inventoryObject js object
for (var i=0; i<results.length; i++){
var inventoryObject = {};
for (var j=0; j<columns.length; j++){
inventoryObject[columns[j].getLabel()] = results[i].getValue(columns[j]);
}
//then we add the inventoryObject to the overall list of inventory items, called inventoryArray
inventoryArray.push(inventoryObject);
}
//we do all of this so long as the while condition is true. Here we are assuming that if the [number of results]/1000 has no remainder then there are no more results
} while (results.length != 0 && count != 0 && count % 1000 == 0);
return inventoryArray;
}
function checkURL(url) {
var response = nlapiRequestURL(url);
var code = response.getCode();
return code;
}
function createErrorRecord(code,item,field) {
if (code == 404){
//create error record
var errorRecord = nlapiCreateRecord('customrecord_item_url_error');
errorRecord.setFieldValue('custrecord_url_error_item', item);
errorRecord.setFieldValue('custrecord_url_error_image_field', field);
}
}
Here I can see searchResults variable will be empty while looping. As your call to searchItems function is async. Which will take some time to execute because I guess it will fetch data from API. By the time it returns value, your loop also would have bee executed. You can test this by putting an alert(searchResults.length) or console.log(searchResults.length). For that you need to use callback function
Also even if you get the results in searchResults. The loop you are doing is wrong. The array you will get is like [{},{},{}] i.e. array of objects.
To access you'll need
for (var i = 0, i > searchResults.length, i++) {
var inventoryObject = searchResults[i] // your inventoryObject
for(var key in inventoryObject){
item = inventoryObject[key]; // here you will get each item from inventoryObject
//loop through fields in item
for (var f = 2, f > item.length, f++) {
field = item[f];
//check URL via item field's value
var code = checkURL(item[field].getvalue([field]));
//generate error based on code variable
createErrorRecord(code,item,field)
}
}
}
And yes welcome to Javascript

How to stop innerHtml repeating itself over and over again in a table?

I have made an array with objects that get there info from three different user variables, however on one of these there are many sub variables that i don't want it to repeat itself every time the user presses the select button(which updates the table) instead i want it to just add onto (or take away) from the sections that it already has in the table. thanks(if you need the variable code let me know) I have been trying to solve thi for a while now! please help!!
//creating array
var gProducts = new Array();
var gTotalCost = 0;
// Adding Products to array gProducts
function addProduct
{
var product = new Object();
product.name = name;
product.cost = cost;
gProducts.push(product);
gTotalCost += parseInt(cost)
}
//Getting products from array, use of for in loop setting new table rows in blank var for each array item
function renderProducts()
{
var HTMLadd = ""
for (var i in gProducts)
{
if( gProducts[i].cost > 0){
HTMLadd = HTMLadd +
"<tr>"+
"<td class='tableSettings00' id=tableRow2 >" + gProducts[i].name +
"</td>"+
"<td class='tableSettings'>€<span id=tableRow2part2>" + gProducts[i].cost +
"</span></td>"+
"</tr>";
}
else
{
}
}
document.getElementById('tableRow').innerHTML = HTMLadd;
}
You're using a for in loop, when you probably wanted just a for loop.
Change this line to
for (var i in gProducts)
to
for (var i = 0; i < gProducts.length; i++)
With a for/in loop, the variable i will be an object, and not an integer.

JQuery Get total item price from EACH cell & Display it, Working, but not correctly

I have this javascript, jquery function, (below)
It gets the text inside each table cell (of class="total_item_price") of a table.
It puts it into an array (prices_array)
Adds up prices_array and formats them to 2 Decimal Places.
Then outputs it into the total_order_price, or returns it if do_request isset.
Problem: I have a function that deletes a item from the basket, then calls this function (getTotalPrice) to update the prices field. This part does not work correctly, and is not producing the correct price.
Basically, I need this function, to:
Get the price(s) of (.total_item_price) which is inside a cell.
Get the shipping price (.shipping_price) + Add them all up
Display it inside cell (.total_order_price)
Then When I call my delete function, I can call ^this^ function to hopefully update the price correctly.
I also call this getTotalPrice function on DOM Ready to update the prices, so its important it works correctly, It also has to work when I call my delete function (below).
I have a jsfiddle but it doesn't work, but this code does work on my localhost. I had to compact it for jsfiddle, and its broken somewhere. Feel free to edit how you want.
Here Is the Code(!):
This function gets the total price and displays it.
function getTotalPrice(do_request)
{
var prices_array = new Array(); // Where our prices are held
// For each .total_item_price - a <td> within my table.
$(".total_item_price").each(function(e){
var text = $(this).text(); // Get the value
var prices = text.substring(1, text.length); // Format it into a string
prices_array.push(prices); // Push it onto our array
});
var result = eval(0);
// Add up our array
for(i = 0; i < prices_array.length; i++)
{
temp = eval(prices_array[i]);
result += temp;
}
// Round up our result to 2 Decimal Places
result = Math.round(result*100)/100;
// Output/Return our result
if (do_request == null)
{
// We want to add our shipping Price and Display the total
// Get the Shipping Price
var shipping_price = $(".shipping_price").html();
shipping_price = shipping_price.substring(1, shipping_price.length);
// Add em
result += eval(shipping_price);
// Round our result to 2 decimal places
var result=Math.round(result*100)/100;
// Update & Display the Result
$('.total_order_price').html("<b>£" + result + "</b>");
}
else
{
// Otherwise we just want the total price and return it.
return result;
}
}
This is the function I made to delete a row from the table and update the prices.
// Delete Item from Basket, Run on click of delete button
function delete_item(e)
{
doIt = confirm('Delete Item from Basket?\r\n You can not undo this action.');
if(doIt)
{
// Get our basket
var basket_md5 = $(e).parent().find("input[name='basket_md5']").val();
var url = "<?php echo SERVER_URL."shop/basket"; ?>";
// Post to basket
$.post(url, { "do": "delete_item","basket_md5": basket_md5});
// Delete Row from Table
// Row Scope
var row = $(e).parent().parent();
// Effect & Remove from DOM
$(row).fadeOut(1000, function(){
$(this).remove();
});
// Update the Prices (again)
//tprice = getTotalPrice("return");
//$('.total_order_price').html("<b>£" + tprice + "</b>");
getTotalPrice();
}
}
In function delete_item(e) move 'getTotalPrice(); here:
$(row).fadeOut(1000, function(){
$(this).remove();
// Update the Prices (again)
//tprice = getTotalPrice("return");
//$('.total_order_price').html("<b>£" + tprice + "</b>");
getTotalPrice();
});

Categories

Resources