Is it possible to update js file using php command? - javascript

I have script.js file. and it has following array
script.js
'COntent': function() {
var contentFacts = {
blocks: {
'block1': {
name: 'yleow',
title: 'H2',
type: 'content'
}
}
};
}
},
I tried like this in my php , but it did not work :(
$lines = file($path.'/script.js');
$lines[64] = "'block2': {name: 'yleow',title: 'H2',type: 'content'}"
file_put_contents($path.'/script.js', implode($lines));
I want to add another element call block2 for this array. How can i update my script.js file function using php?
Is it possible using file_put_contents? please advice

JavaScript is a very poor substitute for a database or any other structured data format. In this case even more because you are trying to inject content into source code.
What you probably want is some form of structured data outside of your code for example a JSON file or an SQLite database.
PHP does support parsing from and serializing to JSON:
json_decode
json_encode
Possible solution
Put the contentFacts into a seperate JSON file
{
"blocks": {
"block1": {
name: 'yleow',
title: 'H2',
type: 'content'
}
}
}
Manipulate JSON with PHP
$json = file($path.'/blocks.json');
$blocks = json_decode($json, true);
$blocks['block2'] = array(
'name' => 'blue',
'title' => 'h3',
'type' => 'content'
);
Write back to JSON file
$adapted_json = json_encode($blocks);
file_put_contents($path.'/blocks.json');
Now you need to get this into your JavaScript part, I assume on the client. You can do this by requesting it from the server:
const contentPromise = fetch('/path/to/blocks.json');
contentPromise.then((blocks) => {
// Do something with those blocks. (render them to the page?)
});

Related

Struggling to show data from javascript in html

Note: I am new to JavaScript and html so there are a lot of things i do not quite understand yet.
I am trying to make a web-application that uses a bus-schedule API to show the bus times around my apartment. I have managed to retrieve the data, but I struggle to display that data in the html. (edit: it is possibly a SDK, i dont really know the difference)
// this is the function write_bus() in my javascript file departures.js:
function write_bus() {
document.getElementById("bustime-kong").innerHTML = data;
}
// 'data' is a variable in javascript that contains the information I fetched from the client, and is what I am trying to show.It is on the following format:
const data = {
aimedArrivalTime: '2022-01-06T12:36:00+0100',
aimedDepartureTime: '2022-01-06T12:36:00+0100',
cancellation: false,
date: '2022-01-06',
destinationDisplay: {
frontText: 'xxx'
},
expectedDepartureTime: '2022-01-06T12:38:12+0100',
expectedArrivalTime: '2022-01-06T12:37:32+0100',
forAlighting: true,
forBoarding: true,
notices: [],
predictionInaccurate: false,
quay: {
id: 'xxx',
name: 'xxx',
publicCode: 'P2',
situations: [],
stopPlace: [Object]
}
}
<script src="departures.js"></script>
<input type="button" onclick="write_bus()" value="Busstider"> <br>
<div id="bustime-kong"></div>
(In order to save some space i removed 2/3 of the data)
I appreciate every bit of help i could get!
You can't insert raw objects like that as DOM text. You have to use specific properties, but if you are so inclined to insert object like that, use JSON.stringify() method.
document.getElementById("bustime-kong").innerHTML = JSON.stringify(data);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
BTW, It is good practice to put <script> tag at the end to make sure HTML is loaded before running any JavaScript.
You can create a function that will parse through the json and print it in table form like below.
// this is the function write_bus() in my javascript file departures.js:
function write_bus() {
document.getElementById("bustime-kong").innerHTML = createTable(data);
}
// 'data' is a variable in javascript that contains the information I fetched from the client, and is what I am trying to show.It is on the following format:
const data = {
aimedArrivalTime: '2022-01-06T12:36:00+0100',
aimedDepartureTime: '2022-01-06T12:36:00+0100',
cancellation: false,
date: '2022-01-06',
destinationDisplay: {
frontText: 'xxx'
},
expectedDepartureTime: '2022-01-06T12:38:12+0100',
expectedArrivalTime: '2022-01-06T12:37:32+0100',
forAlighting: true,
forBoarding: true,
notices: [],
predictionInaccurate: false,
quay: {
id: 'xxx',
name: 'xxx',
publicCode: 'P2',
situations: [],
stopPlace: [Object]
}
}
function createTable(data){
var table = "<table>";
for(var key in data){
table+="<tr>";
table+="<td>"+key+"</td>";
table+="<td>"+data[key]+"</td>";
table+="</tr>";
}
table+="</table>";
return table;
}
<input type="button" onclick="write_bus()" value="Busstider"> <br>
<div id="bustime-kong"></div>
Since it is array of data you need to use Json.stringify method,
document.getElementById("bustime-kong").innerHTML = JSON.stringify(data);

Unable to access JSON data from Javascript

I am passing the following from my Django back-end to my front-end in order to dynamically build a form :
{
"access_key": "93ec6137de00eacee6f8",
"profile_id": "7851E15D64",
"transaction_uuid": "c878c7e6db5657526",
}
Within the browser console, if I pass :
MyJSON = {
"access_key": "93ec6137de00eacee6f8",
"profile_id": "7851E15D64",
"transaction_uuid": "c878c7e6db5657526",
}
Then I can access each value properly, for example, MyJSON.access_key returns 93ec6137de00eacee6f8 perfectly within the console.
However, from my Javascript, I am unable to access any of those values as i get an "undefined".
var obj = JSON.parse(MyJSON)
console.log(obj) // returns the whole JSON String
console.log(typeof(obj)) // returns 'string'
alert(obj[0]) // returns "{", the very first character of the 'string'
alert(obj.access_key) // returns "undefined".
- How can access each Key and Value from MyJSON from my javascript? (not JQuery)
Note that I have reviewed many similar article but I must be missing the obvious ...
Hope you can assist !
Thanks in advance.
EDIT :
I have a list of Fields and a list of Values which i then merge into the below (pass the JSON Validator on https://jsonlint.com/):
{'access_key': '93ec6137d70aada23400eacee6f8', 'profile_id': '7851E53E-96BB-4D4-BD5-0FE61CC15D64', 'transaction_uuid': '00939a90-db7b-41cb-af45-669ec5cc69e8', 'signed_field_names': 'bill_to_forename,bill_to_surname,bill_to_email,bill_to_phone,bill_to_address_line1,bill_to_address_city,bill_to_address_postal_code,bill_to_address_country,transaction_type,reference_number,payment_method,amount,currency,locale,card_type,card_number,card_expiry_date', 'unsigned_field_names': 'card_type,card_number,card_expiry_date', 'signed_date_time': '2021-05-23T16:20:17Z', 'bill_to_forename': 'John', 'bill_to_surname': 'Doe', 'bill_to_email': 'null#cfgfg.com', 'bill_to_phone': '07922889582', 'bill_to_address_line1': '123 Random Street', 'bill_to_address_city': 'London', 'bill_to_address_postal_code': 'RG1T3X', 'bill_to_address_country': 'GB', 'transaction_type': 'sale', 'reference_number': 'o6yejf', 'payment_method': 'card', 'amount': '100', 'currency': 'USD', 'locale': 'en', 'card_type': '001', 'card_number': '4456530000001096', 'card_expiry_date': '12-2026', 'signature': 'Un5gNYB5qZaRazzCDWqrdZuNkTRARIcfAt9aF2a1wbY='}
Back-end Code
FieldList = ['access_key', 'profile_id', 'transaction_uuid', 'signed_field_names', 'unsigned_field_names', 'signed_date_time', 'bill_to_forename', 'bill_to_surname', 'bill_to_email', 'bill_to_phone', 'bill_to_address_line1', 'bill_to_address_city', 'bill_to_address_postal_code', 'bill_to_address_country', 'transaction_type', 'reference_number', 'payment_method', 'amount', 'currency', 'locale', 'card_type', 'card_number', 'card_expiry_date', 'signature']
ValueList = ['93ec6137d0aada23400eacee6f8', '7851E53E-96BB-4DF4-BD55-0FE61CC15D64', 'c4fe96b0-063f-4b94-a6a5-2137bb796bd9', 'bill_to_forename,bill_to_surname,bill_to_email,bill_to_phone,bill_to_address_line1,bill_to_address_city,bill_to_address_postal_code,bill_to_address_country,transaction_type,reference_number,payment_method,amount,currency,locale,card_type,card_number,card_expiry_date', 'card_type,card_number,card_expiry_date', '2021-05-23T16:27:24Z', 'John', 'Doe', 'null#cyrce.com', '07922889582', '123 Random Street', 'London', 'RG1T3X', 'GB', 'sale', 'xl42fn', 'card', '100', 'USD', 'en', '001', '4456530000001096', '12-2026', 'vvb73h0GUpzUrvoG9VDaMc3vQRV5GsL4QTATc7IrrPA=']
NewFormat = dict(zip(FieldList, ValueList))
MyJSON = json.dumps(NewFormat, indent=4)
return JsonResponse(MyJSON, safe=False)
Apologies for the large amount of data.
I am somehow forced to use "safe=False" in my Python back-end otherwise I end up with :
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/Documents/Droplet/Droplet/Harness/sasop2.py", line 543, in signsasop
return JsonResponse(FinalJSONObject)
File "/home/pi/.local/lib/python3.7/site-packages/django/http/response.py", line 561, in __init__
'In order to allow non-dict objects to be serialized set the '
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
Since I am passing safe=False, is that why my front-end does not get the MyJSON as... JSON?
Would this be the root cause of the issue?
Front-End Sample :
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
console.log('%c Processed Data \n',
'background: #000000; color: #FFFFFF; font-size: 30px'
,xhr.response);
// Dynamically create the ReconstructedForm
RawProcessedData = xhr.response
console.log(RawProcessedData)
// Convert to JSON
var obj = JSON.parse(RawProcessedData)
console.log(obj)
console.log(typeof(obj))
alert(obj[0])
alert(obj.access_key)
Thanks a lot for your quick input !
As per deceze's answer, I was essentially double parsing both in the back and front end for no reasons.
Removing the json.dumps from the backend allows the JSON object to be passed and managed in the front end without issue.
I have the same issue when i started developing on Django. If you need to pass dictionarys from django to javascripts, the best thing to do is just using django rest framework. It serialize ( in other words, it transform any data into a dictionary/json ) any given data from a model.
But if you want to make this without Django Rest, you should use fetch on javascript. This fetch ( also called as a "Promise") communicate with the backend ( in this case, Django ) and it GET or POST data from the frontend. I will give you an example.
Supose you have this on views.py:
from django.http.response import JsonResponse
def getJSON(request):
MyJSON = {
"access_key": "93ec6137de00eacee6f8",
"profile_id": "7851E15D64",
"transaction_uuid": "c878c7e6db5657526",
}
return JsonResponse(MyJSON)
And the you can link that to the urls.py like this:
urlpatterns = [
path('get-json', views.getJSON, name="get-json")
]
Then you can GET that JSON by doing this on your javascript:
function getDataJson(){
let url = 'get-json'
fetch(url,{
headers: {
"Content-type": "application/json",
},
})
.then(response => response.json())
.then(data=> console.log(data))
}
This will console log your data.

Parsing JSON-like file type to JSON in JavaScript

I have lots of files with an unusual file extension.
I need to read the files using JavaScript and convert their contents to JSON or regular JavaScript objects.
Is this even possible?
I have some hope, because the files are already structured very similar to JSON:
// file.unusualFileType
Page: {
id: P001
Title: "Page Title"
URL: "/home"
Elements: {
Button: {
Text: "Click me"
Action: SAVE
}
}
}
EDIT: HÃ¥ken Lid kindly provided a solution for my particular use case. Out of curiosity I would still be interested in how to read any file as a string with JavaScript and how one could possible parse such a string.
It would be valid yaml if you strip out the curly brackets. You can use js-yaml to parse the sample data, so maybe it works with the rest of your files too?
const rawData = `
Page: {
id: P001
Title: "Page Title"
URL: "/home"
Elements: {
Button: {
Text: "Click me"
Action: SAVE
}
}
}`
const yamlData = rawData.replace(/[{}]/g, '')
console.log(jsyaml.load(yamlData))
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/3.13.1/js-yaml.min.js"></script>

Shopify script_tag API - how to pass the variable?

I have some javascript code in my ShopifyApp which I'm adding to the ShopifyShop using script_tag API:
$response = $client->request(
'POST',
"https://{$store}/admin/script_tags.json",
[
'headers' => [
'X-Shopify-Access-Token' => $access_token
],
'form_params' => [
'script_tag' => [
"event" => "onload",
"src" => $scriptUrl
]
]
]);
Script:
var _smid = 'someValue';
(function(a,b,c,d,e) {...})
My problem is that I need to pass var _smid there which is different per App instalation (generated server side) - is there any way to do it or maybe some other way to actually pass script as variable from php and not as url to .js file?
Modify your script tag to do a callback to an App Proxy. That way, your App gets the store name, and any other data you need to pass to it.

YII2. Using URL's in js

I have the following javascript code
$(".order-event-btn").click(function(e) {
$.ajax({
url: "URL",
type: "POST",
data: {
eventId: $(e.target).attr('data-event-id'),
},
success: function(data) {
//Some code
},
error: function(data) {
//Some code
},
});
});
I include this script using "BookAsset".
Here
url: "URL",
I need URL to the action "book-event" in the controller Book.
On the server, I can do this:
Url::to('/book/book-event')
But how do I get URL on client side?
There is an solution:
1. js file include via BookAsset.
2. in view file I register bundle:
\frontend\assets\BookAsset::register($this);
3. in view file define a bookEventURL variable. Now it is available in the js-file.
$this->registerJs('var bookEventURL = ' . Url::to('/book/book-event') . ';');
But I do not like this solution.
What will happen when I use this script in many views. I have to define a variable bookEventURL in each view?
My Question. Is it possible to bind js-variables to my BookAsset. When I register my BookAsset in the view, in page source code automatically insert next code:
<script>var bookEventURL = "http://example.com/book-event/";</script>
A proper way of doing this is to add the needed information in your button tag, e.g. :
<?= Button::widget([
'label' => 'Order',
'options' => [
'class' => 'order-event-btn',
'data' => [
'url' => Url::to(['book/book-event']),
],
],
]) ?>
And in your js code :
$(".order-event-btn").click(function(e) {
var url = $(this).data('url');
// ...
});
But if you really want to "bind js-variables" to your BookAsset, you could simply override register() :
public static function register($view)
{
parent::register($view);
$view->registerJs('var bookEventURL = ' . json_encode(Url::to(['book/book-event'])) . ';');
}
If you wanna use it in different places of your application than I guess you should place it in the layout.

Categories

Resources