Passing multi dimensional array to PHP with jQuery and AJAX - php

I've got the jQuery code:
$(document).ready(function() {
answers = new Array();
answers[0] = new Array();
answers[0]['question_id'] = 12;
answers[0]['answer_id'] = 32;
answers[1] = new Array();
answers[1]['question_id'] = 55;
answers[1]['answer_id'] = 132;
answers[2] = new Array();
answers[2]['question_id'] = 987;
answers[2]['answer_id'] = 1112;
$.ajax({
type: "POST",
url: "collect.php",
data: {answers: answers},
dataType: "json",
beforeSend:function(){
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
},
success: function(data){
alert('success!');
}
});
});
Now, should this work? According to what I've found when looking for code examples it should. Problem is, I have no idea how I could collect the data in my PHP file. I mean, it's a $_POST[], but then what? How do I collect the $result[0]['question_id'] and all the other data?
Thanks a lot in advance,
Carl C. Carlsson

You're never actually populating the arrays inside of the answers array with data, their length is still 0 because you're using string indexes rather than int indexes. What you really want are objects stored in your array.
answers[0] = {};
answers[0]['question_id'] = 12;
answers[0]['answer_id'] = 32;

You can collect the value in php page with $_POST['answers']. Then you can loop through that array do whatever you want with the data.

It was solved by changing the Javascript to:
answers = {};
I could then simply access the data in PHP with:
$_POST['answers'][1]['answer_id'];
for example, or just loop through it.
Thanks for your help, ladies and gentlemen.

Related

json Time (hh:mm:ss) value return from php json_encode

I just want to ask if the returned data from my php json_encode is directly treated as "time" on my jquery, or do I have to format it in my jquery script ? Here:
I will be using this data on my jchartFX, I just wonder if this has been treated as "time" values or not . Because my chart displays: "No Data Available".I already made a data format but it seemed like not working.
Here's the entire code:
PHP
public function get_sample_data(){
$data = $this->queries->query("SELECT DATE_FORMAT(a.datetimeRequested,'%M %d') AS `Date`,
SEC_TO_TIME(AVG(TIME_TO_SEC(c.request_startckit))) AS `AVG CT`,
SEC_TO_TIME(SUM(TIME_TO_SEC(c.request_startckit))) AS `SUM CT`
FROM request a
JOIN ckit b ON b.idRequest = a.idRequest
JOIN cycle_time c ON c.idCkit = b.idCKIT
");
echo json_encode($data,JSON_PRETTY_PRINT);
}
Jquery:
chart1 = new cfx.Chart();
chart1.getData().setSeries(2);
var xaxis = chart1.getAxisX();
xaxis.getLabelsFormat().setFormat(cfx.AxisFormat.Date);
var yaxis = chart1.getAxisY();
yaxis.getLabelsFormat().setFormat(cfx.AxisFormat.DateTime);
yaxis.getDataFormat().setCustomFormat("hh:mm:ss");
chart1.getDataGrid().setVisible(true);
var series1 = chart1.getSeries().getItem(0);
var series2 = chart1.getSeries().getItem(1);
series1.setGallery(cfx.Gallery.Bar);
series2.setGallery(cfx.Gallery.Bar);
$.ajax({
url: $("#base_url").val() + "ajax/get_sample_data",
dataType: "json",
success: function(data){
chart1.setDataSource(data);
},
error: function(){
alert("an error occured");
}
});
var divHolder = document.getElementById('ChartDiv');
chart1.create(divHolder);
I think it would be better if you gave an example on how you will be using those values, that way we could see if you would need any kind of parsing. To answer your question, in your JSON response both of them are being treated as strings.

Multiple Arrays returned by json from PHP

To begin with I am building a complete CRM running Ajax and there is a lot to this, so please be patient and read the whole thing.
I have an ajax script returning several json arrays. When I display the return value from my php script I get this:
[{"packages":{"id":"1","name":"Land Line"}},{"packages":{"id":"2","name":"Cellular w\/Alarm.com"}},{"packages":{"id":"3","name":"Home Automation"}}]
What I am trying to do is separate the arrays so I can make a select drop down from it. Before anyone says anything, yes I know how to do that my itself, but I am needing the form this script is populating to be a select dropdown or a complete filled in form based off of the id going into another script. It is a bit confusing, so don't ding me for it please.
Here is the PHP script alliance_form.php:
$equip = "SELECT * FROM packages WHERE brand='$brand'";
if($db->query($equip) === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $db->error, E_USER_ERROR);
} else {
$result = $db->query($equip);
$array = array();
foreach($result as $r) {
$array[] = array(
"packages" => array(
"id" => $r['id'],
"name" => $r['name']
)
);
}
echo json_encode($array);
}
Here is the jquery going to the PHP form and coming back to input the information:
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
success: function(msg)
{
$("#package-form").html(msg);
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
alert(value);
});
});
},
error: function(error)
{
$(".error").html(error);
}
});
This is part of an ordering system of a CRM, so this script is checking the database for existing orders under the id. If the id is there then it is supposed to come back with the order information and I populate the form. If not it will give a select dropdown to select a package which then populates an empty form. That is the gist of what I am on right now.
Here is the question: Why can't I get a response from JQuery on the each() loop on this. One return comes back with a regular array, and this one is a nested array.
I'm not quite clear on what you're asking, but here are my thoughts on this:
You've got .packages in the wrong place. Instead of this:
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
...
You should have written this:
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
...
Better yet, you could just get rid of packages altogether. It's an unnecessary level in the JSON structure.
Also, I don't think jQuery knows that the response is JSON. For this to work, you need either dataType: 'json' in the list of arguments to $.ajax, or something on the server to set the MIME type appropriately.
I'm also concerned about $("#package-form").html(msg);, because msg is not an HTML string.
You should try something like this (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
console.log(value);
});
});
Instead of $.each(msg.packages, function(i, object){...}) because msg is an array of objects and in your given example there are three objects right now and each object has a packages item (nested object) which contains id and name.
Update : You can also use, just one loop (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
console.log(object.packages.id);
console.log(object.packages.name);
});
Sorry guys, I threw out my back and couldn't get to my code from home.
Anyways I tried both solutions you provided, and I have been looking at this for a while but neither worked. I have this updated to:
$("#brand").click(function () {
var brand = $(this).attr('rel');
$("#order-form").empty();
var contact_id = $("#contact_id").val();
var dataString = "contact_id=" + contact_id +"&brand=" + brand + "";
//alert("test");
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
//dataType: "json",
success: function(msg)
{
//$("#package-form").html(msg);
$.each(msg, function(i, object) {
if(msg.packages) {
$("#package-form").append("<select>");
$.each(object.packages, function(index, value) {
$("#package-form").append('<option value="'+value+'">'+index+'</option>');
});
$("#package-form").append('</select>');
}
});
},
error: function(error)
{
$(".error").html(error);
}
});
});
This just returns nothing not even a blank select box. The $("#package-form").html(msg); is just so I can see the output how the php script is sending it back. The if statement is just to run a verification to see if the array has a nested array with packages in it. I need the return function to do a certain action if it does. Very Important!
As for the dataType: 'json', line in the ajax, it doesn't give me a return value if I have that placed in it. But when I remove it, it will display the array.
Nothing has been changed in the PHP file besides moving the query like suggested.
Ok guys. I got the answer! I have it like this:
$("#brand").click(function () {
$("#order-form").empty();
$("#package-form").empty();
var msg = '[{"packages":{"1":"Land Line"}},{"packages":{"2":"Cellular w\/Alarm.com"}},{"packages":{"3":"Home Automation"}}]';
var newData = JSON.parse(msg);
var newSelect = "<select>";
$.each(newData, function(i, ob) {
$.each(ob.packages, function(index, value) {
newSelect += '<option value="'+index+'">'+value+'</option>';
});
});
newSelect += "</select>";
$("#package-form").append(""+newSelect+"");
});
Here is the fiddle: http://jsfiddle.net/M78vE/

jquery each loop into a multi array, check for duplicates

I think what I want to do is really simple but can't get it to work. I'm looping through a table and getting some values from the existing rows, that part works. Then I'm using AJAX to try and make a multidimensional array without duplicates but something isn't working. What I really want to do is delete the duplicate part, reorder the array and array_push new values. Here's what I have:
AJAX:
function getData(){
$("#table .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
$.ajax({
type: "POST",
async: false,
data: {key: key, s: sel, q: q}
});
});
}
PHP:
if(isset($_POST['key'])){
$title = $_POST['key'];
$s = $_POST['s'];
$q = $_POST['q'];
if(!empty($_SESSION['check'])){
foreach ($_SESSION['check'] as $key=>$value){
if(in_array($title, $value)){
unset ($_SESSION['check'][$title]);
$_SESSION['check'] = array_values($_SESSION['check']);
array_push($_SESSION['check'], array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
}else{
$_SESSION['check'] = array(array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
Is there something wrong with the logic? It seems like it should work. The same foreach loop works when trying to delete a table row. It finds the correct KEY and deletes it. Why doesn't it work here?
Here's the answer I got by hours and hours of searching. I avoided using serialize since...well I don't understand how to use it. In JS I'm looping to find values in the table and making an array like this:
function getData(){
var checkArray = new Array();
$("#shopCart .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
checkArray.push(key);
checkArray.push(sel);
checkArray.push(q);
});
$.ajax({
type: "POST",
data: {ch: checkArray}
});
}
In my PHP is where I found a cool trick. Since I'm controlling the data in the array, I know how many values will be in it. The trick I found is "array_chunk" so for the 3 values I'm doing this:
if(isset($_POST['ch']) && (!empty($_POST['ch']))){
unset($_SESSION['check']);
$_SESSION['check'] = array_chunk($_POST['ch'], 3);
}
So I'm just clearing the session variable and adding the new values. That eliminates all the checking and clearing and all that. I'm sure there are better ways to do this but this method is short and works and that's what I'm looking for. Hope this helps someone!

How to create multidimensial arrays with PHP and access with jQuery?

So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.

Multidimensional array via ajax to php turns into null via json_decode

I have gathered data with jQuery, putten it into a multidimensional array, used JSON.stringify on it and passed it to PHP by use of AJAX, for some reason json_decode keeps on giving me a Syntax error, malformed JSON error.
Heres the JSON that gets passed on to the PHP
[\"foo\",\"foobar did the baz\",[[\"bar\",\"kg\",\"200\"],[\"baz\",\"l\",\"1337\"]]]
The weird thing is that i use JSON.stringify on the multidimensional array in JS. Heres how i put it together
var dataz = [];
var arrayContainingAll = [];
$("li", "#ingredientlist").each(function() {
var tempArray = [];
tempArray.push($(".ingredientname", this).text());
tempArray.push($(".unittext", this).text());
tempArray.push($(".amounttext", this).text());
arrayContainingAll.push(tempArray);
});
dataz.push($("h1").text());
dataz.push($("#method").val());
dataz.push(arrayContainingAll);
var json = JSON.stringify(dataz);
How can i make PHP parse the multidimensional array correctly?
I have fixed it by passing on 3 different stringified arrays, but its more the curiosity of why a multidimensional array fails
The PHP to show what happens is: var_dump(json_decode($_POST['ingredients']));
because it appearantly is important to show how i post the data, heres the JS to do the ajax request
$.ajax({
url: '/api/savenewrecipe.php',
type: 'POST',
data: 'ingredients=' + json + "&name=" + $("h1").text() + "&method=" + $("#method").val(),
success: function(result) {
if (result.ok == true) {
// #todo remove this for debugging purposes
//document.location.href = '/recipe/' + result.id;
}
else {
showError("Noget gik galt!", 2000);
}
}
});
If your server uses magic quotes, you'll need to remove them:
if (get_magic_quotes_gpc()) {
$_POST['ingredients'] = stripslashes($_POST['ingredients']);
}

Categories