Pass array through ajax (not working) - php

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

Related

Php - how to encode an array as json and send it back

Allow me to preface this by saying that I looked at multiple SO posts on this and I am still lost.
So in my php code I am fetching data from my database and then I am trying to insert it into an array as follows:
$arrayResult = array();
foreach ($result as $item) {
array_push($arrayResult, array("type" => $item['type'],
"count" => $item['count'])
);
}
echo json_encode($arrayResult);
My problem is as follows, the only time my JS shows any data is when I just print out the data on a successful AJAX call, any attempts at manipulating it fail totally. As in, no data shown at all.
var arrayResult = null;
$.get("../php/displayGraph.php",
function (data) {
arrayResult = (data);
var result = JSON.parse(arrayResult);
$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
The result of this is:
[{"type":"Entertainment","count":"4"},{"type":"Other","count":"31"},{"type":"Politics","count":"50"},{"type":"Sports","count":"3"},{"type":"Technology","count":"9"}]
I am honestly at a loss in terms of what I even need to do to make it work. And here I thought java was bad with json.
Try like this,
$.get("../php/displayGraph.php",
function (data) {
$.each(data, function (i,item){
console.log(item.type + " === " +item.count);
}
/*arrayResult = (data);
var result = JSON.parse(arrayResult);*/
//$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
Not sure why, but the following works
$.get("../php/displayGraph.php",
function (data) {
var result = JSON.parse(data);
$("#results").html(data);
console.log(result[1][0].count);
}
);
Certainly is a 2D array the way my php makes it, but i did not think this would be how to do as all the other tutorials i saw never had it like this.

convert string to array dynamically in jquery

I have working with amcharts (line charts). Set data dynamically with ajax and get the data from php code in JSON format.
Problem comes string is not changed to array dynamically.
if i have add this string static in jquery code
code:
[{"country":"17 Feb","visits":"4","color":"#EA5759"},{"country":"16 Feb","visits":"1","color":"#EA5759"},{"country":"15 Feb","visits":"3","color":"#EA5759"}];
Thats working fine.
if i have set this code dynamically. line charts shows undefined.
i have use this function
ajax return code
[{"country":"17 Feb","visits":"4","color":"#EA5759"},{"country":"16 Feb","visits":"1","color":"#EA5759"},{"country":"15 Feb","visits":"3","color":"#EA5759"}]
i have just pass this on this function. like
var ajaxString = [{"country":"17 Feb","visits":"4","color":"#EA5759"},{"country":"16 Feb","visits":"1","color":"#EA5759"},{"country":"15 Feb","visits":"3","color":"#EA5759"}];
and call this funciton
lineChart(ajaxString);
function lineChart(data) {
var chart;
var chartData=data;
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
chart.startDuration = 1;
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.labelRotation = 45; // this line makes category values to be rotated
categoryAxis.gridPosition = "start";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.dashLength = 5;
// valueAxis.title = "Visitors from country";
valueAxis.axisAlpha = 0;
chart.addValueAxis(valueAxis);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.valueField = "visits";
graph.colorField = "color";
graph.balloonText = "<b>[[category]]: [[value]] Users</b>";
graph.type = "column";
graph.lineAlpha = 0.2;
graph.fillAlphas = 0.9;
chart.addGraph(graph);
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorAlpha = 0;
chartCursor.zoomable = false;
chartCursor.categoryBalloonEnabled = false;
chart.addChartCursor(chartCursor);
chart.creditsPosition = "top-right";
// WRITE
chart.write("chartdiv");
}[![undefined message][1]][1]
But thats not working.
Thank You in advance
The ajaxString that you are passing to your function is simply an string and not a json object , so what your function lineChart might be expecting is json object so try to convert your ajaxString into valid json object before sending it to your function using
JSON.parse(ajaxString);
This looks like you are attempting to set a JSON string to chartdata instead of a javascript object array.
In this case, you should try to parse your string gotten through the ajax call like so : JSON.parse(dataelement) before setting it to chartdata.
You can create the code dynamically in PHP and covert the array in json via json_encode.
encoded json can be used later in the jquery.

Could use some advice on jQuery each function on a associative multidimensional array

I'm working on a jQuery .get that will send a value to the server to compare against an array which will then get encoded into a json format as the responses. Below is the code (jQuery and PHP zend). I'm not sure if my problem is with identifying the keys and values or if it is the syntax. Is there away to view the raw json data echoed by my php controller?
$.get(
"/ed/macro",
{value: singleValues},
function(data) {
$.each(data, function(key,value1){
$.each(data.value1[0], function(key,value2){
$('#stage').html("data");;
});
});
},"json");
$select = $this->getDbTable()->select();
$select->from('sub');
$resultSet = $this->getDbTable()->fetchall($select);
$data = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Subdiscipline();
$entry->setIdSub($row->idsubdiscipline)
->setSub($row->subdiscipline)
->setDescription($row->description);
$data[] = $entry;
}
return $data;
}
public function macAction()
{
$request = $this->getRequest()->getParam('value');
// acti
$sub = new Application_Model_Sub();
$fetch = $sub->fetchAll($request);
$jsonObject = Zend_Json::encode($fetch);
echo $jsonObject;
// action body
}
To view the object print_rin PHP and console.log in Javascript. Or as Sam said, after the JS has called it, look in Net to see what was sent.
Assuming that you are echoing a json string after telling your server to tell the browser it is json with header("Content-type: application/json"); your problem is probably here
$.each(data, function(key,value1){
$.each(data.value1[0], function(key,value2){
data.value1 isn't what you're dealing with there, it's value1. I'm assuming value1 IS an array, and you're picking the first element in it value1[0] to then iterate?
$.each(data, function(key,value1){
$.each(value1[0], function(key,value2){
Or maybe you're after
$.each(data, function(key,value1){
$.each(value1, function(key,value2){
Please echo the object and show it to us.

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!

JSON_decode two dimensional array of objects?

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

Categories