For a PHP/HTML page what is the simplest method of adding data to JSON?
Should I be using PHP, JS, or jQuery?
I've tried different lots of different methods found online, but I can't get any to work. I've tried all of these but I can't get it quite right.
var myObject = new Object();
JSON.stringify()
JSON.parse()
$.extend();
.push()
.concat()
I have this JSON file loaded
{"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"}
]
}
I want to programmatically add
var THISNEWCOMMENT = 'jkl;
{"thecomment": THISNEWCOMMENT}
so that the JSON variable will be
{"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"},
{"thecomment": "jkl"}
]
}
///////////////////
Edit after answer
//////////////////
This is the ajax in my index.php file I used to call the PHP function (in its separate file):
function commentSaveAction ()
{
var mytext = $(".mycommentinput").val();
mytext = mytext.replace("\"","'");
$.ajax({
url: 'php/commentwrite.php',
data: { thePhpData: mytext },
success: function (response) {
}
});
}
And this is the finished PHP function I used with the help of deceze:
<?php
function writeFunction ()
{
$filename = '../database/comments.txt';
$arr = json_decode(file_get_contents($filename),true);
$myData = $_GET['thePhpData'];
$arr['commentobjects'][] = array('thecomment' => $myData);
$json = json_encode($arr);
$fileWrite=fopen($filename,"w+");
fwrite($fileWrite,$json);
fclose($fileWrite);
}
writeFunction ();
?>
//////////////////////
with JS and not PHP
/////////////////////
var myJsonData;
function getCommentData ()
{
$.getJSON('database/comments.txt', function(data) {
myJsonData = data;
var count = data.commentobjects.length;
for (i=0;i<count;i++) {
$(".commentbox ul").append("<li>"+data.commentobjects[i].thecomment+"</li>");
}
});
}
function commentSaveAction ()
{
var mytext = $(".mycommentinput").val();
mytext = mytext.replace("\"","'");
myJsonData.commentobjects.push({"thecomment": mytext});
var count = myJsonData.commentobjects.length;
$(".commentbox ul").append("<li>"+myJsonData.commentobjects[count-1].thecomment+"</li>");
}
Whichever language you do it in, you have to parse the JSON string into an object/array, modify it, then encode it back into a JSON string. Don't attempt any direct string manipulation of the JSON string. PHP example:
$arr = json_decode($json, true);
$arr['commentobjects'][] = array('thecomment' => 'jkl');
$json = json_encode($arr);
Whether to do this in Javascript or PHP or elsewhere depends on when/why/where you need to do this; that's impossible to say without knowing more about the use case.
Try with json_encode and json_decode PHP functions.
//work on arrays in php
$arr = array('sth1', 'sth2');
//here you have json
$jsonStr = json_encode($arr);
//array again
$arrAgain = json_decode($jsonStr);
$arrAgain[] = 'sth3';
//json again
$jsonAgain = json_encode($arrAgain)
Just do it in javascript:
var x = {"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"}
]
};
x.commentobjects.push({"thecomment": "jkl"});
var THISNEWCOMMENT = 'jkl',
myObj = JSON.parse(rawJson),
newComment = {"thecomment": THISNEWCOMMENT};
myObj.commentobjects.push(newComment);
var serialized = JSON.stringify(myObj);
//send the updated JSON to your controller
Parse the object, access the commentobject list inside of it, push the new comment in the list and then serialize the updated object again.
Related
I am trying to extract the values of a json but when I return it I get an object object.
Something I did wrong in decoding? this is the decoding code in php
<?php $contenido=file_get_contents("https://www.deperu.com/api/rest/cotizaciondolar.json");
$info = json_decode($contenido,true);
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
?>
this is the function code
<script>
$(function() {
$("#btnbuscar").on('click',function(){
var direccion='servicio.php';
$.ajax({
type:'get',
url:direccion,
success:function(datos){
var campo=eval(datos);
alert(datos[0]);
}
});
return false;
});
});
</script>
Uwhen you write this:
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
Your $info is an array, and cadena is an array, too. So you can direct point $cadenra to the array like this:
$cadena= $info['cotizacion'];
echo json_encode($cadena);
Or fix your js like this:
alert(datos[0][0]);
Here is a simple way to read your JSON without Ajax but with using $.getJSON
On your PHP file since you want to get only "cotization" data change: $cadena=array(0=>$info['cotizacion'] to $cadena=array(0=>$info['cotizacion'][0] and you can remove [0] if you are planning to have and to loop on multiple "cotizacion"
On your javascript use:
$.getJSON("servicio.php", function(data) {
var items = [];
$.each(data[0], function(key, val) {
(key + '=' + val);
});
});
There are several solutions, but don't get wrong in a javascript/jquery while calling a json chain.
For example:
<?php
// Page : service.php
$json = '{
"service": "Reference dollar exchange rate",
"website": "website.com",
"link": "https://www.website.com/gearbox_type/",
"quotation": [{
"buy": 3.419,
"sale": 3.424
}]
}';
// $json = file_get_contents("https://www.website.com/api/example.json");
$info = json_decode($json,true); // convert array
$cadena=array(
0=>$info['quotation'][0],
);
echo json_encode($cadena); // convert json
// get-> [{"buy":3.419,"sale":3.424}]
echo json_encode($cadena[0]); // convert json
// get-> {"buy":3.419,"sale":3.424}
?>
// Javascript
// To better use your function I would have to do a cleanup of the code with JSON.parse
<script>
$(function() {
/*
* Check yes and Json and convert json string
* Analyze the data with JSON.parse () and the data becomes a JavaScript object.
* Ex. var obj = '{hello:'mitico'}' -> convert object
* $.clean_string_json(obj) return-> {hello:'mitico'}
* $.clean_string_json('text' + obj) return-> {}
* $.clean_string_json('text' + obj,false) return-> false
* $.clean_string_json('text' + obj,true) return-> true
*/
$.clean_string_json = function (str,xreturn) {
try {
return JSON.parse(str);
} catch (e) {
return xreturn === false ? false : xreturn || {};
}
};
$("#btnbuscar").on('click',function(){
$.ajax({
type:'get',
url: 'service.php',
success:function(datos){
var campo= $.clean_string_json(datos);
alert(datos[0]); // return -> {"buy":3.419,"sale":3.424}
}
});
return false;
});
});
</script>
Welcome to stackoverflow! We hope you like it here.
As already pointed out by #Anurag Srivastava, call the url directly and you'll get json back, you do not need a proxy.
const jUrl = "https://www.deperu.com/api/rest/cotizaciondolar.json";
$.get(jUrl)
.then(({cotizacion}) => console.log(cotizacion));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am sending arrays from View to Controller using Post Method. This is my code.
Controller: Session::put('isCheck', $isCheck);
this is how i am assigning value to isChecked array.
var isChecked = [
<?php
$isCheck = "";
if (Session::has('isCheck')) {
$isCheck = Session::get('isCheck');
}
foreach ($isCheck as $isCheck) {
$status = $isCheck;
?>
<?php echo $status; ?>,
<?php } ?>
];
View:
$("#target").click(function () {
var postTo = '<?php echo action('sample#postView'); ?>';
var data = {
isChecked: isChecked,
duplicateIsChecked: duplicateIsChecked
};
jQuery.post(postTo, data,
function (data) {
alert(data);
});
});
isChecked and DuplicateIsChecked are my 2arrays.
In controller I am writing this code:
$duplicateIsChecked = $_POST['duplicateIsChecked'];
$isCheck = $_POST['isChecked'];
But i am getting Undefined index duplicateIsChecked error. Help me
Have you checked the header of your Ajax call to make sure its sending any data? In the code you posted, you're assigning variables to the two values in data but you didn't show where you are declaring those variable values.
You can't pass a javascript array to php like that, you have to convert the array into JSON and send it.
so it should be
var data = JSON.stringify({
isChecked: isChecked,
duplicateIsChecked: duplicateIsChecked
});
To get the JSON payload in controller, you can use
$payload = Input::json()->all();
then to access the attribute, you can reference it as
$payload['duplicateIsChecked'] & $payload['isChecked']
i try to send data to my php scripts but i think i miss something.
First of all,
function deleteData2()
{
var artistIds = new Array();
$(".p16 input:checked").each(function(){
artistIds.push($(this).attr('id'));
});
$.post('/json/crewonly/deleteDataAjax2', JSON.stringify({'artistIds': artistIds}),function(response){
if(response=='ok')
alert(artistIds);
});
}
Above code is my js file. i have artistIds in var artistIds. My goal is sending this array to my php script.In order to that, i make it json , i mean encode it with JSON.stringify
then in php side, i use below code.However, $array is always null. What might be the reason ?
public function deleteDataAjax2() {
$array=json_decode($_POST['artistIds']);
if (isset($array))
$this->sendJSONResponse('ok');
}
You are passing the data as a raw string of JSON, but your PHP is trying to find that string by parsing the data as application/x-www-form-urlencoded and then looking at the artistIds key.
Assuming the array is flat: Forget JSON. You don't need it.
$.post('/json/crewonly/deleteDataAjax2', {'artistIds': artistIds},function(response){
And:
$array = $_POST['artistIds'];
If the array isn't flat, then:
$.post('/json/crewonly/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
And (with suitable error checking added):
$json = $_POST['json'];
$data = json_decode($json);
$artists = $data['artistIds'];
I am trying to send JSON to a PHP file using jQuery AJAX, basically what I am trying to do is get the values and id's of a bunch of child elements and then assign them to a JSON object and then send that object via ajax to the PHP file which would then process it and enter it into a database.
Here is my code,
Javascript/jQuery:
function test(){
var selects = $('#systems_wrapper').find('.dropDowns');
var newArray = new Array();
selects.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
var o = { 'id': id, 'value': val };
newArray.push(o);
});
$.ajax({
type: "POST",
url: "qwer.php",
dataType: 'json',
data: { json: newArray }
});
}
PHP:
<?php
$json = $_POST['json'];
$person = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $person);
fclose($file);
echo 'success?';
?>
It creates the file, but it is completely blank, any idea what it could be?
Thanx in advance!
You could try using the JSON.stringify() method to convert your array into JSON automagically. Just pass the output from this.
data: { json: JSON.stringify(newArray) }
Hope this helps
Don't use an array.
use a simple string like this:
var o = '[';
selects.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
o += '{ "id": "'+id+'", "value": "'+val+'" },';
});
o = o.substring(0,o.length-1);
o += ']';
and in the ajax just send the string 'o'
data: { json: newArray }
in the php file just make a json_decode($json, true);
it will return an array of array that you can access by a foreach
if you want to see the array, use var_dump($person);
You should set a contentType on your ajax POST. I would use contentType: "application/json";
You should use json_encode() not json_decode()! This way you will get the json string and be able to write it.
No need to use json_decode if you're saving it to a text file. jQuery is encoding your array in JSON format, PHP should then just write that format right to the text file. When you want to open that file and access the data in a usable way, read its contents into a variable and THEN run json_decode() on it.
I am trying to post a group of arrays using the jQuery post method, but I am having trouble getting the value of the arrays. How can I get the values of the array that I have sent?
If somebody could help me i would be grateful....
Here is what i have done:
$(document).ready( function()
{
$("#submit_info").click (
function()
{
var batchArr= new Array();
batchArr=arrPush('batch');
var facultyArr= new Array();
facultyArr=arrPush('faculty');
var levelArr= new Array();
levelArr=arrPush('level');
var sectionArr= new Array();
sectionArr=arrPush('section');
var shiftArr= new Array();
shiftArr=arrPush('shift');
$.post("server_side/college_info_insert.php",{
batchArr:batchArr,
facultyArr:facultyArr,
levelArr:levelArr,
sectionArr:sectionArr,
shiftArr:shiftArr
}, function(data)
{
alert(data);
});
}
);
function arrPush(opt)
{
var Arr= new Array();
Arr.push($("#"+opt+"_1").val());
var count= $("#"+opt).val();
var i=0;
for(i;i<=count;i++)
{
if(i==0)
{
Arr.push($("#txt"+opt).val());
}
else
{
Arr.push($("#txt"+opt+i).val());
}
}
return Arr;
}
}
);
How can I get the array values in the next page "college_info_insert.php" ??
okay, so this is actually a really common issue. It's unclear that you can't just send an array as-is from javascript to PHP and have it recognized.
The problem is that PHP doesn't know how to read in multiple values from a POST request - typically things like that require the PHP author to use brackets like: varname[].
So, basically you must send variables as strings. Using JSON you can send even complicated objects as strings to PHP using a single variable name. Typically you'd use JSON.stringify or something along those lines - but if you have a simple array you might not even need it.
Here's a full example of the problem/solution, found using jquery and $.post:
Asume you have a file myurl.php:
<?php
print_r($_POST);
?>
And in a separate file (or the console), you try:
var myarray = Array('some','elements','etc');
var mydata = {postvar1: 'string', postvar2: myarray};
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
This doesn't work! The result is that postvar2 only contains "etc".
The solution is force the array into a JSON string that can be decoded from PHP.
var myarray = Array('some','elements','etc');
var json_array = $.map(myarray,function(n) {
return '"'+n+'"';
});
var mydata = {postvar1: 'string', postvar2: '['+json_array+']' };
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
ON the PHP side you now must use: json_decode($_POST['myarray']); to get your results in a proper array.
Note, this example assumes very simple strings or numbers in your array. If you have complex objects, you will need to use a JSON.stringify function which will take care of extra quotes, escaping special characters, etc.
Not sure if i understood the question but wouldn't something like this work
if (isset($_POST['batchArr'])) {
$batchArr = $_POST['batchArr'];
// Then populate your html here e.g
echo $batchArr[0];
}