convert php array to a javascript array - javascript

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'));

Related

Datatables - add rows with PHP

I have an issue with jquery and datatables. I want to get the informations for the datatable from an mysql database with PHP and after that update the datatable with this informations.
I already tried it with something like this:
var datatable = $("#example").DataTable();
$.get('load_session_overview.php', function(newDataArray) {
//datatable.clear();
datatable.row.add(['Random','12','18','Menu']);
datatable.row.add([newDataArray]);
datatable.draw();
});
The first line with the add is working fine, but I don't know how to format the data in the php script correctly.
And if I'm getting more rows from the php script how can I add them all the the table?
Thanks, Phil
One way to format the data correctly in your PHP script is to return it in a JSON format. You can use the json_encode() function in PHP to convert your data into a JSON string.
For example:
<?php
$data = array(
array('Random','12','18','Menu'),
array('Data1','13','19','Menu2'),
array('Data2','14','20','Menu3')
);
echo json_encode($data);
?>
Then, in your jQuery code, you can use the JSON.parse() method to convert the JSON string into a JavaScript object, and loop through the data to add each row to the table.
$.get('load_session_overview.php',
function(newDataArray) {
var data = JSON.parse(newDataArray);
for(var i = 0; i < data.length; i++) {
datatable.row.add(data[i]);
}
datatable.draw();
});
Alternatively, you can use ajax call and pass the data to it to load it in the datatable and also you can use the ajax call to update the datatable as well.
$.ajax({
url: "load_session_overview.php",
type: "GET",
dataType: "json",
success: function (data) {
datatable.clear();
datatable.rows.add(data);
datatable.draw();
}
});
This way you can load the data in the datatable and also update it as well.
There are several ways to achieve this, for instance
php writes javascript code in an html script tag
see How to print JSON array inside script tag?
XHR request
see Displaying JSON data in HTML

JavaScript array to PHP via AJAX

I have written a simple JS script, that saves mouse positions in an array, which I then send to a php function via AJAX. It works, and saves the recieved data, but the problem is how it is saved, i.e. i would expect to have a normal output of the x and y position as is: [x1,y1],[x2,y2],[x3,y3],...
But what i get is something like this:
a:63:{i:0;a:2:{i:0;i:527;i:1;i:1010;}i:1;a:2:{i:0;i:490;i:1;i:1205;}i:2;a:2:{i:0;i:588;i:1;i:1311;}i:3;a:2:{i:0;i:615;i:1;i:1368;}i:4;a:2:{i:0;i:553;i:1;i:1474;}i:5;...
I thought if i encode it in JSON format that it would save as i thought, but i dont understand why the output is as it is. Any ideas?
The JS code is as follows:
window.onbeforeunload = function() {
var jsonString = JSON.stringify(tabela);
$.ajax({
type: 'POST',
url: 'process.php',
data: {
text1: jsonString
}
});
}
And the PHP side is this:
$text1 = json_decode(stripslashes($_POST['text1']));
$string_data = serialize($text1);
file_put_contents("your-file.txt", $string_data);
The content looks like this in the file, because you passed the array through serialize function. In order to "decode" file content, use unserialize.
If you want to have more human-readable file content, just store the JSON string in the file ($_POST['text1'] directly) or instead of serialize use json_encode again before calling file_put_contents.

Convert html string (json representation) into actual javascript object

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).

Javascript array conversion to jQuery.post's data

I am trying to send different values to php script using jQuery.post
The data I want to send are links like this
http://example.com/image1.jpg
http://example.com/image2.jpg
http://example.com/image3.jpg
http://example.com/image4.jpg
I don't have an exact amount of these links they would vary depending on the user interacting with my script
I am storing these links in a javascript array "fileLinks".
what I want to do is to send these links to php using jQuery.post
Can I format these links in this shape?
jQuery.post(MyAjax.ajaxurl,
{ action : 'ajax-rform',
link1: http://example.com/image1.jpg,
link2: http://example.com/image2.jpg,
link3: http://example.com/image3.jpg,
link4: http://example.com/image4.jpg,
},
function(data){
jQuery("#fileupload").after('<h1>Success</h1><p>Your registration has been recieved.</p>');
}
);
In php I just need to use for loop and replace the link1 and http://example.com/image1.jpg with the arrays and php would iterate it for me but what should I do in javascript?
Thanks
Just pass the array. jQuery will encode it with array notation, and PHP will decide it back into an array:
jQuery.post(MyAjax.ajaxurl,
{ action : 'ajax-rform',
link: fileLinks
},
function(data){
jQuery("#fileupload").after('<h1>Success</h1><p>Your registration has been recieved.</p>');
});
In PHP, you can access the array as $_POST['link'].
Why not just create a json array and then use php's json_decode method?
Perhaps you should just make a data object to send, populate it from your array like this
var postData = { action : 'ajax-rform' };
for(var i = 0; i < fileLinks.length; i++){
postData["link"+(i+1)] = fileLinks[i];
}
And then use that in your ajax
jQuery.post(MyAjax.ajaxurl,
postData,
function(data){
jQuery("#fileupload").after('<h1>Success</h1><p>Your registration has been recieved.</p>');
}
);

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

Categories

Resources