get error when json_decode string from ajax post - javascript

I try send string to controller, the string is json format, when send to controller, i get error and can't decode my json string in that controller. I try to encode first in my controller, but still get error. And the error is
"json_decode() expects parameter 1 to be string, array given",
exception: "ErrorException",
here in my json string
"{ "data" :
[{
"id": "TNI01",
"jenis_bayar": "TUNAI",
"no_kartu": "kosong",
"nominal": "10000",
"seq": "1"
} ,
{
"id": "DEB01",
"jenis_bayar": "DEBIT BCA",
"no_kartu": "786382432432",
"nominal": "20000",
"seq": "2"
}]
}"
here the controller
public function ArrayPostToTablePembayaran(Request $request)
{
$data = json_decode($request->datajson, true);
foreach ($data->data as $datas)
{
$id = $datas->id;
$jenisbayar = $datas->jenis_bayar;
$nokartu = "";
if($datas->no_kartu == "kosong")
{
$nokartu ="";
}
$nominal = $datas->nominal;
$seq = $data->seq;
$this->PosToTablePembayaran1($id , $jenisbayar , $nokartu , $nominal , $seq);
}
}
and here the ajax script for parse json string to controller
function PembayaranKeDatabase1(arraystring)
{
$.ajax(
{
type : "POST",
url : "{{ url('/trx_bayar') }}",
data : { datajson : JSON.parse(arraydata) } ,
dataType: "json",
success: function(data){
},
error: function() {
}
});
}
thanks before

The main issue in your code that you try to decode json twice: in client js code and on server.
Let's inspect what you do:
JS function PembayaranKeDatabase1(arraystring) has an argument of type string, I presume. I also presume that arraystring is a JSON-string. So, you decode JSON-string to object with
JSON.parse(arraydata)
// btw shouldn't it be
//JSON.parse(arraystring)
So, here you send some plain object to server, not json.
Next, on server you try to decode again. But you receive an array in $request->datajson, as json is already decoded on client-side.
So, you can choose between two options:
Remove JSON.parse:
data : { datajson : arraydata },
and use json_decode on server.
Remove json_decode($request->datajson, true) on server. Iterate over your data as
// as $request->datajson is an array
foreach ($request->datajson['data'] as $datas) {
// use [] notation as you work with array, not object
echo $datas['id'];
}

Related

Can't access JSON Object no matter what i'm trying

So i have this JSON Structure, which i want to access:
data { payload: "{"state":{"reported":{"measuredata":{…
JSON.parse doesnt work, neither does JSON.stringify.
i only can access payload, if i go any further, i receive error or undefined:
data.payload // works
data.payload["state"] //undefined
data.payload.state // undefined
data.payload[0].state // undefined
data.payload[0]["state"] // undefined
what am i doing wrong?
the thing that i can see is that you have a bad format on your json data { payload: "{"state":{"reported":{"measuredata":{…
it hspuld be witouth the double quote that be after the word payload payload: "{"state"
you have to have something like this
payload: {"state"
You just need to use JSON.parse for payload json string value.
JSON.parse(data.payload).state;
Sample code for parsing.
var data = {
"logged_in":true,
"town":"Dublin",
"state":"Ohio",
"country":"USA",
"products":
{
"pic_id":"1500",
"description":"Picture of a computer",
"localion":"img.cloudimages.us/2012/06/02/computer.jpg",
"type":"jpg",
"childrenimages":
{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
}
}
};
var data1 = JSON.stringify(data);
var data_final = JSON.parse(data1);
console.log(data_final.products.pic_id);

pass array of numbers from ajax to controller

I know this is a popular topic and I've tried all of the solutions I could find already out there to no avail. I've used all the solutions included for this questions: Pass a List from javascript to controller. I've simplified my test to ridiculously simple. I get into the controller but my controller input param is {int[0]}. I confirmed my array data looks good in the JavaScript and ajax call.
Can anyone please tell me what I am missing?
JavaScript Code
var selectedIds = [];
selectedIds.push(565);
selectedIds.push(573);
selectedIds.push(571);
// selectedIds = [565, 573, 571]
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
data: { "ids": JSON.stringify(selectedIds) },
//data: { "ids": selectedIds},
//data: { ids: selectedIds},
url: "api/services/getbuildingsbyid",
success: function (result) {
return result;
}
});
Controller Code
[HttpPost]
public bool GetBuildingsById(int[] ids)
{
var lookAtIds = ids; // {int[0]}
return true;
}
By using JSON.stringify(selectedIds) you are turning an array of int into a string representation of said array.
The AJAX POST ends up like so:
{ "ids": "[565, 573, 571]" }
instead of
{ "ids": [565, 573, 571] }
If instead you just use the variable for the data, that should resolve the issue:
data: { "ids": selectedIds },
Edit-
Working backwards, by setting a variable to the data we can see the following:
var data = {"ids": JSON.stringify(selectedIds)}
typeof(data["ids"]) // string
data["ids"][0] // '['
data = {"ids": selectedIds}
typeof(data["ids"]) // object
data["ids"][0] // 565
I use:
public ActionResult GetBuildingsById(String selectedIds)
{
// this line convert the json to a list of your type, exactly what you want.
IList<int> Ids = new JavaScriptSerializer().Deserialize<IList<int>>(selectedIds);
return Content(ids[0].ToString());
}
This will take you selectedIds = [565, 573, 571]
and create the list of your type List

convert json object to serialized string for server side processing?

I'm trying to convert a returned json object into a serialized string that I can process further with some PHP server side code:
The returned object looks like this:
Object {id: "123456787654321", email: "some-email#gmail.com", first_name: "First", gender: "male", last_name: "Last"}
I can convert the object to a string with the following:
var paramString = JSON.stringify(response);
console.log(paramString);
// doesn't work
//var params = paramString.serialize();
How do I now convert the string to a serialized string that I can pass to my server with the following client side call:
I would expect something like this:
id=123456787654321&email=some-email#gmail.com&first_name...
My server side code:
$.post("/functions/test_functions.php", {params: params}, function(data) {
...
}, "json");
I handle the params array like this server side:
$vars = $_SERVER['REQUEST_METHOD'] === "GET" ? $_GET : $_POST;
$params = array();
isset($vars['params']) ? parse_str($vars['params'], $params) : null;
You can pass JSON-string to server and decode it with json_decode(). See http://php.net/manual/en/function.json-decode.php for details.
Unless there's a specific reason for stringifying, you don't actually need to. jQuery .post will handle the serialization for you, for example:
var response = {id: "123456787654321", email: "some-email#gmail.com", first_name: "First", gender: "male", last_name: "Last"};
$.post("/functions/test_functions.php", response, function(data) {
...
}, "json");
Will make a POST request like this:
/functions/test_functions.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Form Data: id=12345654321&email=some-email#gmail.com&first_name....

PHP json_encode versus JAVASCRIPT JSON.parse

If I create in PHP a json like this:
if ( ($result = mysqli_query($link, $sql)) && (mysqli_affected_rows($link)!==0) ) {
$entries = array();
while ($row = mysqli_fetch_assoc($result)) {
$entries[] = $row;
}
$data = json_encode($entries);
echo($data);
I will get this result:
[
{"id":"100043","title":"Mini for Sale","session":"1407456000","totalViews":"0"},
{"id":"100000","title":"test","session":"1408366541","totalViews":"4"},
{"id":"100001","title":"Le Cappa","session":"1408377143","totalViews":"0"},
{"id":"100002","title":"Le Cappa","session":"1408378069","totalViews":"0"},
{"id":"100003","title":"test","session":"1408378833","totalViews":"0"}
]
If I do this with JavaScript: console.log("jsondata: ", JSON.parse(data));
(where data is the json above: data = [{"id ... )
I will get this result:
jsondata: [
Object { id="100043", title="Mini for Sale", session="1407456000", mehr...},
Object { id="100000", title="test", session="1408366541", mehr...},
Object { id="100001", title="Le Cappa", session="1408377143", mehr...},
Object { id="100002", title="Le Cappa", session="1408378069", mehr...},
Object { id="100003", title="test", session="1408378833", mehr...}]
My question: Why is this different and how can I get with PHP a json with objects like the javascript one?
Some more Information: I'm trying to implement a table with the dynatable plugin. It works only if I pass the Data sended by PHP again with JSON.parse. Thats means to me that the PHP-json is wrong.
$.ajax({
url: 'http://huntinggrounds.de/stats/test.php',
success: function(data){ console.log("data: ",data); console.log("jsondata: ", JSON.parse(data));
$('#my-final-table').dynatable({
dataset: {
records: JSON.parse(data)
}
});
}
});
Here are booths results copied from console.
data: [{"id":"100043","title":"Mini for Sale","session":"1407456000","totalViews":"0"},{"id":"100000","title":"test","session":"1408366541","totalViews":"4"},{"id":"100001","title":"Le Cappa | Franco Gravante","session":"1408377143","totalViews":"0"},{"id":"100002","title":"Le Cappa | Franco Gravante","session":"1408378069","totalViews":"0"},{"id":"100003","title":"test","session":"1408378833","totalViews":"0"}]
jsondata: [Object { id="100043", title="Mini for Sale", session="1407456000", mehr...}, Object { id="100000", title="test", session="1408366541", mehr...}, Object { id="100001", title="Le Cappa | Franco Gravante", session="1408377143", mehr...}, Object { id="100002", title="Le Cappa | Franco Gravante", session="1408378069", mehr...}, Object { id="100003", title="test", session="1408378833", mehr...}]
What you're seeing in the console is an interactive debug representation of an actual Javascript object in memory. Is is not JSON. Your PHP output already is the perfect JSON representation of that Javascript object.

Ruby - parsing JSON coming via URL

I'm sending a JSON object to ruby with javascript. But I cannot parse it in there. I tried following stuff but no luck. Also I've been searching around for while now, but I couldn't find anything helpful.
Note that I'm very new ruby.
My trials:
def initialize(game_conf_json)
parsed_conf = JSON.parse(conf_json)
#param1 = parsed_conf['name'][0]
#param2 = parsed_conf['surname'][0]
=begin
I also tried this:
#param1 = parsed_conf['name']
#param2 = parsed_conf['surname']
But no matter what other things I try, I'm getting the following error:
"21:in `[]': can't convert String into Integer (TypeError)"
OR
"can't convert Array into String (TypeError), "
=end
File.open("some_direc/conf.json", "w") do |f|
f.write(game_conf_json)
end
end
I create the json in javascript like this:
var json_of_form_vars = {};
json_of_form_vars.name = name_val;
json_of_form_vars.surname = surname_val;
And send it this way:
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: "conf="+json_of_form_vars,
.....
How can I solve this problem? Is there any proper tutorial for this of problem?
UPDATE1 (After suggestions):
I used JSON.stringify and then passed the object to ruby. And then I finally able to print the object in ruby. It's listed below:
{"name": "METIN", "surname": "EMENULLAHI"}
The method .class claims that it is an array. But I cannot access data with classical ways, like:
array['name']
the error is:
can't convert String into Integer
And when I try to pass it to the JSON.parse in ruby, it gives me the following error:
can't convert Array into String
So I used JSON.parse(conf_array.to_json), but again when accessing the data it gives the same error like arrays:
can't convert String into Integer
What should be done now?
UPDATE2
Here is my cgi handler which passes the URL parameters to appropriate places:
cgi_req = CGI::new
puts cgi_req.header
params_from_request = cgi_req.params
logger.error "#{params_from_request}"
action_todo = params_from_request['action'][0].chomp
base = Base.new
if action_todo.eql?('create')
conf_json = params_from_request['conf']
# This line prints the json like this: {"name": "SOME_NAME", "surname": "SOME_SURNAME"}
logger.error "#{conf_json}"
base.create_ident(conf_json)
end
And in Base class:
def create_ident(conf_json)
require 'src/IdentityCreation'
iden_create = IdentityCreation.new(conf_json)
end
IdentityCreation's constructor is listed above.
UPDATE3:
Ok, I now get at least something out of the array. But when I access a key, it displays the key itself:
parsed_conf = JSON.parse(conf_json.to_json)
#param1 = parsed_conf[0]['name']
#param2 = parsed_conf[0]['surname']
# At this point when I print the #param1, it gives me "name"(the key), not "SOME_NAME"(the value).
Here an example of parsing a JSON string. If you still have problems, publish the generated JSON so that we can try it.
require 'json'
require 'ap'
string = %{
{"configurations" : [
{ "drinks" : [
{"menus" : [
{ "hot" : [
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
] },
{ "cold" : [
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
] },
{ "terminals" : { "id" : 4, "id": 6, "id": 7 } },
{ "keys" : { "debit" : "on", "credit": "off" } }
] }
] } ] }
}
hash = JSON.parse(string)
ap hash
gives
{
"configurations" => [
[0] {
"drinks" => [
[0] {
"menus" => [
[0] {
"hot" => [
[0] {
"id" => 15,
"unit" => "0.33",
"price" => "1",
"currency" => "Euro",
"position" => 4
},
etc..
At the moment you're not actually posting json. You're attemping to post json wrapped inside form encoded parameters. In addition, when you do
"conf=" + json_of_form_vars
javascript will convert json_of_form_vars to a string for you but that conversion isn't the same as dumping to JSON. Javascript default string conversions are pretty useless for objects, so you'll need to use JSON.stringify to get actual json.
Since you're composing the body as a string literal you'll also need to escape any special characters that aren't allowed (or have special meaning) in this context. It's usually easier to let jquery do the heavy lifting, with something like
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: {conf: JSON.stringify(json_of_form_vars)}
I solved it finally. Using all the suggestions made under this post and also my irb experiences with hashes, arrays, json and etc.
So instead of converting my object (conf_json) to json (with to_json), I passed it to JSON.parse as a string like below:
parsed_conf = JSON.parse(%{#{conf_json}})
It seems kind of weird to me, because when try to pass it to function like below, I got the error of can't convert Array into String.
parsed_conf = JSON.parse(conf_json)
But it is working like a charm right now.

Categories