Simple way for ajax calls in FLOW3? - ajax

Actually I am working on a FLOW3 project and up to now it´s really great fun working with FLOW3, even if the documentation is not that good. But now I have problem: I want a JavaScript/jQuery function inside my frontend to call a controller action and the controller to return a json. As there is not much about this inside the documentation I tried a the way like in http://bytelude.de/2012/09/10/flow3-wie-erstelle-ich-eine-ajax-action-mit-json-ruckgabe/, but I always got a answer from the application that there is no view defined. I am using FLOW3 1.1.0. Maybe someone can give me a hint how to perform a ajax/json camm in a simple way.

FLOW3 now uses Mime-Types instead of formats: The second example in the Json View Section should do the trick.
You have to set
protected $supportedMediaTypes = array('application/json', 'text/html');
instead of
protected $supportedFormats = array("html", "json");
now.

Maybe you need to check your Route.yaml, if you set the format to json, does it change something ?

If you do not want to bother with Json-Views and Mime-Types you can always just do this in your controller:
return json_encode($data);
When you return something (a string) in the Controller-Action, the view is never queried and the return gets used instead.

Related

Laravel - retrieve data inside controller – POST x PATCH

First important information: I’m new to laravel, so your patience is appreciated.
I’m currently migrating a framework of mine to laravel, so I’m in the early stages.
Currently, I’m trying to set up an API endpoint to make small changes on some records. I’ve already managed to set up a API for inserting records and works perfectly. However, for setting up an API for small changes (patch), I’m having difficulties, probably because I’m not fully familiar with laravel’s Request class.
My successful insert set up looks like this:
\routes\api.php
Route::post('/categories/',[ApiCategoriesInsertController::class, 'insertCategories'], function($insertCategoriesResults) {
return response()->json($insertCategoriesResults);
})->name('api.categories.insert');
\app\Http\Controllers\ApiCategoriesInsertController.php
// some code
public function insertCategories(Request $req): array
{
$this->arrCategoriesInsertParameters['_tblCategoriesIdParent'] = $req->post('id_parent');
// some code
}
With this set up, I’m able to retrieve “id_parent” data set through POST.
So, I tried to do exactly the same architecture for patch, but doesn’t seem to work:
\routes\api.php
Route::patch('/records/',[ApiRecordsPatchController::class, 'patchRecords'], function($patchRecordsResults) {
return response()->json($patchRecordsResults);
})->name('api.records.patch');
\app\Http\Controllers\ApiRecordsPatchController.php
// some code
public function patchRecords(Request $req): array
{
$this->arrRecordsPatchParameters['_strTable'] = $req->post('strTable');
// some code
}
In this case, I´m using postman (PATCH request), testing the data in the "Body tab" with key "strTable" and value "123xxx" and I´m receiving “strTable” as null.
Any idea of why this is happening or if I should use another method in the Request class?
Thanks!
You can access parameters on the Request object using one of the following methods:
$req->strTable;
// or
$req->input('strTable');
The input method also accepts a second parameter which will be used as the default return value if the key is not present in the Request.
If you want to check whether or not the Request contains a value before you attempt to access it, you can use filled:
if ($req->filled('strTable')) {
// The request contains a value
}
Turns out that the way I had set up was in fact working and retrieving data:
$req->post('strTable');
The problem was in how I was testing it. In postman, there are several options to configure:
form-data
x-www-form-urlencoded
raw
binary
I had already switched to x-www-form-urlencoded to test it, but I forgot to fill the “key” and “value” information again. I didn’t realize that the fields blank as we switch between them.
Summing it up: It works when x-www-form-urlencoded selected but doesn’t work with form-data selected. Don’t know what the difference between them yet, but I’ll research it further.
By the way, it worked also with the suggestion from Rube Hart:

Cakephp -how to use and where to put debug($var) in $this?

I want to know the value of the associative array $this in cakephp, base on my research I could use debug($this);
however I don't know where to put it, model, view or controller, and I don't know where to see the result of debug($this);.
I'm trying to get the value of $this so that I can use them in making a rest api using json_encode.
To elaborate the process
Content or what is inside of $this(part which I want to see)
json_encode
ajax
any help suggestions or opinions is highly appreciated

Single method to handle post or loading view in laravel

I am trying to understand how POST routing will work. I have a method defined, signup(), and I want to use the same method to detect if the user wants to sign up (so load the signup view) or if the user already in the signup view (form) and posting his details to register.
Can this be done in one function in laravel? if yes, then how? Is this controlled by Routes and if yes, can someone please clarify this with an example?
Laravel documentation is really confusing for beginners.
Thanks in advance,
While this is possible but it's not recommended way to do that, you should keep your routes separated from each other (using GET and POST) and should use different methods as well. Basically any form submission should use POST request (using POST HTTP method) and to show the form just use a GET method but anyways, you can do it (what you have asked for) like this way:
// Declare the route
Route::post('signup', 'UserController#signup');
Now in your signup check for the submit button to make sure that, the form is submitted, so if the input submit is available in the $_POST array then the form is submitted otherwise, it's not submitted but an empty form was presented to the user or a failed validation redirect happened. Maybe something like this:
public function signup()
{
if(Input::has('submit')) {
// It's a submission, so Validate submitted Form data
// if invalid then redirect back with inputs and errors
// Otherwise save it
}
else {
// show the form
return View::make('user.signup');
}
}
Don't do it
This is just an idea but, it's a bad idea, just think about what happens if you have errors on your form and you want to redirect back then the whole thing would become messy, the controller method will become totally unmanageable after a while because it does many things while it should have only one specific responsibility.
I have this practical experience, because, I used to think that, if I can use one function for loading and saving and even also updating then it would be smart but to be honest it was stupid and obviously it's an anti-pattern, not the best practice, against KISS (Keep It Simple Stupid) principle. This kind of coding is a bad idea and you'll suffer for it in future and you would not dare to touch the code thinking that if you brake anything because you'll be confused by your own code.
Just use separate methods to show a form and save submitted data, Also check this on slideshare.
Yes, you can use one route to do it:
Route::any('signup', 'SignupController#signup');
Or two routes pointing to the same url:
Route::get('signup', 'SignupController#getSignup');
Route::post('signup', 'SignupController#postSignup');
In both cases you'll need a controller:
Here it is with all related methods:
class SignupController extends Controller {
// This one is for Route::any()
public function signup()
{
if (Input::has('email'))
{
// create your user
}
return View::make('signup');
}
// those two are for the second option
public function getSignup()
{
return View::make('signup');
}
public function postSignup()
{
// create your user
}
}

How to get a HTTPRequest JSON response without using any kind of template?

I am new to Django but i am advanced programmer in other frameworks.
What i intend to do:
Press a form button, triggering Javascript that fires a Ajax request which is processed by a Django View (creates a file) that return plain simple JSON data (the name of the file) - and that is appended as a link to a DOM-Element named 'downloads'.
What i achieved so far instead:
Press the button, triggering js that fires a ajax request which is process by a Django view (creates a file) that return the whole page appended as a duplicate to the DOM-Element named 'downloads' (instead of simple JSON data).
here is the extracted code from the corresponding Django view:
context = {
'filename': filename
}
data['filename'] = render_to_string(current_app+'/json_download_link.html', context)
return HttpResponse(json.dumps(data), content_type="application/json")
I tried several variants (like https://stackoverflow.com/a/2428119/850547), with and without RequestContext object; different rendering strats.. i am out of ideas now..
It seems to me that there is NO possibility to make ajax requests without using a template in the response.. :-/ (but i hope i am wrong)
But even then: Why is Django return the main template (with full DOM) that i have NOT passed to the context...
I just want JSON data - not more!
I hope my problem is understandable... if you need more informations let me know and i will add them.
EDIT:
for the upcoming questions - json_download_link.html looks like this:
Download
But i don't even want to use that!
corresponding jquery:
$.post(url, form_data)
.done(function(result){
$('#downloads').append(' Download CSV')
})
I don't understand your question. Of course you can make an Ajax request without using a template. If you don't want to use a template, don't use a template. If you just want to return JSON, then do that.
Without having any details of what's going wrong, I would imagine that your Ajax request is not hitting the view you think it is, but is going to the original full-page view. Try adding some logging in the view to see what's going on.
There is no need to return the full template. You can return parts of template and render/append them at the frontend.
A template can be as small as you want. For example this is a template:
name.html
<p>My name is {{name}}</p>
You can return only this template with json.dumps() and append it on the front end.
What is your json_download_link.html?
assuming example.csv is string
data ={}
data['filename'] = u'example.csv'
return HttpResponse(simplejson.dumps(data), content_type="application/json")
Is this what you are looking for?

Backbone.js PUT/DELETE problems with Codeigniter REST server

NOTE: This question is related to CodeIgniter-RestServer
When I call model.save() from backbone the function where the put request is routed doesn't gets any PUT data. Firebug shows right PUT parameters being sent. However $this->put('keyname') always returns false. Which means CI's REST Server can't find PUT data as it should.
On the other hand, If I set:
Backbone.emulateJSON = true;
I can work, as then Backbone will send all PUT data under a single attribute named "model", using this way $this->put('model'); works
Then the extra effor involved is:
$data = json_decode($this->put('model'),true); // to get normal behavior #sucks
I was running into this issue as well and pushed a few changes that fix the problem:
https://github.com/philsturgeon/codeigniter-restserver/pull/84
have been through this problem already in the past. Solution to this problem is to use this inside your functions:
$data = $this->request->body;
echo $data['id'];
Hope that solves it. Cheers!

Resources