how to access specific data from JsonResponse - json

Supposing I have this return value
return JsonResponse( { 'message' : 'success', 'id' : newProductType.id }, safe = False )
and I have this function on success
.then( function( rs ){
alert(rs.id)
Problem is, it alerts an undefined value. How do I access the id field in that object? Sorry, maybe its a very simple problem but Im a newbie so bear with me.

You can use
rs.new_id
Because your response haven't id field.

Related

How do I resolve a map value called on null

I have a contact model that uses maps but the return is null thus causing aysnc suspension. I have tried tried setting these maps to return an empty list but to no avail do I manage to resolve the issue.
ContactModel{
//factory method constructor
emails: List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x))),
tasks: List<Tasks>.from(parsedJson["Tasks"].map((x) => Tasks.fromJson(x))),
notes: List<Notes>.from(parsedJson["Notes"].map((x) => Notes.fromJson(x))),
}
The error returns as : No such method map called on null. Receiver null
I have tried to resolve the issue by writing it as such
ContactModel{
//factory method constructor
emails: List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x))).toList() ?? [],
tasks: List<Tasks>.from(parsedJson["Tasks"].map((x) => Tasks.fromJson(x))).toList() ?? [],
notes: List<Notes>.from(parsedJson["Notes"].map((x) => Notes.fromJson(x))).toList() ?? [],
}
You can try null checking the json like so :
ContactModel{
emails: parsedJson['Emails'] != null ? List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x))).toList() : [],
tasks: parsedJson['Tasks'] != null ? List<Tasks>.from(parsedJson["Tasks"].map((x) => Tasks.fromJson(x))).toList() : [],
notes:parsedJson['Notes'] != null ? List<Notes>.from(parsedJson["Notes"].map((x) => Notes.fromJson(x))).toList() : [],
}
Basically, I always check 2 things when working with JSON types :
You must check your JSON contains the key you're looking for
You must check null value being returned if the key exist.
I recommend you doing this double check like this :
if(parsedJson.isNotEmpty) {
List<dynamic> emails = [];
if (parsedJson.containsKey('Email') && parsedJson['Email'] is List) {
emails = List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x)))
}
ContactModel({emails: emails});
}
This way, you always make sure you've got the right type, and avoid production error (imagine your API going nuts). It's more verbose, I know, but to me, good code requires accuracy

Retrieve specific data using JSON decode Laravel

I'm new to Laravel. I need to retrieve specific data from the database using the JSON decode. I am currently using $casts to my model to handle the JSON encode and decode.
This is my insert query with json encode:
$request->validate([
'subject' => 'required|max:255',
'concern' => 'required'
]);
$issue = new Issue;
$issue->subject = $request->subject;
$issue->url = $request->url;
$issue->details = $request->concern;
$issue->created_by = $request->userid;
$issue->user_data = $request->user_data; //field that use json encode
$issue->status = 2; // 1 means draft
$issue->email = $request->email;
$issue->data = '';
$issue->save();
The user_data contains {"id":37,"first_name":"Brian","middle_name":"","last_name":"Belen","email":"arcega52#gmail.com","username":"BLB-Student1","avatar":"avatars\/20170623133042-49.png"}
This is my output:
{{$issue->user_data}}
What I need to retrieve is only the first_name, middle_name, and last_name. How am I supposed to achieve that? Thank you in ADVANCE!!!!!
As per the above code shown by you it will only insert data into the database.For retrieving data you can make use of Query Builder as i have written below and also you can check the docs
$users = DB::table('name of table')->select('first_name', 'middle_name', 'last_name')->get();
I will recommend using Resources. It really very helpful laravel feature. Check it out. It is a reusable class. You call anywhere and anytime.
php artisan make:resource UserResource
Go to your the newly created class App/Http/Resources/UserResource.php and drfine the column you want to have in your response.
public function toArray($request) {
return [
"first_name" => $this->first_name,
"middle_name" => $this->middle_name,
"last_name" => $this->last_name
]
}
Now is your controller you can use the UserResource like folow:
public function index()
{
return UserResource::collection(User::all());
}
Or after inserting data you can return the newly added data(f_name, l_name...)
$user = new User;
$user->first_name= $request->first_name;
$user->middle_name= $request->middle_name;
$user->last_name= $request->last_name;
$user->save();
$user_data= new UserResource($user);
return $user_data;

Sequelize raw queries TextRow and getting data out of it

Given this query here,
let output = [];
const sql = `select * from coredb.account LIMIT ${offset},${limit}`;
let data = await sequelize.query(sql, null, {raw: true, type: sequelize.QueryTypes.SELECT});
data.forEach((item) => {
console.log(item['id'], item.id); // <-- output says "undefined, undefined"
});
the data variable is indeed hydrated with the right row data when using console.log to inspect it.
But, when I try to access the individual properties, they only ever come back as undefined. This TextRow object that Sequelize seems to return the result in doesn't seem to want to let me access then explicit rows.
Just curious what i'm missing here, am I missing an option?
I agree, Sequalize raw queries are not intuitive. You don't need the null or raw: true flag. Something like this should work:
let data = await sequelize.query(sql, {type: sequelize.QueryTypes.SELECT});
When I tried this, "data" was an array of two objects, each being the query result. So, the properties can be accessed by using index [0].... e.g.
data[0].forEach((item) => {
console.log(item['id'], item.id); // <-- output says "undefined, undefined"
});
Not yet sure WHY this occurs!
EDIT - it's because .query() should have only two arguments. Changing the call to: sequelize.query(sql, {raw: true, type: sequelize.QueryTypes.SELECT}) resulted in data being a single array (as expected).
Finally I was able to find the solution for it.
You just need to make a new array and push data into it by finding bases on key name like this:
suppose we have data in students object:
let finalArray = new Array();
for (var k in students ) {
finalArray.push(students[k])
}
console.log(finalArray) // Normal JSON array object :)
m.sequelize.query(sql, {
model,
mapToModel: true
})
.then(model => res.status(200).send(model))
.catch(error => res.status(400).send(error.toString())
})

Codeception seeResponseMatchesJsonType method isn't validate fields correctly

I've have API test
public function loginAsRegisteredUser(\ApiTester $I)
{
$I->wantTo('Login as registered user');
$I->sendPOST('/action.php?ap=V4&p=Customer&c=Customer&a=login',['customer' => ['email' => $this->registered_user_email, 'password' => $this->registered_user_password]]);
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
$I->seeResponseIsJson();
$I->seeResponseMatchesJsonType(["customer" => ["id_customer"=> 'string|null',"first_name"=>'string|null',"last_name"=>'string|null',"newsletter"=>'string|null']]);
}
and id_customer field always fails comparation
1) LoginCest: Login as registered user
Test tests/api/LoginCest.php:loginAsRegisteredUser
Step See response matches json type {"customer":{"id_customer":"string|null","first_name":"string|null","last_name":"string|null","newsletter":"string|null"}}
Fail `id_customer: 1` is of type `string|null`
Example of response:
{"customer":{"id_customer":1,"first_name":"as","last_name":"ewq","newsletter":"1"}}
I've tried all possible types for field id_customer(number for example), but no one works. Does anyone now solution?
It actually is validating correctly - your expectations are wrong.
Expected type is string or null, but the actual type is integer.

Yii x-editable on CGridView: not stopping screen update when success returns error

When json response sends response.success == false, I can see the console log showing me the error, but x-editable seems that doesn't catch the return, and the value in the screen is changed to the new one I had introduced, although it has not been really saved. Is there something wrong?
Here is piece of the CGridView code I use:
'class' => 'editable.EditableColumn',
'editable' => array(
'model' => $model,
'params' => array('YII_CSRF_TOKEN' => Yii::app()->request->csrfToken),
'url' => $this->createUrl('user/update'),
'success' => 'js: function(response, newValue) {
if(!response.success)
console.log(response.msg);
return response.msg;
}',
'options' => array(
'ajaxOptions' => array('dataType' => 'json')
),
)
EDIT 1:
Ok, I have been working on that, and I have found which is the problem. It seems that the javascript function I put on success is not working properly.
The if statement is catching correctly the response, but the return value is not being sended correctly. I explain: if I put a literal like that: return "test return"; the value is returned correctly, but if I put return response.msg; nothing is sended.
Of course, response.msg is not empty and contains the String message correctly.
Ok, I have been working on that and I found my stupid mistake... I was returning msg as array and I had to do this:
return response.msg[index];
Where index is where the message is stored.
It was really embarrassing losing time with that...