Convert html string (json representation) into actual javascript object - javascript

I am printing some php data into a field on my page. The data is json_encoded by the backend.
Now i want to retrieve this information and turn it into a javascript object...
$(document).ready(function(){
$('.trigger-info-change').click(function(){
var rel = $(this).attr('rel');
var td_id = 'info-'+rel;
var data = $('#'+td_id).html();
console.log(data);
});
});
now data is correctly console logging my "object" like this:
{"data":{"id":"1","data1":"1","data2":"2"},{"id":"2","data1":"3","data2":"4"}}
Now the question is how do i turn this html into a actual javascript object... I've tried to use jQuery.parseHtml, and some other things google advised but no luck... would i need a script or is there something like that out there?
Thanks in advance!

If you want use Jquery:
var json = $.parseJSON(data)
Or
var obj = JSON.parse(data);

I think this better to print out JSON String in javascipt.
<script>
var data = <?php echo $json ?>;
</script>
Which makes :
<script>
var data = {"data":{"id":"1","data1":"1","data2":"2"},{"id":"2","data1":"3","data2":"4"}};
</script>
But if you insist on your way, use JSON.parse(jsonString).

Related

How to pass json array of one page into another in php?

i have a php page p1.php where in a JavaScript function i have got some json array as j now i want to use this j to another php page p2.php
i have tried it by
window.location.href="p2.php?data="+j
then in p2.php
i used $_get['data'] to get the result
but after researching i come to know the format is not good for huge data.
so
i leave the idea of passing it into the url
if your j is object then you can post with jquery
example :
$.post("p2.php", { datavar : j},function(data){
})
in your p2.php
print_r( $_POST["datavar"]);
echo $_POST["datavar"]["var2"];
it's depends of many data you can move, but always is ugly send pure data by url.
But in your example, only miss transform the json (object) to string:
window.location.href="p2.php?data="+JSON.stringify(j);
If you can go in the right way, store the info in a session:
http://php.net/manual/es/reserved.variables.session.php
Then the p1.php looks like these:
<?php
session_start();
$_SESSION['json'] = isset($_POST['json']) ? $_POST['json'] : null;
// other php stuffs
?>
<!-- other html stuffs -->
<script>
var json = { your: 'json' };
(function(){
var xhr = new XMLHttpRequest();
var data = encodeURIComponent(JSON.stringify(json));
xhr.open('post', 'p1.php');
xhr.send('json='+data);
})();
</script>
These code send the info (json) via AJAX to p1.php

convert php array to a javascript array

I am working with laravel, and i get a list of values from a database with this code:
$idordenes = DB::table('ordenes')->select('id')->get();
when I echo de idordenes variable I get this:
[{"factoryid":233658},{"factoryid":566981},{"factoryid":889566},{"factoryid":114789},{"factoryid":256958},{"factoryid":0},{"factoryid":0},{"factoryid":599544},{"factoryid":222364},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":555696},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},{"factoryid":0},
I want to covert this in a javascript array like this:
var ordenes = [233658,566981,889566,114789,...];
I hope the help. thanks
Try this:
const arr = [{"factoryid":233658},{"factoryid":566981},{"factoryid":889566},{"factoryid":114789},{"factoryid":256958},/* more element */];
let newArr = arr.map(elem=>elem.factoryid);
console.log(newArr);
But your mean is code in php or js ?
You need to use an ajax get request to get the data from php to your javascript file. You can use jQuery to make an ajax request like so:
$.ajax(
url: "path_to_your_php_file",
success: data => {
var ordenes = JSON.parse(data);
console.log(ordenes); // Ordenes is now the array in javascript
}
);
In your php file you must "send out" the data you wish the ajax call to receive. You can do this by doing the following:
echo json_encode(array_column($idordenes, 'factoryid'));

How to extract json objects into an external file?

I have this small code example:
<script type="text/javascript">
var texts = [{key:'key_1', value:'value_1'},
{key:'key_2', value:'value_2'},
{key:'key_3', value:'value_3'}];
</script>
I use a json array directly in my xhtml page by using the script tag. The json array "texts" is used by an another java script function in my xhtml page, but that is not important at the moment.
How can a extract this json array into an external file? Which library it must be used?
EDIT:
I use a java maven project and that should be include my external json file!
I tried this code but it doesn´t work:
<script type="text/javascript">
var placeholderTexts = himjQuery(document).getJSON('placeholder.json');
</script>
You can use each loop in jQuery
Just try this
$.each(texts, function(key, value) { }
please try the below.
var arraysel;
var json = { };
for(var i = 0, l = arraysel.length; i < l; i++) {
json[arraysel= [i].id] = arraysel= [i].value;
}
After reading many times your question, I think what you want is this:
Create a .js file, for example data.js, with your data... which is not a JSON-serialized object, but a real literal. Use pure JSON notation if you want.
var DATA = {"a":1, "b":2};
Import that "script" wherever you want to use your data.
<script type="text/javascript" src="./data.js></script>
Use this data from any place in your JS code, for instance:
console.log(DATA.a);
Please get JSON data from AJAX and evaluate response and store in variable
<script>
var placeholderTexts = new Object();
$(function(){
$.get('placeholder.json', function(data){
try{
placeholderTexts = jQuery.parseJSON(data);
console.log(placeholderTexts)
}catch(e){
alert(e.toString());
}
});
});
</script>

How to serialize a JSON object in JQuery

I am not able to serialize the JSON object "data", shown below.
<script type="text/javascript">
var myObj = {'first_name':{'answers':{'0':'John'}}};
var postdata = {'data':myObj};
$.post("get_note.php", postdata, function(data){
$('#note').text(data);
});
</script>
Following is the code in file get_note.php:
<?php
print_r($_POST['data']);
?>
This results in the following being printed to the #note element.
Array ( [first_name] => )
The array appears to be empty. I was expecting a multidimensional array in the PHP file. Why is it empty?
On the client, you can serialize by doing JSON.stringify() for pure javascript. On the server, you'll need to do a php json_decode() on the string.
So on the client:
var postdata = {'data':JSON.stringify(myObj)};
and on the server:
$myObj = json_decode(htmlspecialchars_decode($_POST['data']),true);
References:
js JSON.stringify(): http://www.json.org/js.html
php json_decode(): http://php.net/manual/en/function.json-decode.php
You could try sending a serialized JSON array and decrypt it in server side.
To serialize JSON array use this:
var my_json_array = { index: 11 };
JSON.stringify(my_json_array);
Then in server side you can convert (decode) it to PHP array like this:
$json = $_POST["my_json_array"];
$my_array = json_decode($json);
So your code would turn in this:
<script type="text/javascript">
var data = {'first_name':{'answers':{'0':'John'}}};
var postdata = {'data':JSON.stringify(data)};
$.post("get_note.php", postdata, function(data){
$('#note').text(data);
});
</script>
and
<?php
print_r(json_decode($_POST['data']));
?>
How it was said, this solution is good for new browsers (with native JSON support) for older ones this solution won`t work.
More about JSON support in browsers you can read here:
http://en.wikipedia.org/wiki/JSON#Native_encoding_and_decoding_in_browsers

Get htaccess URL params in JavaScript

Is there any way in Javascript to get the parameters ume modified URL with htaccess?
As an example: www.website.com/argument/1/argument/2
Where "/argument/2" = &product_id=2
There is some way to pick up these parameters in JavaScript?
You can export these properties by simply printing the map as JSON. I'm going to show this in PHP.
<script>
var GET = <?= json_encode($_GET); ?>;
</script>
Then you can access the values as GET['product_id'].

Categories

Resources