Convering json data to Java script array - javascript

i have code above which gets data from a database and then place in in json form to make it readable in java script.
the results of the echo is
"FIAT":["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"],
"Land Rover":["Defender","Discovery","Discovery 3","Discovery 4"]
I would like the data to be converted in such a way the i can reference it in this form Var Brand=array ();
Brand["FIAT"]=["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"];
Brand["Land Rover"]=["Defender","Discovery","Discovery 3","Discovery 4"];
in java script. Does Any one know how i can do this.
$query = mysqli_query($conn,"SELECT * FROM car_models");
// Loop the DB result
while(($result = mysqli_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['Brand'], $data)){
// Create array for current user
$data[$result['Brand']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['Brand']][] = $result['Model'];
}
//json data
json_encode($data);

I found the solution. Simply added the json object in a variable and now am able to get the echo it to the console
`
//json data
var brandAvailable =
console.log(brandAvailable);
"`

Related

JSON from array not being parsed correctly

I'm sending my mysql result to an associative array and then encoding with JSON
$showDisplayResult = $mysqlConn->query($getDisplayPage);
while($row=mysqli_fetch_assoc($showDisplayResult))
{
$rows[] = $row;
}
$showDisplays = json_encode($rows);
ANd in my main page I'm using javascript to grab this, parse it and append the correct variables into my URL. The functionality seems to work but it only shows undefined as the variables in the URL.
Here's the javascript:
<script type="text/javascript">
let obj = <?php echo $showDisplays; ?>;
//obj = JSON.parse(obj);
let params = new URL(document.location).searchParams;
params.set("pageID", obj.pageID);
params.set("display", obj.display_id);
let url = window.location.href.split('?')[0];
let nextURL = url + "?" + params.toString();
window.setTimeout(function () {
window.location.href = nextURL;
}, obj.duration * 1000);
console.log(obj);
</script>
So my URL is now showDisplay.php?display=undefined&pageID=undefined
How can I get this to parse the JSON correctly?
UPDATE:
If I echo $showDisplays, this is the JSON that prints:
[{"pageID":"104","page_type_id":"1","display_id":"3","slide_order":null,"duration":"56","active":"1","background_img":null,"panel_id":"96","panel_type_id":"1","page_id":"104","cont_id":"148","contID":"148","content":"\r\n\r\n\r\n<\/head>\r\n\r\nThis is full content<\/p>\r\n<\/body>\r\n<\/html>"},{"pageID":"116","page_type_id":"1","display_id":"3","slide_order":null,"duration":"54","active":"1","background_img":"images\/BG_spring.svg","panel_id":"113","panel_type_id":"1","page_id":"116","cont_id":"165","contID":"165","content":"\r\n\r\n\r\n<\/head>\r\n\r\nThis background should be green<\/p>\r\n<\/body>\r\n<\/html>"}]
So on page load i want the url to have display=3&pageID=104 then after 56 seconds (its duration) it should refresh and th URL should be display=3&pageID=116 for 54 seconds, and then keep the loop
If I read the code correctly, $showDisplays is an array of row objects, not a single row object. The JavaScript, however, tries to access properties of a row object as if they were on their containing array, obj.
If you want to access properties of the first row object in the array, you can do this with:
params.set("pageID", obj[0].pageID);
params.set("display", obj[0].display_id);
The next row object would be at the next index, obj[1]. So, in order to get all of the row objects in sequence, you would loop over them.

How to solve "notice array to string conversion in C" error in php and javascript?

So I am trying to send the "id" of a selected row in datatable in javascript to a php page so I could delete it from database.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0] });
the variable "ids" is sent by post method
$.post( "deleterow.php", { v1: ids });
but it didn't worked so i try to see the response from post method and it says
"notice array to string conversion in C on line ... "
the line is of php page where i am writing the delete query
$id = $_POST["v1"];
$query = "DELETE FROM `package` WHERE `id` = '$id'";
The whole php page works fine when trying with other values.
Because you send an array here:
$.post( "deleterow.php", { v1: ids });
so v1 contains an array of elements. But in your php code you treat it as a single element:
$id = $_POST["v1"];
Hence the notice array to string conversion.
If you send an array of elements, you have to get it as an array and treat is as an array. To create a correct SQL string you should append each ID, like this:
$ids = json_decode($_POST["v1"]);
$query = "DELETE FROM `package` WHERE";
$first = true;
foreach ($ids as $id) {
if ($first) {
$first = false;
} else {
$query += " OR";
}
$query += " `id` = '$id'"
}
This way you loop the array and append a id = ID for each array element.
Now, this is important, this code is prone to SQL injection, a really bad security problem. Read this to get more info about this: How can I prevent SQL injection in PHP?

Send multiple base64 to php

I want to send multiple base64 strings via jquery's $post(). The number of strings are not always the same. How can I do this and fetch it in php?
Is it a good option to have all strings in an array and add them in $post()?
var items = [
"data:image/png;base64,i.....",
"data:image/png;base64,i....",
"data:image/png;base64,i...."
] //the number od these strings varies on each post
$.post("../send.php",
{
for(i=0;i<21;i++){
'item'+i: items[i]
}
},
)
php:
if($_POST['item1']){
$item1 = $_POST['item1'];
}
I would go with the following steps:
1) Create a form with the input fields that contain all these base64 strings. (the form and all its fields can all be hidden in html)
2) In my form all the input text fields can have the same name like in this case
<input type="text" name="text1[]">
2) When I need to add a new string, I shall add an input field in that form by using jQuery.append()
3) in my jquery post i will set the data to
$.post('../send.php',$('#myFormId').serialize(),function(){
// what i want to do with the response
})
4) in my php page I can easily loop over
foreach($_POST['item1'] as $item){
// do what you want with data
}
that's it!
Try this
JS :
$.post("../send.php",{items:items}); //send to server
PHP:
$_POST['items'] // catch in server
I would create a regular array of strings, and then iterate to the array of strings and add them as properties of an object using a for loop. Here's an example.
var items = []; // Empty array.
items.push(item1, item2, item3); // Add Base64 strings.
var postdata = {}; // An object for our postdata.
// Iterate through the array and add items as properties to the object.
for (var _i = 0, _j = items.length; _i < _j; _i++) {
postdata['item_'+_i] = items[_i]; }
// POST the object to the PHP file.
$.post("../send.php", postdata);
Then, in PHP, you get $_POST['item_1'] until $_POST['item_n'] from jQuery. :)
UPDATE
You can process the postdata in PHP like below.
<?php
foreach($_POST as $k => $v) {
// Do things for each item POSTED.
// This will end after the last POSTed item is reached.
// $k is the 'key', as in what's inside the square brackets of $_POST[]
// $v is the 'value', as in $_POST[key] = "THIS STUFF";
}
?>
Hope that was helpful!

Laravel: upload multiple rows created from arrays

I'm building an application with Laravel which communicates with an OpenCPU server to perform some calculations. The OpenCPU server returns data in JSON format, which I then process to pull out the relevant information. This data returns a sku, retailer, date and sales. These are then posted to a controller using AJAX. Within this controller I then want to upload this data into the database by creating a new array of data to upload in one go. Each row should have a sku, retailer, date and sales. The date field in the database is called date, but called obs in the code.
OpenCPU returns JSON which is the parsed to a Javascript object using
var data = JSON.parse(output);
After logging to the Javascript console I get an array of the correct length, with the sales numbers.
The data is then sent to a Laravel controller via AJAX
$('#save').click(function(){
var id = $('#filter option:selected').text();
var json = $.ajax({
url: 'sales/' + id + '/update',
type: 'POST',
data: {
'sku': $('#sku').text(),
'retailer': $('#retailer').text(),
'obs': data.OBS,
'sales': data.Sales,
},
async: false
}).responseText;
var message = JSON.parse(json);
$('.flash').html(message).fadeIn(300).delay(2500).fadeOut(300);
});
In Laravel I then try to store the data in a MySQL database using the following
$sku = Input::get('sku');
$retailer = Input::get('retailer');
$obs = Input::get('obs');
$sales = Input::get('sales');
foreach($obs as $key => $n ){
$arrayData[] = array(
'sku' => $sku,
'retailer' => $retailer,
'date' => $obs[$key]
'sales' => $sales[$key]
);
}
Chart::create($arrayData);
However the above code doesn't appear to work. The following code will create the correct number of rows in the database with the sku and retailer populated, but the sales figure is just the loop number, rather than the number of sales
$sku = Input::get('sku');
$retailer = Input::get('retailer');
$dates = Input::get('obs');
$sales= Input::get('sales');
foreach(range(1, count($dates)) as $key){
DB::table('charts')->insert(
[
'sku' => $sku,
'retailer' => $retailer,
'date' => DateTime($obs[$key]),
'sales' => $sales[$key]
]
);
}
Given that the sku and retailer are a single input and repeated, I expect it's either an issue with passing the array to Laravel or the way in which I'm trying to access the elements in the 'obs' and 'sales' array
It looks like you have the right steps, get the inputs:
$sku = Input::get('sku');
$retailer = Input::get('retailer');
$dates = Input::get('obs');
$sales= Input::get('sales');
Buy now you try to forcibly insert them into the database. Why not use eloquent for database insertion: (Keep in mind you'd need to have a model for the charts table called Chart.php)
$chart = new Chart;
$chart->sku = $sku;
$chart->retailer = $retailer;
$chart->dates = $dates;
$chart->save();
That being said, I do realize that you're trying to pass arrays to the database, so that might take some experimentation. If you can't figure out what's (attempting) being passed to the database, you can always use:
die($variable);
To check what's up. Good luck!

Database string value to PHP array to be used in Javascript

I need to store values into a Wordpress database and the use the value in a Google Chart.
The questions are:
1. What format do I use to store it into the database?
Currently I am using WP-TYPES and adding the array as follows to a Multi Line Box:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
This is what it needs to output in the Javascript for the chart.
Convert the String to a array in PHP (Not doing it correctly)
I retrieve the data with:
$graphdata = types_render_field("graph-data", array("output" => "raw","separator"=>";"));
This gives me a string value.
Then I add it to an array:
$thechartcontent[$i] = [
"name" => get_the_title(),
"chartheaders" => array($graphdata),
];
In JavaScipt:
I set the PHP Array to Java
var chart1 = <?php echo json_encode($thechartcontent[0]); ?>;
Then I get the data from the array to a var:
var chartheaders1 = chart1['chartheaders'];
This is where I get stuck. The value that I get is a string. It needs to show exactly this:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
for it to work.
Any help please.
Well, it will not be exacly like you want since it's JSON encoded in JSON format. This might be useful. Or you can convert object into array in JS.
I suspect that what you are outputting is an array containing a string, which is not what you want. You must split $graphdata into an array of arrays containing your data before adding it to $thechartcontent:
$graphdata = substr($graphdata, 1, strlen($graphdata) - 1); // trim the opening and closing brackets
$graphdata = explode('],[', $graphdata); // split $graphdata into an array of strings
foreach($graphdata as &$row) {
$row = explode(',', $row); // split the row into an array
}
$thechartcontent[$i] = array(
'name' => get_the_title(),
'chartheaders' => $graphdata
);
When you json encode the data, you should use the JSON_NUMERIC_CHECK constant, so your numbers don't get quoted as strings:
var chart1 = <?php echo json_encode($thechartcontent[0], JSON_NUMERIC_CHECK); ?>;

Categories