file_put_content array structure does not work - javascript

I'm trying to move an array into a .json file and then simply console.log it. I think its my structure in my array that is messing it up.
$jsonarray = array('Symbol'=>[$symbol],'PERatio'=>[$peratio], 'MarketCap'=>[$marketcap], 'Dividend'=>[$dividend], 'ROE'=>[$roe], 'DebtToEbitda'=>[$debttoebitda], 'EbitdaGrowth' =>[$ebitdagrowth], 'RevenueGrowth' =>[$revenuegrowth],);
file_put_contents('Stockdata1.json', json_encode($jsonarray), FILE_APPEND);
This is how it looks like in the .json file.
{"Symbol":["A"],"PERatio":["31.55"],"MarketCap":["19722.500"],"Dividend":["0.87"],"ROE":["14.48"],"DebtToEbitda":["2.04"],"EbitdaGrowth":["5.40"],"RevenueGrowth":["4.20"]}{"Symbol":["AA"],"PERatio":["44.45"],"MarketCap":["6960.660"],"Dividend":["0.00"],"ROE":["2.33"],"DebtToEbitda":["0.95"],"EbitdaGrowth":["0.00"],"RevenueGrowth":["0.00"]}{"Symbol":["AAC"],"PERatio":["0.00"],"MarketCap":["217.730"],"Dividend":["0.00"],"ROE":["-2.76"],"DebtToEbitda":["8.71"],"EbitdaGrowth":["22.30"],"RevenueGrowth":["15.00"]}{"Symbol":["AAP"],"PERatio":["18.68"],"MarketCap":["6888.440"],"Dividend":["0.26"],"ROE":["12.69"],"DebtToEbitda":["1.17"],"EbitdaGrowth":["6.50"],"RevenueGrowth":["13.60"]}
when i then try to console.log in js like this
$.getJSON('Stockdata1.json', function (data) {
console.log(data);
});
nothing comes out... Hope someone can see my mistake..

As soon as you FILE_APPEND the second array, you're invalidating the JSON in the file. The file will contain two JSON objects without a separator (i.e. (abbreviated for clarity) {"Symbol":["A"]}{"Symbol":["B"]}).
Instead, what you need for valid JSON, is to have the file contain a JSON array of all objects: [{"Symbol":["A"]},{"Symbol":["B"]}]. The only way to do that, is to not use file_put_contents() with the FILE_APPEND flag, but to load the file as JSON, add the new object, and write the full JSON back to the file.
My suggestion is to change your code to something along these lines:
$jsonarray = array('Symbol'=>[$symbol],'PERatio'=>[$peratio], 'MarketCap'=>[$marketcap], 'Dividend'=>[$dividend], 'ROE'=>[$roe], 'DebtToEbitda'=>[$debttoebitda], 'EbitdaGrowth' =>[$ebitdagrowth], 'RevenueGrowth' =>[$revenuegrowth],);
$data = json_decode(file_get_contents('Stockdata1.json'));
if (!$data) {
// file is empty or does not contain valid JSON
$data = [];
} elseif (is_object($data)) {
// file only contains a JSON object, not a JSON array
$data = [ $data ];
}
$data[] = $jsonarray;
file_put_contents('Stockdata1.json', json_encode($data));

Related

How to retrieve content in PHP from external JavaScript

I have an external JavaScript file, I would like to display array content in my PHP page. How can I display the content by loop. I tried to display the content using following code. But Failed.
<?php
ini_set('allow_url_fopen', 'On');
$feed = file_get_contents("https://example.com/media-list.js");
$array = json_decode($json);
var_dump($array);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
?>
media-list.js content
var contents = {
"0W7EHsR8":{
"attachmentCode":"0W7EHsR8",
"title":"title1",
},
"vciym7Zb4":{
"attachmentCode":"vciym7Zb4",
"title":"title2",
},
"XlKBM6":{
"attachmentCode":"XlKBM6",
"title":"Title3",
}
};
I would like to display content like
Title is "title1" .
Title is "title2".
You are trying to use json_decode() on a Javascript Array. JSON and Javascript are two different things.
You need to convert your contents array to JSON, save it in a different file (contents.json for example) and load that file with file_get_contents.
If you need to do this only once you can do something like
var contents = {
"0W7EHsR8":{
"attachmentCode":"0W7EHsR8",
"title":"title1",
},
"vciym7Zb4":{
"attachmentCode":"vciym7Zb4",
"title":"title2",
},
"XlKBM6":{
"attachmentCode":"XlKBM6",
"title":"Title3",
}
};
console.log(JSON.stringify(contents));
and copy the result from the console (click CTRL+Shift+I to open it).
JSON.stringify() takes a Javascript array and turns it into a JSON string.
for this small array the JSON equivalent is
{"0W7EHsR8":{"attachmentCode":"0W7EHsR8","title":"title1"},"vciym7Zb4":{"attachmentCode":"vciym7Zb4","title":"title2"},"XlKBM6":{"attachmentCode":"XlKBM6","title":"Title3"}}
If you intend on making this dynamic (say, loading all attachemnts from a database) you can create a php file that loads that data into an array and returns it into proper JSON using json_encode(). Loading that file with file_get_contents and using json_decode like you are doing now should do the trick.

Passing php array to javascript then accessing values by key

I'm using $.post to return an array from a separate php file, and trying to access the values of the array in javascript by the keys, but am having trouble doing so.
Here's the post code:
$(document).ready(function(){
var limRefresh = setInterval(refreshLIM, 10000);
var dbAction = "feedRefresh";
var newestRow = <?php echo $newestRow ?>;
$.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){
console.log(status);
console.log(newArr['status']);
console.log(newArr.status);
console.log(newArr[0]);
});
});
Here's the excerpt of how the response is being formatted in the external php file:
echo json_encode(array("status" => "success","actId" => $newActId));
And here's the respective console logs (just trying different options):
{"status":"success","actId":"585924418"}
undefined
undefined
{
Any ideas where I'm going wrong?
The response you get as status from $.post is a string. You need to parse it order to use it as you intend. Moreover, newArr is undefined because you have not defined it anywhere. This is probably because you have reused someone else's code and missed this part:
newArr = JSON.parse(status)
The response is coming as string, so you need to parse it before you can access it as JSON:
$.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){
var data = JSON.parse(status);
console.log(data['status'])
console.log(data['actId'])
}

How is dynamically created array in jquery is accessed in PHP

I have created a script that adds items on click into an array.
$(document).ready(function()
{
var array_ids = [];
$('.add').click(function()
{
array_ids.push($(this).parent().siblings('.row_id').html().trim());
alert(array_ids);
});
});
Items are coming from mysql database so I am storing primary keys of items. keys are stored in array like this manner
1,2,3,4,5
Now I want to access this array in php so that I could store in database one by one.
I thought to doing some ajax and this is my code
$('.show').click(function(e)
{
//e.preventDefault();
$.ajax(
{
method: 'POST',
url: 'createsale.php',
data: {items: array_ids},
success: function()
{
alert('done');
}
});
});
I get the done alert but couldn't manage to get it stored in database. Can anyone tell how do I insert those items in mysql?
Send the value from Javascript by using Json {"key":value} or array [1,2,3]. While getting them to use them in PHP, you can use json_decode() to convert the Json or array from Javascript to PHP.
If you want your information from PHP to Javascript, Just use the funtion json_encode() that will send a json string.
Ref: json_encode, json_decode
your createsale.php file should has something like this below code to receive array Data & dont forget to escape your data using mysql_real_escape_string before doing any mysql query
<?php
if(isset($_POST["items"]) && $_POST["items"] !=""){
$arr = $_POST["items"];
//convert JS array to PHP array
$arr = json_decode($arr,true);
//then you have your PHP array => new array(1,2,3,...);
/* use for/forEach loop
for($i=0;$i<count($arr);$i++){
do the task
}
*/
}
?>

JSON stringify and decode JS/PHP

I have a problem with sending an object in PHP. I stringify the object before sending it to the PHP file.
The PHP file then uses json_decode. But the decode shows a blank variable.
The object which i console.log shows this as its structure:
Its then sent to PHP with this :
console.log(my_Obj);
var as = JSON.stringify(my_Obj);
call_data('add.php?&as='+as, nxtFunc);
Now in the PHP file i have this which handles the situation:
$path = json_decode($_GET['as']);
echo $_GET['as'].'<br/>';
print_r($path);
die;
The result is:
[null,null,{\"8\":[null,null,null,null,null,null,[],[],[],[],[]],\"9\":
[null,null,null,null,null,null,null,null,null,null,[]],\"10\":
[null,null,null,null,null,null,null,null,null,null,[],[]],\"11\":
[null,null,null,null,null,null,null,null,null,null,null,[]]}]
<br/>
My XHR request url in Chrome shows:
add.php?as=[null,null,{%228%22:[null,null,null,null,null,null,[],[],[],[],[]],%229%22:[null,null,null,null,null,null,null,null,null,null,[]],%2210%22:[null,null,null,null,null,null,null,null,null,null,[],[]],%2211%22:[null,null,null,null,null,null,null,null,null,null,null,[]]}]
Notice the print_r shows nothing. Should i not be using stringify ?
Thats because my_Obj is an array and not an object.
Try this:
var as = JSON.stringify({data: my_Obj});
Note:
You will also need to clean up the array before stringifying - i.e. clear out all null/undefined indices. Check this answer: https://stackoverflow.com/a/281335/921204

jQuery $.ajax to pass multidimensional array to PHP

I am using jQuery and PHP to write JSON data to my server. I'm processing a decent amount of repeating numeric data (~.75kb), so I want to pass the data to PHP in the form of a multidimensional array.
At the moment I cannot manage to get the data to PHP in a form that it can recognize. I've tried various combinations of sending/receiving as arrays and objects with no success.
The best case scenario would be one in which I pass a the array to the PHP and the PHP converts it to a readable form. I'd rather not use associative arrays or any serializing on the part of the Javascript.
Code... This is giving me a 500 internal server error, which no longer occurs if I omit the passed data variable. (I'm not yet using $data in the php file yet because I know it's not working.)
function generateData() {
// code here
return [ one[ sub_one[], sub_two[] ], two[], three[], four[] /* Etc... */ ]
}
function saveData() {
$.ajax({
url: "scripts/save.php",
data: {
"area":"testing",
"location":"testing",
"name":"testing",
"data":generateData()
}
});
}
<?php
$area = $_GET['area'];
$location = $_GET['location'];
$name = $_GET['name'];
$data = $_GET['data']);
# Performing operations with variables...
echo 1;
?>
Thanks for any help you can offer.
Found a solution:
"data": {
data: generateCellData()
}
The above code passes data as an object to PHP, whereby I can access the original array as $data("data"). I'm still somewhat baffled by why this works when I'm already passing the data and other parameters as an object.

Categories