extjs: nested baseParams in request - ajax

In the frame of an Ajax request, I am trying to use a nested object for parameter "baseParams". Basically, I would like to produce an URL like "ajax.php?foo[controller]=demo&foo[action]=index".
Bellow is the code that wrongly produces: "ajax.php?foo=[object]&foo=[object]".
Ext.data.JsonStore(
baseParams: {
foo: {
controller: 'demo',
action: 'index'
}
},
proxy: new Ext.data.HttpProxy({
method: 'GET',
url: '/ajax.php'
}),
(...)
);
Of course, I could write something like bellow but I was looking for a more nifty solution.
Ext.data.JsonStore(
proxy: new Ext.data.HttpProxy({
method: 'GET',
url: '/ajax.php?foo[controller]=demo&foo[action]=index'
}),
(...)
);
After few attempts, I wonder if it is really possible. But maybe I missed something. Can you help?

Or use something like this (which is better than a long url string):
baseParams: {
'foo[controller]': 'demo',
'foo[action]': 'index'
}

I did something like this, which is identical in the end to Igor Pavelek's response, only a little more programmatic:
var foo = {
'controller' : 'demo',
'action' : 'index'
};
var gfObj = new Ext.ux.grid.GridFilters({paramPrefix: 'foo'});
var bp = gfObj.buildQuery(foo);
Ext.data.JsonStore({
baseParams : bp,
(...)
});

baseParams: {
foo['controller']: 'demo',
foo['action']: 'index'
}
I would recommend this , i think there is simple difference of commas from above

Related

Laravel 6 Form Array $request->input() doesn't work

I have this array of prices, like so:
<input type="input" id="prices[type][1]" name="prices[type][1]">
<input type="input" id="prices[type][2]" name="prices[type][2]">
I send this data via a post request (JSON: Yes, the Content-Type is set to application/json) and expected to get an array when I use $request->input('prices') but that doesn't really happen. Also tried $request->get('prices').
When I do $request->all() I do get all the data I submitted:
JS Used to make request:
const response = await fetch(this.action, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': this.$page.token,
},
body: this.formData(),
});
const body = await response.json();
this.formData():
formData(): Object {
const formData = new FormData(this.$el);
return JSON.stringify(Array.from(formData.entries()).reduce((memo, pair) => ({
...memo,
[pair[0]]: pair[1],
}), {}));
},
Does anyone have an idea on where it might go wrong?
Hm, it looks like the array is broken even if you do all() as I don't see the type key in the array.
Try this instead:
dd(json_decode($request->getContent(), true));
As it is JSON so you will need to get the body and convert it into an array.
You need to use:
$prices_array = $request->only('prices');
Or:
$no_prices_array = $request->except('prices');
That way you can filter a request by field, and access them.

How to correctly return html template from ajax request with Symfony

I was wondering how to return correctly an HTML template (SEO friendly) from an ajax call.
In my app, I use 2 differents ways to return response:
For simple template:
public function ajaxCallAction() {
//.....
$response = array(
"code" => 202,
"success" => true,
"simpleData" => $simpleData
);
return new JsonResponse($response);
}
And in the JS I do something like:
$("div#target").click(function(event) {
$.ajax({
type: "POST",
success: function(response) {
if(response.code === 202 && response.success) {
$("div#box").append(response.simpleData);
}
}
});
});
For complexe template (more than 20 lines and various var):
public function ajaxCallAction() {
//...
$listOfObjects = $repo->findAll();
$viewsDatas = [
'listOfObjects' => $listOfObjects,
//....other vars
];
return $this->render('myAppBundle:template:complexTemplate.html.twig', $viewsDatas);
//in complexTemplate.html.twig, I loop on listOfObjects for example...
}
And for this kind of call, the JS looks like:
$("div#target").click(function(event) {
$.ajax({
type: "POST",
success: function(response) {
$("div#box").append(response);
}
});
});
All those methods are working, but with the second one, we dont have status code (does it matter?) and I know that returning directly formated html template can be heavy (according to for example this topic Why is it a bad practice to return generated HTML instead of JSON? Or is it?).
How are you guys doing ajax calls? What are the best practices here?
In my apps, I typically use something like that:
$response = array(
"code" => 200,
"response" => $this->render('yourTemplate.html.twig')->getContent() );
Hope this help!
Edit
To return your response, you should use JsonResponseas explained in docs: http://symfony.com/doc/current/components/http_foundation.html#creating-a-json-response
Simply use that:
return new JsonResponse($response);
Try with "renderView" ;)
return $this->json([
'html' => $this->renderView('template.html.twig', []),
]);

How to pass the Query Data in Body for making REST API call in graphql

I am doing a post operation where i am getting some response.
My URl looks Like:
http://domainname/api/v1:id
As a part of body i want to pass the below data:
{ elemetnt { id, name } }
Can anybody suggest me how i can achieve this.
i am trying with the below code but i am getting 404:
let queryParam = `{ elemetnt { id, name } }`;
this.http.post(`http://domainname/api/v1:1`, {
query: queryParam,
}, {
headers: new Headers({
'Content-Type': 'application/graphql',
}),
})
.catch((error: Response | any) => {
console.log(error);
return Observable.of(error);
})
.subscribe((res) => {
console.log(JSON.stringify(res));
});
I know i am doing something wrong. But, if somebody can help me on this then it would be great help.
It depends on method which receiving this data, but this is correct format for you as given in question
queryParam= { element : { id: "0000" , name: "name" };
you may need to stringy your solution
Canyou please try with
'Content-Type': 'application/json'
and pass json body like
{"query":"{ elemetnt { id, name } }" }
I think this may help you

fieldASTs on GraphQL resolve

I have been going crazy over this for GraphQL. I have seen a lot of resources referring to this last fieldASTs param for the selectionSet. However, it doesn't seem to be there. I haven't found any solid evidence that it is, but it has been brought up in github issues and tutorials. I am a little confused by this. Is there or is there not a 4th param?
I have also tested the other params to see if I can pull it off of those.
const SomeType = new GraphQLObjectType({
name: 'SomeObject',
fields: () => ({
someItems : {
type: new GraphQLList(SomeCustomType),
resolve: (someItems, params, source, fieldASTs) => {
const projections = getProjection(fieldASTs);
return SomeModel.find({}, projections);
}
}
});
with current version (0.7.0), now it is in the forth argument, third argument is for context.
the following observation from this blog post may help.
http://pcarion.com/2015/09/27/GraphQLResolveInfo/
Welp, I found it. I dove through the changelogs and it was changed to be part of the third param. However, it isn't structured the same way
resolve: (item, params, info, fieldASTs) => {
//used to be
fieldASTs.selectionMap.selection.reduce(someLogic);
//now its simply
fieldASTs.reduce(someLogic);
}
I'm using graphql#0.4.14, and found it here:
info //third argument
.fieldASTs[0]
.selectionSet
.selections
//.reduce...
I guess they are still changing everything, so I've added try/catch to getProjection()
Yes the fourth param comprises of fieldASTs but its hooked under the object as an array
const SomeType = new GraphQLObjectType({
name: 'SomeObject',
fields: () => ({
someItems : {
type: new GraphQLList(SomeCustomType),
resolve: (someItems, params, source, options) => {
const projections = getProjection(options.fieldASTs[0]);
return SomeModel.find({}, projections);
}
}
});
This solved for me.
In express-graphql being graphql v0.8.1 I had to do it like this (note the use of mongoose too):
function getProjection (fieldASTs) {
return fieldASTs.fieldNodes[0].selectionSet.selections.reduce((projections, selection) => {
projections[selection.name.value] = 1;
return projections;
}, {});
}
resolve (root, params, info, fieldASTs) {
let filter = {};
if(params._id){
filter._id = params._id;
}
var projections = getProjection(fieldASTs);
return grocerModel.find(filter).select(projections).exec();
}
I am new to graphql, but this resolved it for me and I think something may have changed in the versions as fieldASTs did not exist on the options (4th param) object, but fieldNodes does that has the necessary child objects to perform the projection.
export default {
type: new GraphQLList(teamType),
args: {
name: {
type: GraphQLString
}
},
resolve(someItems, params, source, options) {
const projection = getProjection(options.fieldNodes[0])
return TeamModel
.find()
.select(projection)
.exec()
}
}
There are 2 competing Open Source libraries to achieve what topic starter was asking for:
graphql-fields-list
graphql-list-fields
They both try to solve the same problem, but the former seem to have some more features, including TypeScript support out of the box.

jQuery AJAX call, how to handle

I'm wondering what is the best method to handle AJAX calls with jQuery? Right now I'm doing something like following:
$("#test").live('click', function(){
// Process form
$.ajax({
type: "post",
url: "test.php",
success: function(html){
if(html.success == 0) {
alert('Error');
} else {
var obj = $.parseJSON(html.rows);
$("#success").html(obj[0].name);
}
},
dataType:'json'
});
return false;
});
In test.php file, I'm checking if request is an AJAX request. If it's an AJAX request I'm running a database query to get some data (this part isn't important in this question, I think):
// query goes here
if(mysql_num_rows($query) > 0 ) {
$result['success'] = 1;
$result['data'] = json_encode($data);
} else {
$result['success'] = 0;
}
Now I'm wondering if my method is the best possible? FYI I'm using KohanaPHP framework currently, so I want to not break MVC "rules". If I'm doing it wrong, do you have any tips and suggestions how to handle AJAX calls in controllers?
Regards,
Tom
What you have looks good here, though I don't think you need a $.parseJSON() there, it should already be an object at that point, this should work:
$("#success").html(html.rows[0].name);
As a side note, from a readability/maintainability perspective, I'd rename your html argument to be data, like this:
success: function(data) {
This is purely preference, but using html when it's an HTML type response, and data or something else when it's JSON/already an object you're expecting keeps things a bit easier to read for outsiders.
#tom - you need to encode the PHP array like this:
$data = array(
'status' => 'success'
);
echo json_encode($data);
But you might want to change the array structure a little. Since the xhr object has a text status I usually encode an JSON array like this:
$response = array(
'status' => 'success' // or flash or error
,'flash' => array(
'header' => 'whatever is wrong with submission of data html list format'
'fields' => array('field names to be highlighted')
)
,'html' => 'html presentation'
,'data => array('json data')
);
echo json_encode($response);
Now you can do some nice things like this:
,success: function(response) {
if (response.status === 'success') {
$('.basic_container').hide();
that.removeDataTable();
that.getContent(contentUrl);
$('.basic_container').show();
}
if (response.status === 'flash') {
$('#flash').html(response.flash.header);
$('#flash').show();
that.highlightWithFlash(response.flash.fields);
}
}

Resources