PHP assertive array to JavaScript [duplicate] - javascript

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 3 years ago.
So my website has received some data in the form of a PHP associative array (see below) and I'm trying to convert it to something I can interact with using JavaScript.
JavaScript seems to treat it as just a string and I've had problems using JSON.parse. I have control over the format of this data before it arrives at my JS do I need to restructure it??
Extra Info: Web page A requests data from web page B then web page B collects the data from a database and returns a big array. The array above is the response from web page B in web page A. Each index (["tag"],["current_ids"] etc) actually have large array contained in them, I just shortened it to 1 for ease of understanding.

Data on the web is always sent and received as strings. JavaScript needs the data in a format that it can understand, for example JSON.
PHP has an in-built function to convert your data, e.g. your array, into JSON called json_encode(). It also has a sister function for decoding JSON into PHP called json_decode().
https://www.php.net/manual/en/function.json-encode.php
https://www.php.net/manual/en/function.json-decode.php
Depending on your setup, you'll want JavaScript to make a XHR request to an endpoint where you're running PHP and then you'll use PHP to process that request and return a JSON string.
Alternatively, you could use PHP to directly echo the JSON string into JavaScript, for example:
<script>
<?php echo "var myData = ${json};"; ?>
</script>
XHR is the better practice in general but you should use whichever approach best suits your needs.

Related

store javascript data in PHP Variable [duplicate]

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 2 years ago.
I am not familiar with Javascript at all. I need to retrieve the value from externalReferralProgram . Which is in json format.
I want to get the value of this and store it in a PHP variable.
const FTXRest = require('./');
const ftx = new FTXRest({
key: 'apikey',
secret: 'apiseceret'
})
ftx.request({
method: 'GET',
path: '/api_key_status'
}).then(console.log);
PHP is a server-side language. Javascript is a client side language.
What happens is PHP will run whatever stuff its supposed to, then send whatever HTML and javascript you tell it to send to the browser. At this point, PHP will wipe out this session and start handling other requests. The browser then receives this content and starts running the javascript.
With this understanding, you can see that it really doesn't make sense to store a javascript value in a PHP variable - by the time the javascript is running, PHP has already long-forgotten about this request.
Your best bet is to either find a way to do the same javascript logic in PHP, or, make the javascript send a REST request back to the PHP server with whatever data you need, so that PHP can do further processing on it (this means creating a separate PHP file that'll receive javascript data from $_GET or $_POST).
Use json_decode
Takes a JSON encoded string and converts it into a PHP variable.

When using AJAX, unable to split string and treat it as an array

I'm trying to use AJAX to receive updates from a database without needing to reload the page. I've had very minimal problems thus far, however, I finally hit one. When retrieving information from a database, I have it convert all possible rows to an array. From there, I encode that array back to Javascript using $test1 = json_encode($array). In this same PHP function, I'm doing this to multiple pieces, converting those encoded arrays to a string by doing echo $test1."#".$test2."#".$test3. In Javascript, I split that string by the hashtag, and then grab the information of an array by doing something like test1 = array[1]. When doing that, I can retrieve that array entry as a string even though it's in the fashion of a Javascript array. Any ideas on how I can make it treat that string, which is setup like an array, as an array? Thanks in advance!
When retrieving the information from the AJAX response, you need to make it a Javascript Object. Convert the response to an object by doing JSON.parse(response) to get it to work

Javascript(Ajax) vs PHP: Generating HTML Elements [duplicate]

This question already has answers here:
JSON vs HTML Ajax response
(3 answers)
Closed 9 years ago.
Does generating html elements such as table rows with js through a ajax callback function really any slower than php(echo "< tr>< /tr>)? The browser still has to render client-side the information into the table whether its done in php or js.
I couldn't find much information on this subject, so I wanted to get some opinions here. Are there any arguments to not use js to generate elements dynamically from a ajax call?
Note: I originally forgot to mentioned that the table rows would be data from a database.
In your case using ajax is time wasting because it should send request to server, and server should process it, then responding with the result, while using native JS (only javascript) is faster because the server is not included, and using direct print when page loading is fastest.
But if you need to work dynamic tables, you can work on JavaScript without AJAX call, I don't see any reason here to use AJAX for building HTML table.
Its perfectly fine to generate html elements using ajax call. There might arise occasion where you HAVE to return the DYNAMICALLY generated HTML elements.For this you cannot just print it client side since you need the info from the db.
If you have the info to be presented in a tabular form beforehand, meaning before the page is built, then you should use PHP.
If, the data is to be requested at runtime from the server, then AJAX should be used.
If you just want to built tables with no data (or repeating data which is already available on the page) then, using plain JavaScript is the best option.
Suppose you have an existing page with a table
| A | A | A |
| A | A | A |
Now you place an ajax-call reading some data from the server. If you want to replace the whole table it might be usefull to let php create the table, return it to the browser en let javascript replace the entire table.
If you only want the second row to change, you might want php to return an array with values and let javascript replace the cell-contents based on that response.
But one way or the other, you still have to go the circle browser => server => browser. So the few moments javascript takes to alter the page don't add too much time to that.

modify contents of a js file

Hi I have a javascript array of Url's in content.js file. I need to display the urls in seperate input boxes on a seperate page say display.php. Edit and delete buttons are given along with each input boxes. any change made by the user should be reflected in the content.js file.
I have shown all the url's in the input boxes. now an onclick event calls a function on button press.
My question is what will be the best way to update the array in content.js file(the file contains only one array). I'm trying to use file handling but that will require the content.js to have a strict format always. Is there a better way to modify the contents of the array or delete rows from array without file handling?
In first step, you should read the contents of JS file and pass it to json_decode function. It will give you PHP array. Use this array to display text boxes to user.
In second step, you should get the strings the user was submitted (e.g. from $_POST) and construct a PHP array from them. Then use json_encode to convert PHP array to JavaScript array represented in a string. Then you can write this string to JS file. So its content will be always valid.
You could do it with a server-side language like PHP. See this tutorial on how to write files using PHP. I would convert the array into a string using json_encode and use json_decode to convert it back into an array after reading it.
If you're only saving these URLs for the user and nobody else (so only the person entering/editing the data needs to see it) then I recommend using HTML5 localStorage

json save to db and use it after

how to convert this json to database:
var obj = {
'one' : ['qq','rr'],
'pizda' : { }
}
and then retrive it and use it?
You could store it in mongodb without too much effort.
db.foo.save(obj); // Save obj to a database
db.foo.find(); // find it again.
You might want to give a bit more details.
Assuming that the database runs on the webserver and you thus need to pass the JSON as a string around between webserver and webbrowser, then the answer depends on the server side language you're using.
If you're using PHP, then you can convert between a JSON string and a PHP array using json_decode() and json_encode()
If you're using JSP/Java, then there are several libraries available to convert between a JSON string and a Java object, the popular ones being Google Gson, JSON.org and Jackson.
If you're using ASP/.NET, then there are several libraries available as well, under each Google JSONSharp.
Also see the bottom of this page for an overview of several JSON parsers/formatters in various languages.

Categories