I have to store a data from ajax call to model.Now I am using "pushPayload" to save the data to my model.But it is throwing error
serializer.pushPayload is not a function
In controller I am doing something like this after the ajax call.
currentState.store.pushPayload('discover',result)
serializer (discover.js)
export default DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin,{
isNewSerializerAPI: true,
primaryKey:'pk',
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
How do I save the data recieved from server to my model.The reponse is an array of object
store.pushPayload internally uses either application serializer's pushPayload function or the given model's specific serializer's pushPayload function. In your case model specific serializer is of JSONSerializer type which doesn't have the required function.
You can refer JSONAPISerialzer, which has the pushPayload function and try to replica it in your JSONSerializer.
Related
So I am trying to use a resource collection to return datatable json information. Before I used my collection I first did a proof of concept that looked like this:
public function index()
{
$clients = QueryBuilder::for(Client::class)
->allowedIncludes('accounts')
->get();
if (request()->ajax()) {
return DataTables::of($clients)->make(true);
}
return view('client.index', compact('clients'));
}
This worked perfectly and the json response looked like so:
{data: [{id: "4428", number: "492501", name: "Test Client", email: "test#test.com",…},…]
draw:1
input:{view: "datatable", draw: "1",…}
recordsFiltered:2
recordsTotal:2}
Then I updated my index call to use my resource collection that looks like this:
public function toArray($request)
{
switch ($request->view) {
case 'datatable':
self::withoutWrapping();
return DataTables::of($this->collection)->make(true);
}
return parent::toArray($request);
}
The response is now plopped in an "original" attribute and a bunch of other items are added to the response. I don't understand why. It looks like this:
*callback: null
*charset: null
*content: <The above response is in here as a string>
*encodingOptions: 0
*statusCode: 200
*statusText: "OK"
*version: "1.0"
exception: null
headers: {}
original: <The above response is in here as an object>
I can set my dataSrc on datatables to original.data and it works fine but where did all this extra stuff come from? I have used a few other resource collections and never had all this stuff added in.
Update: because everything i am looking for is in "original" the pagination breaks as well as most of the other datatable functionality. If I move this return back into the controller it works fine.
So, the answer has to do with response type. The eloquent resource has an undocumented function called "toResponse" and if your return is going to be some kind of jsonResponse you need to modify it instead of your toArray method. What was happening was I was returning a JsonResponse and it was turning it into an array and just returning that json encoded.
To be clear as mud, here is my new Resource:
public function toResponse($request)
{
switch ($request->view) {
case 'datatable':
self::withoutWrapping();
return DataTables::of($this->collection)->toJson();
}
return parent::toResponse($request);
}
So, to reiterate, if you are returning an array or something that conforms to an array correctly (which datatables jsonresponse does not) you override "toArray". If you are returning a jsonResponse you need to override "toResponse".
Another option is to have your code start in toArray but when you know your going to return a jsonResponse you call $this->toResponse($request). Option is yours.
A javascript code uses "map" method on array of object to extract just the text value:
var checked_leaves = checked_ids.filter(function(elm) {
if (elm.children.length == 0)
return elm;
}).map(function(elm, index) {
return elm.text.trim();
});
this array of string is sent to a Laravel route using ajax (with Vue http)
this.vm.$http.get(this.el.action + checked_leaves).then((response) => {
console.log(response);
//this.vm.speciesDetails = JSON.parse(response.data);
}, (response) => {
});
Where the this.el.action is api/taxonomytospecies/ and the corresponding Route is:
Route::get('api/taxonomytospecies/{ids}', 'TaxonomyController#getSpeciesFromTaxonomy');
And inside TaxonomyController:
public function getSpeciesFromTaxonomy($ids) {
// Eloquent job to retrieve the data from the DB
}
1) Is there a better way to pass an array of values like the one I get from the javascript code (they are a lot of strings) to a route of a controller?
2) I get an internal 500 error. The error shows that the call is like :
api/taxonomytospecies/name1,name2,name3,name4,name5
But i don't know how to resolve this kind of error
I would suggest you to use post request instead of get as the data is large.
You can send data as an array to the server.
var data = {ids: checked_leaves};
Then send data variable in your post request.
In your controller you can get data as:
public function getSpeciesFromTaxonomy() {
$ids = request()->get('ids') // returns an array.
// Eloquent job to retrieve the data from the DB
}
And your route should be as:
Route::post('api/taxonomytospecies', 'TaxonomyController#getSpeciesFromTaxonomy');
The solution is to set the Route as:
Route::get('api/taxonomytospecies/', 'TaxonomyController#getSpeciesFromTaxonomy');
And the Vue-resource request as:
this.vm.$http.get(this.el.action, {params: { ids: checked_leaves } }).then((response) => {
but i don't understand why.
I have an AJAX call in my view,
var ajaxData= $.ajax({
type: "GET",
url: "${createLink(controller:'profile',action:'ajaxList')}",
success: function(data) {
}
});
I created a method in the ProfileController.groovy class in order to return "data" from this call, but I don' know how to format the controller correctly. Here is what I want to return. The model, profile, has a name and a description. I want to return a hash object where the key is the name and the value is the description. Is there a way to do this in the controller so that this ajax call returns that hash. Any help would be aprpeciated. Thanks!
In your controller's ajaxList action build your model as you want it, as usual, and then instead of return model at the end you want to render model as JSON.
For example,
class ProfileController {
def ajaxList() {
def profiles = Profile.list()
def model = profiles.collect { [(it.name): it.description] }
render model as JSON
}
}
And if you want to use the same list action for returning different formats, look at using withFormat.
I have an ajax call in my jquery to my MVC controller:
$.getJSON('/mysite/controller/dosomething', { postId: id }, function (data) {
The 'data' that I am returning is in the form of a JsonResult, and consists of a simple custom object with 1 property called 'Message' and another property called 'Count'. Both of these values are assigned and I am returning them as follows (edited for brevity):
[HttpGet]
public JsonResult DoSomething(int postId)
{
var response = new MyAjaxResponseModel {Message = "Hello world!", Count = 66};
return Json(response, JsonRequestBehavior.AllowGet);
}
In my jQuery, I then want to be able to look at both values in the Json response, but I don't know the proper way to get at these values?
data.Message, data.Count in the callback you're passing to $.getJSON()? To inspect the structure of your data object, you can use console.log(data) (also, in that callback)
I try to send data form ajax to cakephp cotroller
function loadtooltip(obj, $user_id) {
//AJAX
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
displaytooltip(obj, req.responseText);
}
}
};
req.open("POST", "http://127.0.0.1/cakeplate/tooltips/tooltip/", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send($user_id);
};
this controller
<?php
Class TooltipsController extends AppController{
var $name = 'Tooltips';
var $uses = array('Reply','User');
var $component = array('RequestHandler','Javascript','Ajax');
var $layout = 'tooltip';
function tooltip($user_id=NULL){
if(!empty($user_id)){
$tooltip = $this->Reply->User->findById($user_id);
$this->set('tooltip',$tooltip);
}
}
}
?>
I need somebody to help me to modified code
the way you're doing at the moment in the controller, you won't me able to get the user_id, because it is a var passed through GET method of http.
This variable would be accessible if you make a GET request for example for this url:
http://example.com/cakeplate/tooltips/tooltip/1 where 1 would be your $user_id.
If you send the request as POST, you can access the values in this var $this->data
This way you will be able to process the request based in the var that you pass to the controller.
Another problem that you will face that this controller will need to render a view, so i suggest that you take a look at http://book.cakephp.org/view/1238/REST, there you can see how you can create a route that will make the controller parse another view, it a different custom layout, like the json (the one i suggest in this case), and then you can show in this view only the json value.
Last, but important as well, i would suggest to that you use jQuery to do the javascript part, i think it will be easier, you can check it at http://api.jquery.com/jQuery.get