JSON_decode two dimensional array of objects? - php

I have a two dimensional array of objects like so:
function test(n){
this.id = n;
}
var testArray= new Array(2);
for(i = 0; i < testArray.length; i++){
testArray[i] = new Array(2);
for(j = 0; j < testArray[i].length; j++){
testArray[i][j] = new test((2*i)+j);
}
}
I then stringify it to post using AJAX like so:
var data = {testA: {testB: testArray[0], testC: testArray[1]}}
var text = JSON.stringify(data);
Once I perform the jquery AJAX call:
$.post("test.php",text,function(data){
alert(data);
});
I cannot work out how to decode and use this object on the PHP side, so far i've tried something like this:
<?php
$data = json_decode($_POST);
if($data == null){
echo "fail";
} else {
echo $data;
}
?>
But I get an error that says it expects a string and I'm passing it an array. I've also tried something like
$data = json_decode($_POST['testA']);
and then error doesn't appear but instead it always outputs "fail".
Does anyone know what I need to do on the PHP side so I access the data?

Why would you run stringify on it? If you just send it like this:
$.post("test.php", data, function(data) {
You should be able to retrieve it like this:
$data = $_POST['testA'];

Related

Pass array through ajax (not working)

I have an array named "bulk" that looks like this:
bulk['A']['country'] = 'country';
bulk['B']['country'] = 'country2';
bulk['B']['otherdata'] = 'Data';
So, it's like a multidimensional array... I'm passing it trough ajax like this:
$.ajax(
{
type: 'POST',
url:"SaveFields.php",
dataType:'json',
data:bulk,
success:UpdatePoints,
error:function()
{
console.log('Falló el ajax, presione Control+F5');
}
});
BUT, it's not being received on the php post! I'm doing a printr and the POST is empty...
echo "<pre>";
print_r($_POST);
echo "</pre>";
HOWEVER, if I try to pass any other data, any other array... the data is received and the post is printed!
There's something obviously wrong with the "bulk" array but I can't understand what... any tips? any clues?
the bulk receives data from fields like this:
bulk[bloque_nombre]['country'] = campos[0].val();
bulk[bloque_nombre]['name'] = campos[1].val();
bulk[bloque_nombre]['title'] = campos[2].val();
bulk[bloque_nombre]['area'] = campos[4].val();
bulk[bloque_nombre]['city'] = campos[5].val();
And if I log the bulk in console, the data appears correctly...
Solved it! I declared the "bulk" array like this:
var bulk = {};
bulk['graduados'] = {};
bulk['nacimientos'] = {};
bulk['puestos'] = {};
bulk['incorporaciones'] = {};
instead of:
var bulk = new Array();
bulk['graduados'] = new Array();
bulk['nacimientos'] = new Array();
bulk['puestos'] = new Array();
bulk['incorporaciones'] = new Array();
I don't know the exact reason behind this, maybe I can't pass full arrays using ajax, but objects are accepted correctly...

AJAX returning both query result and string?

I'm trying to create an ajax search function, where user is to enter the search criteria, then ajax grab those data and send them to php to query the result from the database, then it returns the result along with the pagination link stored in a string.
In the javascript file:
$(document).ready(function(){
$('.song_filter').change(function(){
var url = 'listing/ctrl';
var data {
title: $('#title').val();
author: $('author').val();
}
$.post(url, data)
.success(result) {
var jsonObj = $.parseJSON( result );
output_list(jsonObj); /* fetch out the result */
}
});
});
And in my php listing/ctrl, I have both the query result and the paginated link ready to return. I have no problem returning only the query result on its own, but I don't know how to return both the result and the link.
$result = $this->pagination->get_result();
$page_nav = $this->pagination->page_nav(); // <li class="page">2</li><li class="page">3</li>
echo json_encode($result, JSON_UNESCAPED_UNICODE);
You can append the link to the json object, something like this:
$result = $this->pagination->get_result();
$page_nav = $this->pagination->page_nav();
// create an object to store the result and the link
$json = new stdClass();
$json->link = $page_nav;
$json->data = $result;
echo json_encode($json, JSON_UNESCAPED_UNICODE);
And the in your ajax success
.success(result) {
var jsonObj = $.parseJSON( result );
jsonObj[0].link /* Here comes the link */
jsonObj[0].data;
}

What is the simplest method of programmatically adding data to JSON?

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.

Transfer JavaScript Array to PHP array using ajax?

I am trying to transfer a list of data from a javascript array to a php array and I can't seem to get ajax to do the trick. Can someone show me the code on how to do this? So far here is what I have, which is just the array:
JAVASCRIPT
var dates;
// the dates array is then filled up here
// it contains information in the form {'2012-01-01', '2012-03-12', ...}
$.ajax({
type: "REQUEST",
url: "NAMEOFPHPFILE.php",
data: { sendData1 : dates },
success: function() {
alert("Attempting to transfer array -> AJAX");
}
});
var submissions;
// the submissions array is then filled up here
// it contains information in the form {int, int, ...}
// ect ......... with 3 more arrays using { sendData2 : submissions },
PHP
<?php
$bDates = $_REQUEST['sendData1'];
// need to set this array = to the JavaScript dates array
$bSubmissions = $_REQUEST['sendData2'];
// need to set this array = to the JavaScript submissions array
?>
I would prefer to use the REQUEST method to prevent information logging into the URL. This code also doesn't work when trying POST instead of REQUEST
At the very end of the .php page, I am outputting a bunch of arrays onto a CSV page where I iterate through the arrays and place their elements in the file. This already works, but I need to transfer some of these arrays from javascript to PHP so that I can spit out the data. That looks like this:
<?php
$stringData = "Dates, Number of Lines Changed, , Bug Dates, Arrivals, Fixed, Closed, Hold_";
for($i = 0; $i < sizeof($dataXAxis); $i++){
$date = substr($_REQUEST['Dates'][$i+1], 0, 24);
$stringData .= "$date, $dataYAxis[$i], , $bDates[$i], $bSubmissions[$i], $bCompletions[$i], $bDones[$i], $bRejections[$i]_";
}
echo '<BR><BR>Download Your CSV File';
?>
Why doesn't the AJAX work? The arrays appear empty...
One method would be to try sending the data in the form of JSON. Then using json_decode, you can convert it to an array. Example:
var Json = {"User1":"John", "User2":"Joe", "User3","Jerry"};
var data = "data="+Json;
hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
console.log(hr.responseText);
}
}
hr.open("POST", "parsefile.php", true);
hr.send(data);
Then when you get the data in your PHP file it's something like:
$data = $_POST['data'];
$array = json_decode($data, true);
This all will tell php to turn our data into an assosciative array. It can then be manipulated as an assosciative array.
I was literally just working on this.
jQuery
var group_ids = $('.form-elements li').map(function(){
return $(this).data('group-id')
}).get()
$.get('{{ url('group/update_order_by') }}', {group_ids: group_ids});
PHP from the restful Laravel framework
public function get_update_order_by()
{
$group_ids = Input::get("group_ids");
$group_count = count($group_ids);
for ($i = 0; $i < $group_count; ++$i) {
$group = Group::find($group_ids[$i] );
$group->order_by = $i;
$group->save();
}
return true;
}
Raw PHP (ugh...)
$group_ids = $_GET("group_ids");
$group_count = count($group_ids);
for ($i = 0; $i < $group_count; ++$i) {
echo $group_ids[$i];
}
return true;
The simply convert an array to string
var data = [1,2,"hello"];
var data_str = data.join(",");
and afterwards convert the string to array in php:
$array = explode(",", $_REQUEST["data"]);
In PHP, the REQUEST expects arrays to be passed in the following format:
sendData1[]=first&sendData1[]=second&sendData1[]=third
This is automatically converted into an array:
$sendData = $_REQUEST['sendData`];
echo $sendData[0];
echo $sendData[1];
First, for the sake of simplicity, create an array holding both arrays you want to send and parse:
var request = Array(dates, submissions);
Second, make sure you're sending your request as properly formatted JSON. In addition, when testing I recommend returning the output from the remote file in your callback to see how your data was parsed. I recommend the following implementation, as well as sending via POST:
$.ajax({
type: "POST",
url: "NAMEOFPHPFILE.php",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(request),
success: function(data) {
alert(data);
}
});
In your PHP file, get you can parse the contents of the aforementioned request into an array using the following:
<?php
// convert json data read from the input stream to an array
// *note* you MUST set the true flag in the json_decode() function, otherwise it will convert the data into an object
$request = json_decode(file_get_contents('php://input'), true);
var_dump($request);
You should now get an alert containing the var_dump of the array(looks messy, I know!).
This should be enough to get you started, hope it helps!

Submit arrays to php using dojo

How do I submit an array from dojo to php.
I'm submitting these values:
["a", "b", "c"]
Here's what I got so far:
btn_send.onclick(function(){
var name_array = name_looper();
console.log(name_array);
dojo.xhrPost({
url: "dojo_phpform.php",
content: {names: name_array},
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
});
function name_looper(){
var names = dojo.query('input[type=text]');
var name_array = [];
names.forEach(function(element, index, array){
name_array[index] = dojo.attr(element, 'value');
});
return name_array;
}
I tried to echo $_POST['names'] from the php file(dojo_phpform.php) and it didn't return any errors. It seems like the array isn't actually submitted. The only thing that's returned is the last item in the array. What do I do?Please help, Thanks in advance!
I just tested this with grails and php. In grails I have no problem getting an array submitted through a dojo xhrPost : I retrieve the array properly parsed with all its values as expected.
If I post :
dojo.xhrPost({
content : {
names : ['foo', 'bar']
},
url : "mygrailscontroller"
});
I get an array param on the other side. Which proves the problem hasn't to be solved on the dojo side, but on the php side.
In php, if a form input has a variable of type array, its name parameter has to be set with square brackets, like : "names[]" rather than "names".
So... in your case the solution is not to flatten the array into a string (sorry), but to name your array argument with brackets. So it would be :
dojo.xhrPost({
content : {
"names[]" : ['foo', 'bar']
},
url : "myphpcontroller"
});
As far as I've been able to see, dojo's xhr functions don't support it. I'm using a helper function to "flatten" parameters myself.
_flattenXhrParams: function(params)
{
var newParams = {};
for(var key in params)
{
if(dojo.isObject(params[key]))
{
for(var innerKey in params[key])
{
newParams[key + "[" + innerKey + "]"] =
params[key][innerKey];
}
}
else if(dojo.isArray(params[key]))
{
for(var i = 0, l = params[key].length; i < l; i++)
{
newParams[key + "[]"] = params[key][i];
}
}
else
{
newParams[key] = params[key];
}
}
return newParams;
}
It's butt ugly, I know, and obviously only works on one dimensional arrays/objects. In your case, you'd do:
dojo.xhrPost({
url: "dojo_phpform.php",
content: _flattenXhrParams({names: name_array}),
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
.. and you'd get POST parameters like names[]=a&names[]=b&names[]=c. For objects, you'd get names[somekey]=a&names[otherKey]=b etc. PHP handles both nicely.
I'm pretty sure the values of the content object only take strings. If you want to submit an array, you'd have to turn it into JSON and then json_decode it on the server.

Categories