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);
Related
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);
});
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.
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);
})
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
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.