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

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

Related

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);

2-d arrays PHP->JSON->jQuery

I have a 2-dimensional array ( $array = array(array()) ) that I put through json_encode in php, and get something like...
[["209","2008-03-06","Technical Writing 1","009"],["210","2008-03-06","Technical Writing 2","005"]]
When I go to use $.parseJSON() on this string, it doesn't give me anything. Any thoughts?
EDIT
My jQuery looks like:
$.ajax({
type: 'POST',
url: "stat_fetch.php",
data: { },
dataType: 'html',
success: function(data) {
$parsed = $.parseJSON(data);
},
async: false
});
Try indexing into the data you get back - for example
$.getJSON("/myprog/php",function (data) { alert(data[0][0]; });
will pop up an alert box with the value "209" from your array example above.
Sometimes $.parseJSON doesn't work as I expect, I got problems in past with this. I think you can use simple javascript but the function JSON.parse is also buggy.
Read this about the JSON.parse: http://caniuse.com/json
I suggest you to use a library, like this:
https://github.com/douglascrockford/JSON-js
Try json2.js or json_parse.js, they work great and are crossbrowser.

Multidimensional Arrays via ajax to 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);
})

Get values from array from php ajax post

I am currently working on a php project with the user of ajax. I need to populate values from a database into an html drop down box and I want to do this from an ajax post.
For all the other ajax so far in the project I have been using $.post but I do not need to post anything to the php script as it is just going to retrieve everything from the database. what I need to do is the php script retrieves the information from a database and populates the information into an array and then return the array to the calling php script that calls that ajax.
Is the array idea the best idea, if so how do I get the contents of the array from the ajax, or is there a better way and how do I do the ajax call if I am not doing a post of anything.
Thanks for any help you can provide.
The easiest way to do what you're describing is using JSON with your jQuery Ajax request, like so:
// PHP side
<?php
// Do your database query, and then echo out your desired data like so:
echo json_encode(array(
'test' => 'your data',
'test2' => array('you can also use', 'arrays'),
'test3' => array('or' => 'keyed arrays'),
));
die(); // don't echo anything other JSON, or you'll get errors
?>
// Javascript side
$.post("url.com", post_data, function(json)
{
// Do something with your data here:
alert(json.test);
alert(json.test2[1]);
alert(json.test3["or"]);
}, "json");
$.ajax({
url: "your_script.php",
global: false,
type: "POST",
data: {},
dataType: "json",
async:false,
success: function(results){
//append your json results to your DOM
$('#some_div').html('');
for(var i = 0; i < results.length; i ++)
{
$('#some_div').append('<p>' + results[i].html + '</p>');
}
}
});
and your PHP will need to json_encode the results...
die(json_encode(array(array('html' => 'first'), array('html' => 'second'))));

Jquery Ajax Returned Array - how to handle in Javascript

If someone could assist me please. I'm doing a jquery Ajax post, for some reason the Json object isn't working so just returning a php array instead
$.post
(
"classes/RegisterUser.php",
$("#frmRegistration").serialize(),
function(data)
{
alert(data);
}
);
The data is returned to Javascript 100% as
array
(
[key]=>value
[Name] => SomeOneName
[Surname] => SomeOneSurName
)
How would i go about getting the value of Surname in Javascript?
Thanks for your assistance?
Regards
Expanding on The MYYN's answer, after you get your script to return JSON, you must specify that you're receiving JSON and act accordingly. You can do this with .ajax():
$.ajax({
type: 'post',
url: 'classes/RegisterUser.php',
data: $("#frmRegistration").serialize(),
dataType: 'json',
success: function(obj) {
// This alerts SomeOneSurName
alert(obj.Surname);
}
});
Maybe your PHP script should return json (right now it seem to return something like var_dump($some_ary);. A proper way to do this is via php's json_encode.

Categories