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....
Related
Axios sends an array of strings instead of an array of objects. I have an array of objects that contains data about the event. I'm trying to send a request to the server via axios, but I get a array of strings insteenter image description heread of objects at the output
let data = {
title: 'Game',
subject: 'Some subject',
date: ['01/01/2021','01/01/2021'],
years: ['1970', '1970'],
address: 'None',
ages: [
{
title: 'Men',
weights: [{page: 0, title: '60'}]
}
]
};
api.Create({
params: data
}).then(function (response) {
console.log(response.data);
})
.catch(function (err) {
console.log(err);
});
api response
try to:
console.log(JSON.parse(response.data))
What you get back from the server is string. you need to parse it.
When you send data to and from a server, it is sent as a 'serialized' string, usually JSON format
That's how server responses work
It turned out to be an incorrect request. I used GET to pass the object, instead of POST, so it converts it to a string. I want to notice that there is an evil community on this site.
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'];
}
In Mobilefirst Platform 8.0, in order to send a request to an adapter procedure I can use something like this
resourceRequest.setQueryParameter("params", "['Washington', 'United States']");
But this is for 2 string values. How can I send a JSON object instead of a string?
I would like to send something like this:
var request = {name: 'George', suername: 'Williams', Id: '1234'};
resourceRequest.setQueryParameter("params", request);
If yes, what is the correct syntax?
Try the following approaches:
Pass it directly, but as a string...
resourceRequest.setQueryParameter("params", “[{’name’ : ‘bob’, ‘’age’ : 25}, 'United States']");
Create a JSONArray and pass it
JSONArray params = new JSONArray();
params.putObject(myJsonObject);
resourceRequest.setQueryParameter("params", params);
This is probaly a really easy question but am struggling with this four about 2 hours now.
I have a php file:
$array = array(
"id"=> 1, "firstName"=> "James", "lastName"=> "King", "managerId"=> 0, "managerName"=> "", "title"=> "President and CEO", "department"=> "Corporate", "cellPhone"=> "617-000-0001", "officePhone"=> "781-000-0001", "email"=> "jking#fakemail.com", "city"=> "Boston, MA", "pic"=> "James_King.jpg", "twitterId"=> "#fakejking", "blog"=> "http://coenraets.org"
);
echo json_encode($array);
Now I want to give this an object like the following:
Object
blog: "http://coenraets.org"
cellPhone: "617-000-0001"
city: "Boston, MA"
department: "Corporate"
email: "jking#fakemail.com"
firstName: "James"
id: 1
lastName: "King"
managerId: 0
managerName: ""
officePhone: "781-000-0001"
pic: "James_King.jpg"
title: "President and CEO"
twitterId: "#fakejking"
Right now i'm getting the following response:
abort: (a)
always: ()
complete: ()
done: ()
error: ()
....
readyState: 4
responseText: "{"id":1,"firstName":"James","lastName":"King","managerId":0,"managerName":"","title":"President and CEO","department":"Corporate","cellPhone":"617-000-0001","officePhone":"781-000-0001","email":"jking#fakemail.com","city":"Boston, MA","pic":"James_King.jpg","twitterId":"#fakejking","blog":"http:\/\/coenraets.org"}"
setRequestHeader: (a,b)
state: ()
...
__proto__: Object
I really don't know where to look and am probaly doing something wrong but I really have no idea.
UPDATE
js
var result = $.ajax({
url: "http://localhost/cordova/employees/index.php?name="+ searchKey,
context: document.body
});
console.log(JSON.parse(result.responseText));
The line console.log(JSON.parse(result.responseText)) gives me the following error:
Uncaught SyntaxError: Unexpected token o
That's because you're looking at the XMLHttpRequest object. You need to parse out the response to get the object.
var obj = JSON.parse(xhr.responseText);
where xhr is the name of the object you're doing a console.log on.
$.ajax() makes an asynchronous HTTP request, so you can't just get the response right way. You have to wait for the response to come to you. The done() construct can be used to fire a callback when your response is ready.
var getEmployee = $.ajax({
url: "http://localhost/cordova/employees/index.php?name="+ searchKey,
context: document.body,
dataType: 'json'
});
// the callback will get fired when the response is received
getEmployee.done(function (result) {
console.log(result.blog);
});
// this will get fired immediately before the response is even received
console.log(getEmployee.responseText);
It's simple feature.
read about stdClass in PHP
and modify your php code to:
$array = new stdClass();
$array->id = 1;
$array->firstName = "James";
//..... other fields
echo json_encode($array);
Trying to figure out the JavaScript syntax for handling JSON feed returned by a REST service. Suppose a random REST service (e.g. http://random.service/directory) is returning the following feed:
{
'firstName': 'John',
'lastName': 'Smith',
'address': {
'streetAddress': '21 2nd Street',
'city': 'New York'
}
}
and that I have a JSON parsing JS function (to parse the above feed) like:
function parseRESTFeed(json) {
...
}
How do I bridge the REST call of "http://random.service/hello" to parseRESTFeed(json) via JS?
Much Thanks!
If you use jQuery (and you should if you don't), then you can do it like this (ref):
$.getJSON('http://random.service/directory', null, function(data){
// And here you can do whatever you want with "data", no need to parse it
alert(data.firstName);
});
If you have some other way to get response from the service as string, again there is no reason to parse, since you can use javascript's eval. For example:
var myJSON = "{'firstName': 'John','lastNAme': 'Smith'}";
var data = eval('(' + myJSON + ')');
alert(data.firstName);