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.
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'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);
I am new to JQuery and the whole JQuery to PHP back to JQuery process.
So i have a simple ajax JQuery script:
$.ajax({
type: "POST",
url: "includes/calc.php",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
This goes to a PHP script and then I return a value, using a simple echo
echo $newprice;
The success function above uses this as 'data'. This all works and is fine.
But what if I want to return more than one value.
I think I can used json_encode();
As I understand it something like:
$dataset = array($var1, var2, var3);
echo json_encode($dataset);
But say I have two values, how do i put them both into the JSON and then how do I split them on the other end.
So say 'data' is an array, how do I tell JQuery to split it?
Sorry if this is simple
If you specify the dataType option for .ajax() as json, jQuery will automatically parse the JSON string returned by the call into an appropriate javascript object/array.
So your call might look like this:
$.ajax({
type: "POST",
url: "includes/calc.php",
dataType: "json",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
Now, let's say the response from your PHP script is a JSON string representing an object like this:
{"key1":"value1","key2":"value2"}
In your success handler you can simply access this as an object like this:
success: function(data){
alert(data.key1);
alert(data.key2);
}
Or, if the returned JSON string represents an array like this:
["value1","value2"]
Then you can access the array values in the success handler like this:
success: function(data){
alert(data[0]);
alert(data[1]);
}
If you do not want to add the dataType option, you can also opt to manually parse the returned JSON string into an object/array like this:
success: function(data){
var dataObj = JSON.parse(data);
alert(dataObj.key1);
alert(dataObj.key2);
}
$.ajax({
type: "POST",
url: "includes/calc.php",
datatype : 'json',
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data.firstvalue);
alert(data.secondvalue);
}
})
please look at that datatype. now the respose need to be json.
In your php user json_encode instead of echo.
$firstvalue = 'your first value';
$secondvalue = 'your second value';
echo json_encode(array('firstvalue' => $firstvalue,'secondvalue' => $secondvalue));
There are many ways to organize data in a JSON object. The simplest is to return a linear array of strings or numbers. Use http://jsonlint.com/ to test your data to see if it's valid JSON, or just feed a PHP array (linear or associative) into json_encode.
If data is a JSON linear array, you can treat it like any other JavaScript array in your success callback:
var first = data[0]; // first element
var second = data[1]; // second element
implode your php variables with a symbol or any custom data
like
$var[0] = '1st variable';
$var[1] = '2nd variable';
$var[2] = '3rd variable';
echo implode('_SPLIT_',$var);
Now in jquery success function
split the response with 'SPLIT'
as
var response = data.responseText.split('_SPLIT_');
var variable1 = response[0];
var variable2 = response[1];
var variable3 = response[2];
and assign as your wish
I want to manipulate a PHParray in javascript. This is the code i'm using.
Array.php
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
?>
fx_funciones.js
/*Pre-sentences*/
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
}
});
This is what I want to do but it's not working.
I think , the answer for above question is already addressed in below link. please check them out.
Get data from php array - AJAX - jQuery
I hope it will help you
Try this:
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
echo json_encode($sentido);
And:
$.getJSON('array.php', function(sentido) {
console.log(sentido);
});
You'll need to return the array from your PHP code as JSON, using the json_encode function. Then, in your jQuery code, specify a json dataType so that it's implicitly converted and passed to the callback function as an array:
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
},
dataType: 'json'
});
Use the standard JSON notation. It serializes objects and arrays. Then print it, fetch it on the client and parse it.
On the server:
echo json_encode($sentido);
For more on PHP's json_encode: http://php.net/manual/de/function.json-encode.php
On the client, this is specially easy if you use the jQuery function for ajax that expect JSON-encoded objects, and parses them for you:
$.getJSON('address/to/your/php/file.php', function(sentidos) {
alert(sentidos[0]); // It will alert "ver"
alert(sentidos[1]); // It will alert "tocar"
});
It uses GET but this most probably what you need.
For more on jQuery's $.getJSON: http://api.jquery.com/jQuery.getJSON/
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.