how to convert a JSon object to an array in Javascript - php

I am returning array as
$array = array {
'id' => 1,
'name'=>krishna,
}
echo json_encode($array);
exit;
from an ajax call
How can I convert this json value to java script array?
This is my actual data
var data = [{
"candidate_notes_id":"1",
"candidate_id":"38",
"subject":"test",
"description":"t‌estestsete\netestes\n\n\nsteetet",
"private":"0",
"created_date":"2012-09-14 11:55:13",
"updated_date":"2012-09-14 11:55:13",
"updated_by":"admin"
}]
var newArray = jQuery.parseJSON(data);
alert(newArray);
return false;
result :
var newArray = JSON.stringify(data);
var date_split = newArray.substr(1,newArray.length-2);
var newData = date_split.replace('\n','<br>');
var newArray = $.parseJSON(newData);
alert(newArray.candidate_notes_id);
alert(newArray.candidate_id);
alert(newArray.subject);
alert(newArray.description);

If you are using jQuery then you can use jQuery.parseJSON(YOUR_AJAX_RESPONSE_DATA); which will convert json to JS object
Link: http://api.jquery.com/jQuery.parseJSON/

Please look at an answered question ...
You will find how to convert a json to an array.
JSON to javaScript array
var array = [];
$.each(JSONObject, function(i, obj) {
array.push([obj.id.value, obj.name.value]);
});

You can parse it using
obj = JSON.parse(responseData); // replace `responseData` with your XHR response variable name
in your success callback function. Then convert it an array as follows
var myArray=[];
myArray[0]=obj.id;
myArray[1]=obj.name;
but first of all your
$array = array {
'id' => 1,
'name'=>krishna,
};
should be
$array = array (
'id' => 1,
'name'=>'krishna'
);
DEMO.

Related

Can't print the json from ajax post using json_decode

I am using ajax to post data to a php script for work to be done... Basically, I'm taking all the form variabes, and creating json... Then taking this json and sending it to the controller script:
function createJSON() {
jsonObj = [];
$("input[class=form-control]").each(function() {
var id = $(this).attr("id");
var value = $(this).val();
item = {}
item [id] = value;
jsonObj.push(item);
});
jsonData = JSON.stringify(jsonObj);
var request = $.ajax({
url: "../../../../ajax/signupController.php",
type: "POST",
data: jsonData,
dataType: "html"
});
request.done(function( msg ) {
console.log(msg);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
My code gets to the php script fine, and when I use "print_r" in php to print the output, I get this:
Array
(
[0] => stdClass Object
(
[mail-firstname] => FName
)
[1] => stdClass Object
(
[mail-lastname] => Lname
)
)
My problem is, I can't GET AT the elements... I have tried:
$data = json_decode(file_get_contents('php://input'));
foreach ($data as $key => $value) {
print "<p>$key | $value</p>";
}
but I can't get at the array elements... I get an error... What am I missing about accessing the array after decoding the file contents?
Thanks.
Update:
Modified foreach:
foreach($data as $key=>$value){
print $value->ccyear;//now I can get at individual elements
}
BUT ANY VALUE THAT HAS A DASH IS CAUSING THE SCRIPT TO FAIL... For example, if the name is "mail-firstname" PHP thinks it's mail AND firstname...
The problem is that your values are nested an extra level in your data. And they each have different keys, so it's hard to get at them. It would be better if you use the id as the keys of the top-level array, rather than nesting them:
jsonObj = {};
$("input[class=form-control]").each(function() {
var id = this.id
var value = this.value;
jsonObj[id] = value;
});
Then you should change your PHP to use the second argument to json_decode(), so you get an associative array instead of a stdClass object:
$data = json_decode(file_get_contents('php://input', true));
I'm not really sure why you need to send JSON. Why not just use:
data: jsonObj;
Then you can access the inputs as $_POST['mail-firstname'], etc.

What is the simplest method of programmatically adding data to JSON?

For a PHP/HTML page what is the simplest method of adding data to JSON?
Should I be using PHP, JS, or jQuery?
I've tried different lots of different methods found online, but I can't get any to work. I've tried all of these but I can't get it quite right.
var myObject = new Object();
JSON.stringify()
JSON.parse()
$.extend();
.push()
.concat()
I have this JSON file loaded
{"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"}
]
}
I want to programmatically add
var THISNEWCOMMENT = 'jkl;
{"thecomment": THISNEWCOMMENT}
so that the JSON variable will be
{"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"},
{"thecomment": "jkl"}
]
}
///////////////////
Edit after answer
//////////////////
This is the ajax in my index.php file I used to call the PHP function (in its separate file):
function commentSaveAction ()
{
var mytext = $(".mycommentinput").val();
mytext = mytext.replace("\"","'");
$.ajax({
url: 'php/commentwrite.php',
data: { thePhpData: mytext },
success: function (response) {
}
});
}
And this is the finished PHP function I used with the help of deceze:
<?php
function writeFunction ()
{
$filename = '../database/comments.txt';
$arr = json_decode(file_get_contents($filename),true);
$myData = $_GET['thePhpData'];
$arr['commentobjects'][] = array('thecomment' => $myData);
$json = json_encode($arr);
$fileWrite=fopen($filename,"w+");
fwrite($fileWrite,$json);
fclose($fileWrite);
}
writeFunction ();
?>
//////////////////////
with JS and not PHP
/////////////////////
var myJsonData;
function getCommentData ()
{
$.getJSON('database/comments.txt', function(data) {
myJsonData = data;
var count = data.commentobjects.length;
for (i=0;i<count;i++) {
$(".commentbox ul").append("<li>"+data.commentobjects[i].thecomment+"</li>");
}
});
}
function commentSaveAction ()
{
var mytext = $(".mycommentinput").val();
mytext = mytext.replace("\"","'");
myJsonData.commentobjects.push({"thecomment": mytext});
var count = myJsonData.commentobjects.length;
$(".commentbox ul").append("<li>"+myJsonData.commentobjects[count-1].thecomment+"</li>");
}
Whichever language you do it in, you have to parse the JSON string into an object/array, modify it, then encode it back into a JSON string. Don't attempt any direct string manipulation of the JSON string. PHP example:
$arr = json_decode($json, true);
$arr['commentobjects'][] = array('thecomment' => 'jkl');
$json = json_encode($arr);
Whether to do this in Javascript or PHP or elsewhere depends on when/why/where you need to do this; that's impossible to say without knowing more about the use case.
Try with json_encode and json_decode PHP functions.
//work on arrays in php
$arr = array('sth1', 'sth2');
//here you have json
$jsonStr = json_encode($arr);
//array again
$arrAgain = json_decode($jsonStr);
$arrAgain[] = 'sth3';
//json again
$jsonAgain = json_encode($arrAgain)
Just do it in javascript:
var x = {"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"}
]
};
x.commentobjects.push({"thecomment": "jkl"});
var THISNEWCOMMENT = 'jkl',
myObj = JSON.parse(rawJson),
newComment = {"thecomment": THISNEWCOMMENT};
myObj.commentobjects.push(newComment);
var serialized = JSON.stringify(myObj);
//send the updated JSON to your controller
Parse the object, access the commentobject list inside of it, push the new comment in the list and then serialize the updated object again.

convert a value from json_decode to a string

how do i convert my value from json_decode to string so i can pass in a the string value to check if an email exists here is my code.
my json is in this format:
{email:'test#test.com' }
PHP:
$var = json_decode($_REQUEST["email"], true);
$result = $membership->CheckEmailAddress($var); // get $var to become a string
It looks pretty ugly im just starting php and Im not getting very far aye lol.
jquery:
$('#checkemail').click(function () {
var json = {
email: $('#email').val()
};
$.post('http://' + location.host + '/buyme/include/getemailaddress.php', {
'email': 'test#yahoo.co.nz'
}, function (res) {
var obj = JSON.parse(res);
alert(obj.message)
});
});
also how do I put my json variable in my $.post function cose thats the value I want to put there
what value in $_REQUEST["email"] if it's a json value you are showing above then try
your $var is a json object you can fetch email value like not use $var it's an array
tried this :-
$val = json_encode(array('email' =>'test#test.com'));
echo $val; //output {"email":"test#test.com"}
$var = json_decode($val, true);
print_r($var); // output Array ( [email] => test#test.com )
echo $var['email']; //output test#test.com

Parse json data into variables and submit to a function on each iteration

I created a php script that generates the json response
this is the example of the output:
[[],{"idgps_unit":"2","lat":"40","lon":"40","name":"ML350","notes":"Andrew","dt":"2012-10-29 19:43:09","serial":"3602152","speed":"44","odometer":"208.49"},{"idgps_unit":"1","lat":"42","lon":"39","name":"unit1","notes":"fake unit 1","dt":"2012-10-18 18:16:37","serial":"12345","speed":"0","odometer":"0.16"}]
This is how I form the response in PHP:
$data[] = array();
foreach ($list->arrayList as $key => $value) {
$unit = new Unit();
$unit = $value;
//create array for json output
$data[] = array('idgps_unit' => $unit->idgps_unit, 'lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes,
'dt' => $unit->dt, 'serial' => $unit->serial, 'speed' => $unit->speed,
'odometer' => $unit->odometer);
}
echo json_encode($data);
Now, in JS I did this:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
success : function(data) {
var jsonData = JSON.parse(data);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: START
var C_longitude = 0;
var C_name = 0;
var C_idgps_unit = 0;
var C_serial = 0;
var C_speed= 0;
var C_notes= 0;
var C_dt = 0;
var C_time = 0;
var C_odometer = 0;
initialize(C_longitude,C_name,C_idgps_unit, C_serial,C_speed, C_notes, C_dt, C_time, C_odometer);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: END
}
});
});
}
I need to parse the json reponce into values
Assuming that JSON.parse(data) only gets the associative array in the JSON response, you should be able to get the values in the JSON data like so:
var i = 1;
var C_longitude = jsonData[i]["lon"];
var C_name = jsonData[i]["name"];
Assuming that the first empty array is not removed by JSON.parse(), i = 1 would get the first batch of data and i = 2 would get the second.
The parsed JSON behaves the same way as if it was defined in JavaScript
If you put dataType: "json" in the ajax settings it will return you a json object than you don't need to parse it again. So this would look like:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
dataType: "json"
success : function(data) {
}
});
});
}
However you could also use your own option but than just use the parseJSON function so var jsonData = jQuery.parseJSON(data);

How to Read JSON Post Object from PHP

I have a problem with "JSON, JQuery, Ajax, JavaScript and PHP".
I have code to save data. This code send data(JSON) via JQuery Ajax to proses.php. The code for save data shown below :
$("#save").click(function(){
var id_promotion_code = $("#id_promotion_code").val();
var i=0;
var y=0;
var datarule = {
rule: []
};
$('#tablerule tr').each(function() {
if(y!=0)
{
var id_pricing_rule = $(this).find("td").eq(0).html();
var date_book_start = $(this).find("td").eq(3).html();
var date_book_end = $(this).find("td").eq(4).html();
var date_book_no_end = 0;
if(date_book_end=="NO END")
{
date_book_no_end = 1;
date_book_end = $(this).find("td").eq(3).html();
}
var date_reservation_start = $(this).find("td").eq(5).html();
var date_reservation_end = $(this).find("td").eq(6).html();
var date_reservation_no_end = 0;
if(date_reservation_end=="NO END")
{
date_reservation_no_end = 1;
date_reservation_end = $(this).find("td").eq(5).html();
}
datarule.rule.push({
"id_promotion_code" : id_promotion_code,
"id_pricing_rule" : id_pricing_rule,
"date_book_start" : date_book_start,
"date_book_end" : date_book_end,
"date_book_no_end" : date_book_no_end,
"date_reservation_start" : date_reservation_start,
"date_reservation_end" : date_reservation_end,
"date_reservation_no_end" : date_reservation_no_end
});
i++;
}
y++;
});
$.ajax({
type:"POST",
url:"proses.php",
data:"aksi=tambahrule&datarule=" + datarule,
success: function(data){
alert("Sukses " + data);
},
error: function(){
alert("Error" + data);
}
});
});
And the code in proses.php shown below :
if($aksi=='tambahrule'){
$datarule = $_POST['datarule'];
$jsone = json_decode($datarule, true);
print_r($jsone);
}
But i can't get the json data with proses.php code. Please help me how to read json object that send via jquery ajax with php? Actually i want to looping the json for get the data.
------------------------MY NEW EDIT-----------------------------
Thanks for your response...
I already modify my code. And running but not well yet.
This is the response when i check using Firebug :
Array
(
[rule] => Array
(
[0] => Array
(
[id_promotion_code] =>
[id_pricing_rule] => BN2
[date_book_start] => 2012-03-01
[date_book_end] => 2012-03-01
[date_book_no_end] => 1
[date_reservation_start] => 2012-03-09
[date_reservation_end] => 2012-03-09
[date_reservation_no_end] => 1
)
[1] => Array
(
[id_promotion_code] =>
[id_pricing_rule] => EB10%
[date_book_start] => 2012-03-15
[date_book_end] => 2012-03-15
[date_book_no_end] => 1
[date_reservation_start] => 2012-03-31
[date_reservation_end] => 2012-03-31
[date_reservation_no_end] => 1
)
)
)
And this is the PHP code for get the data :
$datarule = $_POST;
$rulenya="";
foreach($datarule->rule as $doc)
{
$rulenya=$rulenya.$doc->id_pricing_rule;
}
print_r($datarule);
But get the error. My question is?
1. The data is in Array, should i change to Object? And how?
2. How can i get that data in PHP?
I think you should send the data in another way:
data: { aksi: "tambahrule", datarule: datarule},
as datarule is a complex object and can't be appended to a querystring. Serverside your code should be ok
Try using dataType: 'json', in your ajax call.
The answer of Nicola Peluchetti is correct, datarule is NOT a querystring, you need to send it as he explained.
Furthermore, having your data as an array is fine. But you need to alter your server code to handle it as such:
$datarule = $_POST['datarule'];
$rulenya = '';
foreach ($datarule['rule'] as $doc) {
$rulenya .= $doc['id_pricing_rule'];
}
or something along those lines...
You don't json_decode. You can try it;
PHP Code:
$datarule = $_POST['datarule'];
$datarule = implode(',', $datarule);
print_r($datarule);
$datarule is a array

Categories