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
Related
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'));
I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});
Hi I have a php script that successfully gets an array of data from an exsternal xml source, the array is called $file, I know that the php array is populated by using print_r($file).
I have tried to use the following php to pass to a javascript session:
//Convert to JSON Array
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
But either this hasn't worked, or the following JS code below is wrong:
var jsonarray = result["json_array"];
alert(JSON.stringify(jsonarray));
Could someone please tell me where I am going wrong?
You should not use JSON.stringify there. JSON.parse is what you are looking for. Since you want to parse existing JSON, not create new JSON.
edit: Your code is a bit odd. I'd think you want something like this
php
//Convert to JSON Array
echo json_encode($file, JSON_FORCE_OBJECT);
js
alert(JSON.parse(data)); // Where data is the contents you've fetched from the server
You have to encapsulate php code :
<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>
var jsonarray = <?= $result["json_array"] ?>;
alert(JSON.parse(jsonarray));
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 jQuery post:
var animals = {
animalsArray: [],
tripId: <?php echo $_GET['id']; ?>
};
$('.student-check').each(function() {
animals.animalsArray.push($(this).attr('id'));
});
var sendMe = JSON.stringify(animals);
$.post("saveChanges.php", sendMe, function(response) {
console.log(response);
}, "json");
PHP handler:
echo json_encode(print_r($_POST, true));
// Array
// (
// )
Why is the array empty? I'm posting data but the response returns an empty array.
You are encoding the data as JSON, which isn't a format PHP handles natively for form submissions.
Remove var sendMe = JSON.stringify(animals); and pass animals to $.post instead of sendMe. jQuery will encode it using one of the standard formats supported by HTML forms and PHP.
Alternatively see this question for how to get the raw request body.
Also:
echo json_encode(print_r($_POST, true));
json_encode and print_r are both functions that take a data structure and express it as a string. Use one or the other, not both.