Multidimensional Arrays via ajax to PHP - php

Ok seriously struggling here. I am having some problems trying to send a multdimensional array to PHP via ajax. Here's what I have been trying:
To simplify rather than copy paste a wall of code:
peoplearray[0] = [name] => 'john'
[age] => '28'
[sex] => 'Male'
peoplearray[1] = [name] => 'julie'
[age] => '20'
[sex] => 'Female'
main_array['item'] = 'x';
main_array['something'] = 'x';
main_array['another'] = 'x';
I want to get this to php via post. I figured I may aswell just join them together as I am multidimensional anyway thus :
main_array['peoplearray'] = peoplearray;
now to do the ajax:
// var data = JSON.stringify(main_array);
var send = $.ajax({
type: "POST",
cache: false,
url: "theurl",
data: {data:main_array} //I do change this `main_array` when using the above stringify!
});
send.done(function(msg) {
console.log(msg);
})
in PHP I am just doing the following right now:
$data= $_POST['data'];
print_r($data);
in firebug: (an empty string)
when I have the var data = JSON.stringify(main_array); uncommented I get the following: [][
if i add $data = json_decode($_POST['data']); to the php I get:
Array ( )
Basically the main_array I realise does not need to be an array and so I can get that stuff across no problem but what I need to do is get the peoplearray over so that I can do some foreach etc... with it in php. Any help would be much appreciated I am sure I am just being stupid!
EDIT: The reasoning behind this is that peoplearray could have 0 or 100 entries so I just need to get it to php so I can foreach it to do the DB inputs. If there is a better approach I would be very grateful to hear it as I am still pretty new to this.
EDIT: Thanks to Nicola's answer everything is passing fine except the important part which is mainarry.peoplearray - it is not appearing in the the return console.log and I cant access it in PHP. Any solutions on this or do I have to put the foreach intelligence in the javascript and just send everything individually?

First of all main_array is not an array but an object because in javascript there are no associative arrays and for this reason
main_array['peoplearray'] = peoplearray;
is equivalent to
main_array.peoplearray = peoplearray;
and you should declare main_array like this
var main_array = {};
then try to change your function like this:
var send = $.ajax({
type: "POST",
dataType: "json",
cache: false,
url: "theurl",
data: {data:main_array}
});
and server side
header('Content-type: application/json');
$data= $_POST['data'];
echo json_encode($data);

I got it to work by keeping the peoplearray seperate.
So I did as Nicola said and created mainarray as an object ie. declaring with curlies: {}
The peoplearray I left as an array ie declaring with [], however then name,age&sex fields I created as an object ie. {} and then .push() them into the the peoplearray.
Then the ajax looked as follows:
var send = $.ajax({
type: "POST",
dataType: "json",
cache: false,
url: "theurl",
data: {data:main_array, people:peoplearray}
});
then with the PHP everything is available in the $_POST, and if you
echo json_encode($people); //or whatever var name it is stored as in the php
the objects ie name,age,sex properties are shown in the
send.done(function(msg) {
console.log(msg);
})

Related

Can't return json array from PHP to jQuery AJAX

Problem
I am using AJAX jQuery with a dropdown to get some response from PHP. So far i wanted just one row from database, but now i want another array.
Current situation
front -
$.ajax({
type: "POST",
url: "project_details.php",
data: data_string,
cache: false,
success: function(data){
if(data){
var json = data;
obj = JSON.parse(json);
$("#project-name").text(obj.project_name);
$("#start-date").text(obj.start_date);
}
}
});
back -
$result=mysqli_query($db,"SELECT distinct project_name,start_date FROM `projects` WHERE a.supervisor_email = '$email' and a.project_id = '$project'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if($count==1){
echo json_encode(array("project_name" =>$row['project_name'],
"start_date" => $start->format("d M,Y"))); }
What I want -
I need another array returned from PHP -
$result_1=mysqli_query($db,"SELECT member_email FROM `projects` WHERE a.supervisor_email
$email' and a.project_id = '$project'");
$row_1=mysqli_fetch_array($result,MYSQLI_ASSOC);
so the final echo should be something like
if($count==1){
echo json_encode(array($row_1,"project_name" =>$row['project_name'],
"start_date" => $start->format("d M,Y"))); }
I can't figure out how to read this from jQuery
Note that table I'm using is at project_id, member_email level
First of all, specify the datatype as json.
This way you do not need..
var json = data;
obj = JSON.parse(json);
..and you can use the data variable directly. Also, depending on what you are doing with the AJAX data, it may be better to use .html() instead of .text().
In regards to your original question, I see that you have added $row_1 to your existing array but it will not work that way. I don't know what it contains, but seems to be an array. Since AJAX is expecting json format you need to have key=>value pairs. How about like this?
PHP:
$json_arr = array();
while ($row_1=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$email{'member_email'] = $row_1['member_email'];
}
if($count==1){
echo json_encode(array("member_email" =>$email,
"project_name" =>$row['project_name'],
"start_date" => $start->format("d M,Y")));
}
AJAX:
$.ajax({
type: "POST",
url: "project_details.php",
data: data_string,
dataType: "json",
cache: false,
success: function(data){
if(data){
$("#member_email").text(data.member_email);
$("#project-name").text(data.project_name);
$("#start-date").text(data.start_date);
}
}
});
I'm not exactly sure if I got your question right. But you would like to have $row_1 as additional array to be echoed, am i right? If so, Try this:
PHP
echo json_encode( array(
"row_1" => $row_1,
"project_name" =>$row['project_name'],
"start_date" => $start->format("d M,Y")
)
);
Then on your $.ajax
use data.row_1 , data.project_name, data.start_date to refer to your encoded value
Note: I would also like to recommend what #EternalHour said that you should use dataType: 'json' instead for a much cleaner approach, and it seems to be easier that way too.
Please tell me if my recommended code worked. If not would you please tell me the error that comes with it too.
Do you get what you want when you do a console.log(obj); ?
Cause there is no "project_name" inside
your SQL-Select
Regarding jQuery .. tried $.each?
$.each(obj, function(key, project)
{
...text(project.project_name);
});

Stock with sending data with jQuery to PHP file

I'm trying to send data via POST to PHP file..
$.get() - works fine, hovewer I couldn't tell the same about $.post() or $.ajax() with method post..
Here my code I wrote:
$('[name="update"]').click(function(){
tr = $(this).parents('tr');
u = [];
u["username"] = tr.find('[name="u[username]"]').val();
u["display_name"] = tr.find('[name="u[display_name]"]').val();
u["type"] = tr.find('[name="u[type]"]').val();
$.ajax({
type: "POST",
url: "../ajax-queries/update-user.php",
data: {update:u},
cache: false,
success: function(data){
alert(data);
}
});
});
And PHP file looks like:
<?php
print_r($_POST);
?>
Response I get:
Array(
)
Using latest jQuery lib... no ideas why not working.. any solutions you can offer?
Is that could be posible because of port:2014?
in case i tried and in :80 (same results)..
Because you aren't setting anything.
Try changing u to {}, like: u = {};
Array with key index is not an array, it's an object, try alert(typeof u).
sending an array with key index will fail in IE8.

jQuery.parseJSON trouble

I'm pretty unfamiliar with JSON, as I haven't used it too much and I'm trying to learn some of it.
So I have an ajax request that gives me this: [{"palvelu_id":"1","palvelu_nimi":"Meikkikoulutus","palvelu_kuvaus":"Kuvaus","palvelu_hinta":"10"}]
And I'm trying to use jQuery.parseJSON to use it on a page.
var palveluData = $.parseJSON(d);
$("#ajanvarausInfo").html(palveluData.palvelu_kuvaus+"<br>"+palveluData.palvelu_hinta);
But I get undefined as answer, what am I doing wrong here?
You should get the first element of the array:
$("#ajanvarausInfo").html(palveluData[0].palvelu_kuvaus+"<br>...");
If the array has more than 1 element you should iterate through the array, you can use jQuery $.each() utility function.
EDIT::
Wow, looks like ive kept the window open for to long before replying -.-
You have an outter array there, so you need to take that into account ( your php side might be not correct )
$("#ajanvarausInfo").html(palveluData[0].palvelu_kuvaus+"<br>"+palveluData[0].palvelu_hinta);
Usually you not need that when properly setting everything up
$.ajax ({
url: 'myurl',
type: 'POST',
data: { key_value pairs here },
dataType: 'json',
success: function(response){
$("#ajanvarausInfo").html(response.palvelu_kuvaus+"<br>"+response.palvelu_hinta);
});
});
On the php side
$response = array(
"palvelu_id" => "1",
"palvelu_nimi" => "Meikkikoulutus",
"palvelu_kuvaus" => "Kuvaus",
"palvelu_hinta" => "10"
);
echo json_encode($response);

How to post javascript data to PHP?

If I have a variable that needs to be posted to a PHP script without refreshing the page.
Is this possible? And if so, how?
My attempt using jQuery:
$.ajax({
url: "myphpfile.php",
type: "post",
data: json/array/whatever,
success: function(){ // trigger when request was successfull
window.location.href = 'somewhere'
}
})
How would I receive an array passed in my php script?
Use GM_xmlhttpRequest() to allow for cross-domain posts (which it will be in most scenarios).
Greasemonkey Script:
// ==UserScript==
// #name _Sending arbitrary data, demo
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #grant GM_xmlhttpRequest
// ==/UserScript==
var someArray = [1, 2, 3];
var serializedData = JSON.stringify (someArray);
GM_xmlhttpRequest ( {
method: "POST",
url: "http://SERVER.COM/PATH/ShowJSON_PostedData.php",
data: serializedData,
headers: {"Content-Type": "application/json"},
onload: function (response) {
console.log (response.responseText);
}
} );
ShowJSON_PostedData.php:
<?php
echo '<title>JSON data</title>';
echo '<h2>JSON post data:</h2><pre>';
$jsonData = json_decode($HTTP_RAW_POST_DATA);
print_r ($jsonData);
echo '</pre>';
?>
The console. will show:
<title>JSON data</title><h2>JSON post data:</h2><pre>Array
(
[0] => 1
[1] => 2
[2] => 3
)
</pre>
The accepted answer of this thread may be really useful since it shows a simple case : using jquery $.ajax to call a PHP function
My suggestion is : make something that works, then progressively add complexity until you reach your custom case. This way you feel much safer and you are aware of potential problems as they get in.
To pass an array from php to the client side, you may use echo json_encode($myArray); in your php script.
Hope this helps

how do I parse the POST data that gets sent to ajax?

I am sending a html form using jquery to ajax, When I send the form to my php file and use print_r($_POST) to see what got sent, this is the result:
Array
(
[data] => user_first_name=&user_last_name=&user_birthday_day=&user_birthday_month=&user_birthday_year=&user_addr_street=&user_ad
dr_street_no=&user_addr_city=&user_addr_zip=&user_addr_country=1&user_contact_phone=&user_contact_email=&user_knows_us_from=
)
Basically, I get what this is doing, but I am not quite sure what is the best approach to split this string into an array. I know how to use explode('&', $data), but it only explodes my string into an array with values, but numbered keys.
I need $key => $value to look like [user_first_name] => 'Peter' instead of [1] => 'user_first_name=Peter'
How do you solve this problem?
EDIT: This is my ajax code, but it works, so I think it won't really be neccessary here, but still ..
var formData = $('#form-registracia').serialize();
$.ajax({
url: '/ajax/registracia.php',
type: 'POST',
dataType: 'text',
data: {'data':formData},
success: function(data){
// something will be here
}
});
Instead of data: {'data': formData} all you need to do is data: formData
I see two things that are wrong:
you need to serialize the form data: $(form).serialize()
what you get on the other end is your normal $_POST array

Categories