JSON format issue in JavaScript - javascript

Following is my JavaScript code to get JSON data:
$(document).ready(function()
{
$.support.cors = true;
$.getJSON('http://example.com/root_dir/test_json.php', function(data1)
{
alert("data1= "+data1);
});
});
but the above alert shows me JSON in following format-
If I hit my php script URL in browser, it shows JSON data in expected formate as shown below-
[{"name":"AB","std":"7","number":"82"},{"name":"CD","std":"9","number":"90"},{"name":"PQ","std":"12","number":"79"}]
Following is my test_json.php code-
<?php
//Create an array
$json_response = array();
$row_array['name'] = 'AB';
$row_array['std'] = '7';
$row_array['number'] = '82';
array_push($json_response,$row_array);
$row_array['name'] = 'CD';
$row_array['std'] ='9';
$row_array['number'] = '90';
array_push($json_response,$row_array);
$row_array['name'] = 'PQ';
$row_array['std'] = '12';
$row_array['number'] = '79';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>

getJSON decodes the JSON into a JavaScript data structure.
Concatenating it with a string will implicitly call toString() on it. That will turn arrays in to a comma-seperated format and plain objects into "[Object object]".
Nothing is going wrong. That is the expected behaviour.
If you want to see the data in JSON format, then use JSON.stringify(data) or use .ajax instead of .getJSON and access the raw text data in the jqXHR object.

Related

Accessing json data passed in string form

I am passing data from php in json format, how do I access it?
This is the result:
{"solctype":"Long Term Agreement","checkbox":"1","prnumber":"356363563"}
I have tried
$.post("getgrid?id="+id,
{
},
function(data, status){
console.log(data.solctype);
});
This always returns undefined
You need to parse the string data and convert it to a JavaScript object.
Use something like this:
var stringData = {"solctype":"Long Term Agreement","checkbox":"1","prnumber":"356363563"};
var parsedData = JSON.parse(stringData);
console.log(parsedData.solctype)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Getting array values in php from jQuery post

I am trying to send an array from jQuery post to PHP.
But I am not getting any values with the below code.
Could anyone help ?
jQuery
$("body").on("click", ".js-form",function(event){
var arr = [];
i = 0;
$('.addcolor').each(function() {
if( $(this).text()=="done"){
arr[i++]= $(this).data('request-id');
}
});
alert(arr);
$.post("../ajax/save_Request.php", {requestids:arr, action:'save_request' })
});
alert(arr)-> prints 11,24,35 (eg)
But I am not getting any values in the following PHP variable.
PHP
$ids = ( isset($_POST['requestids']) ) ? $_POST['requestids'] : 0;
Try with this 'choices[]'
$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } );
See more in : jQuery.post and search the key "Pass arrays of data to the server". I think that you missed []. Try it and return me the result.
Try converting the array to a JSON string first, using
var json = JSON.stringify(arr);
Now that it's a JSON string, you can simply pass it through a hidden field. Then, once you get the string back from the PHP page, you can turn it back into an array using
$array = json_decode($arr, true);
where $arr is the JSON string.
I had a similar problem with trying to pass an array from JQuery to another PHP page and this worked for me.

JQuery unable to parse JSON string created by json_encode

I am currently in a bind, JQuery is unable to parse the following json strings
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
The above strings when parse through JSON.parse create the following arror:
SyntaxError: JSON.parse: unexpected non-whitespace character after
JSON data at line 1 column 112 of the JSON data
The PHP code which creates the string above is this:
public function getCustomerSuggestions($name){
$customers = $this->model->where('name','LIKE','%'.$name.'%')->show();
if(count($customers)>=1){
foreach($customers as $customer){
$list[] = ['value' => ucfirst($customer->name),'data' => $customer->id];
}
}
else{
$list[] = ['value' => 'No Customers Found', 'data'=> NULL];
}
$full_list['query'] = 'Unit';
$full_list['suggestions'] = $list;
return json_encode($full_list);
}
As you can see I am using the function json_encode to create the JSOn string so there should be no issue but it still doesnt work.
Edit
The json is sent using an autocomplete tool called DevBridge Autocomplete which takes the JSON strings and creates a suggestion list. The code I am using is
$('input[name=\"customer\"]').devbridgeAutocomplete({
serviceUrl: '".SITE_PATH."/ajax/admin/quotes/getcustomer',
minChars: 1,
onSearchStart: function (query){
var searchinput = $(this).val();
$('.autocomplete-suggestions').html('Searching: '+searchinput);
},
onSelect: function(suggestion){
var selection = $(this).val(suggestion.value);
$('input[name=\"customerid\"]').val(suggestion.data);
$.get('".SITE_PATH."/ajax/admin/quotes/getcustomerdetails',{id: suggestion.data},
function(response){
var obj = $.parseJSON(response);
$.each(obj, function(key, value){
$('#'+key).val(value);
});
});
}
});
It seems you have two JSON objects after each other. That's simply invalid. There can only be a single value at the root of a JSON "document". If you want to send down multiple objects, you need to put them in an array.
It seems getCustomerSuggestions is called multiple times and the return value of each call is returned to the client. Instead, the method should return an array, the caller should collect the return values in an array and JSON encode that array.
Well, your JSON string is NOT valid.
It should be,
[
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
,
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
]
But as Felix Kling said, check your PHP code.

php decode json array

I have a php page that receives a json object from javascript page, but i was not able to decode the json in php. How to decode the json and store in php such that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; in php ?
after removing "myString = JSON.stringify(myObject);"
echo $value; outputs "Array"
echo $value[0]; outputs nothing
echo $value->{"key"}; outputs nothing either
how can i actually get the array contents?
javascript:
var mon=[1,2,34,5,2];
var tue=[2,1,34,5,2];
var wed=[8,1,34,5,2];
var myObject = {'key' :'value','key2':'value','key3':'value'};
myObject.key = mon;
myObject.key2 = tue;
myObject.key3 = wed;
myString = JSON.stringify(myObject); //this line removed
var jsonString = JSON.stringify(myObject);
$.ajax({
type: "POST",
url: "n3.php",
data: {data : jsonString},
cache: false,
success: function(aaa){
alert("OK");
$("#pageContent").html(aaa);
}
});
php:
<?php
$value = json_decode($_POST['data']);
echo $value; //this echos the whole json object
echo $value->{"key"}; //this outputs nothing
?>
You are JSON encoding your data twice on the Javascript side. When you call json_encode in PHP once, you get a JSON encoded object back. That's why echo $value outputs the whole string. If it was a PHP array at this point it would output "Array" or an error in case it was an object, it would not output the whole content.
Either json_decode it again, or don't double encode it in Javascript.

How could I JSON.parse nested object inside array

I'm trying to pass this structure on a PHP/Ajax response:
{"asn":"167", "jte":"[[1381547700000,0.0], [1381548600000,0.0]]", "visitas":"[{x:1380596400000,text:'HELLO WORLD.',title:'X'}]"}
But JSON.parse returns an error.
SyntaxError: JSON.parse: expected property name or '}'
Without the "visitas" object everything runs fine. Is it possible to "nest" as this?
UPDATE:
Ajax Part:
$.ajax({
type: 'post',
url: 'cxxx.php',
data: { asn: asn },
success: function(p){
p = JSON.parse(p);
jusante=JSON.parse(p.jusante);
montante=JSON.parse(p.montante);
vazao=JSON.parse(p.vazao);
minima=JSON.parse(p.minima);
fator=JSON.parse(p.fator);
visitas=JSON.parse(p.visitas)
and PHP part:
$v="[";
while(odbc_fetch_row($res)){
$datavisita = odbc_result($res, "DATA_VISITA");
$descricaovisita = odbc_result($res, "DESCRICAO_VISITA");
$login = odbc_result($res, "LOGIN");
$descricaomotivo = odbc_result($res, "DESCRICAO_MOTIVO");
$id_motivo=odbc_result($res, "ID_MOTIVO");
$datavisita=date("U", strtotime($datavisita))*1000;
$descricaovisita=preg_replace("/\r|\n/", "", $descricaovisita);
$v.="{x:$datavisita,text:'$descricaovisita',title:'$id_motivo'}, ";
}
$v=rtrim($v,", ")."]";
echo "{\"asn\": \"$asn\", \"description\": \"$description\", \"jusante\": \"$o\", \"montante\": \"$m\", \"vazao\": \"$f\", \"minima\": \"$mn\", \"fator\": \"$fp\", \"visitas\": \"$v\" }";
the Json you are using is valid, I checked it on JSONLint, so your problem might be with serialization, just make sure your "visitas" object is serialized correctly because the problem might be happening because it's the only member with an object value inside
Remove the quotes around the visitas array:
var json = JSON.parse('{"asn": "167","jte": "[[1381547700000,0.0], [1381548600000,0.0]]", "visitas": [{"x": "1380596400000", "text":"HELLOWORLD.","title":"X"}]}');
While the outermost JSON object looks fine, there might be a problem with the nested one!
If you are trying to parse the nested JSON element "visitas" you might have a problem in the fact that your property names (e.g. x, text and title) are not enclosed in quotation marks ("). This is of course a bit tricky since you are trying to include the visitas element as a string.
A solution might be to include the visitas element as a proper JSON element instead.
You need to escape the single quotes. I imagine you are surrounding the above in single quotes when you pass it to JSON.parse.
The below works.
JSON.parse('{"asn":"167", "jte":"[[1381547700000,0.0], [1381548600000,0.0]]", "visitas":"[{x:1380596400000,text:\'HELLO WORLD.\',title:\'X\'}]"}');
Note the slashes before the single quotes inside the string.
I would do the following:
var jsondata = {
"asn": "167",
"jte": "[[1381547700000,0.0], [1381548600000,0.0]]",
"visitas": "[{x:1380596400000,text:'HELLO WORLD.',title:'X'}]"
};
jsondata = JSON.stringify(jsondata);
then send it to php
var postdata = { data : jsondata};
var url = "<?php echo base_url(); ?>"+"test";
$.post(url, postdata, function(result){
console.log(result);
});
sice your php result is echoed the wrong way you should fix that first. Create arrays so that you can easily use the JSON_ENCODE function like so:
$array = array(
"asn" => "test_asn",
"description" => "description_test",
"jusante" => "jusante_test",
"montante" => "montante_test",
"vazao" => "vazao_test",
"minima" => "minima_test",
"fator" => "fator_test",
"visitas" => "visitas_test"
);
$json = json_encode($array);
echo $json;

Categories

Resources