jQuery ajax post request doesn't work suddenly, - ajax

I have a jQuery ajax call in my ZF2 application. It just worked before. Suddenly it won't work anymore. Even when I put a non-existent action in the request, it doesn't give a server error like it did before. It just seems like it doesn't make the request.
There's absolutely no errors in the console. Everything works up until the point where I make the request. This is the function it's in:
$('.expand').click(function(){
var CCID = $(this).parent().attr('id');
CCID = parseInt(CCID);
console.log(CCID); // Works
if($.inArray(CCID,$expanded) > -1){
foldin(CCID);
} else {
console.log('Works up to here.'); // Works
$.post('admin/expand', {
id: CCID
},function(data){
console.log('Doesn\'t log this.'); // Doesn't work
if(data.hasOwnProperty('info')){
console.log('sup');
expand(data.info);
} else {
console.log('Can\'t find customer info.');
}
},'json');
}
});
Like I said before, absolutely no errors, and logs all the bits that I commented that do. Kind of hoping I made a stupid mistake and you can spot it. Been over it a bunch of times already, can't find it.
I'll add the action in my controller if anyone want to see it, but the post request doesn't even seem to look for it, because it doesn't give an error if I give it a bogus action.
edit: below is some extra information
So I added a failure handler at the request of a commenter, it returned:
failed [Object, "parseerror", SyntaxError]
In SyntaxError it says "unexpected token <", but there's none in the .js file and I can't find where it tells me what line/file it finds it in. That would help, probably.
This is the action I call in my controller. Doesn't seem to find it at all though:
public function expandAction(){
$request = $this->getRequest();
$response = $this->getResponse();
if($request->isPost()){
$post_data = $request->getPost();
$CCID = $post_data['id'];
$customer = $this->getCustomerTable()->getCustomer($CCID);
$response->setContent(\Zend\Json\Json::encode(array(
'info' => $customer,
)));
}
return $response;
}

Arun P Johny taught me to use the Network tab in Google Chrome developer tools to figure out the problem. From there I could see that the path 'admin/expand' should've been 'expand'.
Might be a bit of a localized answer but I feel that his advice to use the network tab was helpful enough to warrant an answer. Maybe it'll be helpful to someone else at some point.

Related

Redirect using get and then redirect to the response

Lets start off with the code
if($request->berbix == true || $request->berbix == 'true'){
THIS IS WHERE I NEED THE LOGIC TO GO
}
else {
session()->flash('flash.banner', 'Profile updated!');
session()->flash('flash.bannerStyle', 'success');
return Redirect::route('dashboard');
}
In the if statement this is what needs to happen.
user needs to be send to /verification/create with their user model
When that is completed, it will provide a URL
user then needs to be redirected to said URL
I know this should be simple but I am having a HECK of a time wrapping my head around the simple logic. The main thing I am struggling with (and I know why, but don't know how to solve it), is when I do for example Http::get() it isnt sending it as the user so the request doesn't know the user info
Any help either a solution or a nudge on what I need to do would be very nice right now!
While I would still consider redirecting to a different route/controller to handle this, since you said you want it all in one place, it is possible to call controller methods directly and retrieve a response without leaving the current method or creating another HTTP request.
You could do something like this.
$url = app()->call('App\Http\Controllers\VerificationController#create', [
'user' => auth()->user()
]);
if ($url) {
return redirect($url);
}

Test the view that is showing after authorisation

I am learning how to do simple tests on my application. Simply, I dont know how to get over the problem below.
Problem:
I am just trying to see, if my page is loading correctly by checking if site contain word "Send". Send is my button that is located in my view.
How can I check the view as a logged user?
My test function:
public function testSiteIsLoadingCorrectly()
{
$response = $this->get('/homepage');
$response->assertSee("Send");
}
After some research I got this function:
public function testSiteIsLoadingCorrectly() {
$user = User::factory()->create();
$response = $this->actingAs($user)
->withSession(['banned' => false])
->get('/');
$response->assertSee("Welcome on my page!");
}
It works great but only for "/". If I give another route, my console is showing a lot of text and finally it doesn't work.
How can I solve this?
assertSee() works bad with polish chars like ą,ę,ć etc...
That's the reason of all problems.
PS.
"Send" in Polish means "Wyślij"...

laravel 4.2. user permissions and hiding link source

I am a total newbie with Laravel and learning it now for a week. I have some basic questions that I can't find an answer to. Next week I will start with developing CRM system and I need some info from experienced developers who could tell me is the approach I am attending to make a good one.
I will need some authentication system, like 4 groups of users (Admin, Basic, Manager, Office) where Manager and Admin will add the Basic users. There will be few view and features and every groups will have defined access to each view and feature. Since few days I am searching for packages, watching the tutorials and learning. I found an interesting package for which I think it could help me with this user-group-permission things.The package is Sentry. Could this help me with my requirements?
What is the case when for example I have a user in group Basic and he deletes for example some comment with the button. On the left side down in the browser the user can see the link to this comment when he hovers the link. For example www.test.com/comments/345/delete where the id is 345. What if user types that with another id, that means he can delete another comment. I found some suggestions on how to solve this, to make it with jQuery and javascript so the link wouldn't be shown and POST would be made with for example with AJAX. But since I am a newbie, I am thinking how much time would this take and is this a good approach at all? Could package Sentry from 1. question help me with the permission on what route each group can access?
Any help or advice would be appreciated.
Sentry does what you want, yes. Here's a question with some answers explaining the permissions part.
The visible link part can be avoided by doing a POST request instead of a GET request.
When you open your form, you add a method attribute.
Form::open(array('url' => 'foo/bar', 'method' => 'post'))
A GET request will put the parameters in the URL, hence the visible ID. Using a POST request will put the parameters in the headers, thus hiding it from the URL.
An example could be deleting a comment. A GET request could look like this:
http://www.example.com/comments/delete/1
And the parameters would be defined in your method signature:
public function getDelete ($id) {
Comment::find($id)->delete();
}
Where the POST equivalent would be
http://www.example.com/comments/delete
And the parameters would be defined in your Input class, you would get them using the get method
public function postDelete() {
Comment::find(Input::get('id'))->delete();
}
1) The best package to help you with that is Sentry indeed.
2) To make sure an user can delete only his comments you can do something like this (but there are more solutions either you do it with Ajax or not):
public function destroy($id) {
$user = Sentry::getUser();
$comment = Comment::find($id);
if($comment) {
if($comment->user_id != $user->id) {
return Response::back(); // optional message: Permission denied!
}
$comment->delete();
return Response::back(); // optional with message: Deleted!
}
return Response::back(); // optional message: Comment not found!
}
You can use Sentry in this case to get the logged in user and check for user id. I think you should let user delete their own comments always but if you need special roles (Admins for example) to be able to delete any comment, or special permission comments.delete (For some Managers) - you can use Sentry as well:
public function destroy($id) {
$user = Sentry::getUser();
$comment = Comment::find($id);
if($comment) {
if($comment->user_id != $user->id && !$user->hasRole('Admin') && !$user->hasPermission('comments.delete'))) {
return Response::back(); // optional message: Permission denied!
}
$comment->delete();
return Response::back(); // optional with message: Deleted!
}
return Response::back(); // optional message: Comment not found!
}
A nicer way of making the DELETE thru a Form request check this:
Laravel RESTfull deleting

Laravel 4: redirect if item doesn't exists, ModelNotFoundException doesn't work anyway I try it

I'm following Dayle Rees' book "Code Bright" tutorial on building a basic app with Laravel (Playstation Game Collection).
So far so good, the app is working but, following his advices at the end of the chapter, I'm doing my homeworks trying to improve it
So, this snippet is working fine for existing models but throws an error if the item doesn't exists:
public function edit(Game $game){
return View::make('/games/edit', compact('game'));
}
In other words, http://laravel/games/edit/1 shows the item with ID = 1, but http://laravel/games/edit/21456 throws an error since there's no item with that ID
Let's improve this behaviour, adapting some scripts found also here on StackOverflow (Laravel 4: using controller to redirect page if post does not exist - tried but failed so far):
use Illuminate\Database\Eloquent\ModelNotFoundException; // top of the page
...
public function edit(Game $game){
try {
$current = Game::findOrFail($game->id);
return View::make('/games/edit', compact('game'));
} catch(ModelNotFoundException $e) {
return Redirect::action('GamesController#index');
}
}
Well... nothing happens! I still have the error with no redirect to the action 'GamesController#index'... and please notice that I have no namespaces in my Controller
I tried almost anything:
Replace catch(ModelNotFoundException $e) with catch(Illuminate\Database\Eloquent\ModelNotFoundException $e): no way
put use Illuminate\Database\Eloquent\ModelNotFoundException; in Model instead of Controller
Return a simple return 'fail'; instead of return Redirect::action('GamesController#index'); to see if the problem lies there
Put almost everywhere this snippet suggested in Laravel documentation
App::error(function(ModelNotFoundException $e)
{
return Response::make('Not Found', 404);
});
Well, simply nothing happened: my error is still there
Wanna see it? Here are the first two items in the errors stack:
http://www.iwstudio.it/laravelerrors/01.png
http://www.iwstudio.it/laravelerrors/02.png
Please, can someone tell me what am I missing? This is driving me mad...
Thanks in advance!
Here are few of my solutions:
First Solution
The most straightforward fix to your problem will be to use ->find() instead of ->findOrFail().
public function edit(Game $game){
// Using find will return NULL if not found instead of throwing exception
$current = Game::find($game->id);
// If NOT NULL, show view, ELSE Redirect away
return $current ? View::make('/games/edit', compact('game')) : Redirect::action('GamesController#index');
}
Second solution
As I notice you may have been using model binding to your route, according to Laravel Route model binding:
Note: If a matching model instance is not found in the database, a 404 error will be thrown.
So somewhere where you define the model binding, you can add your closure to handle the error:
Route::model('game', 'Game', function()
{
return Redirect::action('GamesController#index');
});
Third Solution
In your screenshot, your App::error seems to work as the error says HttpNotFound Exception which is Laravel's way of saying 404 error. So the last solution is to write your redirect there, though this apply globally (so highly discouraged).

Grails Hibernate Session or Spring Transaction destroying Domain validation errors

So my problem is that my validation errors are being deleted from my domain object before I can render them on the page. I thought I had fixed this error in the past, but it has crept up on me again.
Here is a look at my original implementation. The errors were being cleared when tripService.stepData(trip) was being called.
Edit- I should not that I only experienced this issue when the page adds to a hasMany relationship.
Controller -
Trip trip = tripService.savePrePaymentInfo(params)
if (trip.hasErrors()) {
render(view: "step4", model: tripService.stepData(trip))
}
else {
redirect(action: trip.status.action, id:trip.id)
}
Service -
Map stepData(Trip trip)
{
Map returnSet = [:]
returnSet.status = Status.findAllByActionNotEqual("review")
returnSet.trip = trip
returnSet
}
So I did some reading online and someone one on a forum post like 2 years ago said there was something in hibernate..possible bug... I don't know, but their suggestion worked. The suggestion was to wrap the controller in a withTransaction:
Trip.withTransaction {
//Controller code here
}
This has been working for me fine. The issue now is that I have a taglib in my view that calls tripService again. When that call is being made it is now clearing my validation errors. This is getting really frustrating. Does anyone have ANY idea on what I can do to resolve this?
Edit: Adding service method being called from taglib:
String findBannerName(Long pidm, String format = 'LFMI')
{
"abc"
//It really doesnt matter what is here - tried just returning this string and it produced the issue
}
Are you sure the trip.errors property is populated in the first place?
Also, which tripService method are you calling in the taglib?

Resources