Laravel URL Generator With Angular JS Varible - javascript

I am making an application with Angular JS as frond end and Laravel as back end.
I having a list of master data table view and a delete and edit options.
<a class="resedit btn btn-sm btn-default" href="{{URL::route('edit_repair_category',[[category.id]])}}/"><i class="icon-note"></i></a>
<a title="Delete" ng-click="deleteRow($event,category.id,'{{URL::route('delete_repair_category')}}',currentPage)" class=" btn btn-sm btn-delete"><i class="glyphicon glyphicon-trash"></i></a>
Above I am generating URL of Edit page with Laravel URL Generator, But I want to pass the ID of the master data to fetch the data from controller.
I am using [[ ]] for Angular JS bindings.
URL::route('edit_repair_category',[[category.id]])
Now I got the exception Use of undefined constant category - assumed 'category'
Routes.
Route::get('edit-repair-category/{id}', ['as' => 'edit_repair_category', 'uses' => 'RepairCategoryController#editRepairCategory']);
Is there any possibilities ?

The reason you're getting this error is because you're mixing javascript and PHP.
The PHP portion of you code is going to be processed on the server and then passed to the browser where the javascript is then going to be processed, so as far as PHP is concerned you are trying to use a constant.
Since category.id is just going on the end of the url you should be able to do something like:
<a class="resedit btn btn-sm btn-default" href="{{ URL::route('edit_repair_category', null) }}/#{{category.id}}"><i class="icon-note"></i></a>
null is being used here to prevent an error being thrown.
The # before {{category.id}} just tells blade to treat this like a normal string and not to do anything with it (the # symbol will be remove by blade).
Hope this helps!

Related

Not able to redirect to url of ejs file to router defined in js file having two parameters

I am working in node js and ejs file.
In router i am expecting two parameters as below line
router.get('/pettycashlistview/:expenseId&:isDisabled',verify,(request,
response) => {
one is expense id and another one is isDisabled as i am passing both parameters through a file and below line
pettyCashTableRows += '<tr><td colspan="4"><center><a target="_blank"
href="/expense/pettycashlistview/'+expenseId+'&'+buttonDisable+'"
>View All</a></center></td></tr>';
I want to pass same thing through ejs as the below line:
<a class="btn btn-primary btn-md bg-gray mb-mobile"
href="/expense/pettycashlistview?expenseId=<%= parentExpenseId %>"
id="createNewPettyCashButton">Go To Petty Cash</a>
How can i acheive the same thing for last line and what parameters i need to define that i should not get error buttonDisable is not defined.
How can I pass two parameters for
<a class="btn btn-primary btn-md bg-gray mb-mobile"
href="/expense/pettycashlistview?expenseId=<%= parentExpenseId %>"
id="createNewPettyCashButton">Go To Petty Cash</a>
generally I would split seperate parameters and not try to join them.
/pettycashlistview/:expenseId/:isDisabled would give you two seperate keys in the req.params object, one called expenseId and another called isDisabled.
You may need to parse the params to the correct datatype after extracting them from the req.params object (i.e. cast the isDisabled property to a boolean)

Angular return URL is wrong

In my Angular 5 Application I am doing something like this at
this.returnUrl = this.route.snapshot.queryParams['returnUrl']
I am using this when a user accesses a route but it's not logged in. He is redirected to the login page and after login he should be going back to this return url.
The problem is that http://localhost:4200/schedule?selectedDate=2018-01-29 when accessing this route, the return url becomes:
http://localhost:4200/login?returnUrl=%2Fschedule%3FselectedDate%3D2018-01-29 and after the successful login, the application tries to go to the http://localhost:4200/%2Fschedule%3FselectedDate%3D2018-01-29 URL but that throws a 404 error since it does not recognize the path.
Any idea how can I stop Angular changing my url to this format ? I was assuming that it would pick up the correct URL.
I managed to somehow fix this by instead of using
this.router.navigate(this.returnUrl)
I used
this.router.navigateByUrl(this.returnUrl);
i think You can simply add the url like this <button class="btn btn-md btn-danger pull-right" routerLink="../../">cancel</button>
or else call click event
Use this.
this.returnUrl = decodeURIComponent(this.route.snapshot.queryParams['returnUrl']);

How to handle name with slash as one path param in url

I have a route in app.js like
.when('/provider/:id/app/:aName', {
templateUrl: 'templates/provider/form.html',
controller: 'YourController'
});
in html:
<a class="btn btn-warning" ng-href="#/provider/{{id}}/app/{{appName}}">Edit</a>
However my appName will contain slashes, such as abc/test
so with inputs id = 1 and appName = abc/test, href will become
<a class="btn btn-warning" ng-href="#/provider/1/app/abc/test">Edit</a>
This is causing a problem, because my code presumes that the slash in the application name represents a different section of the website, the above href fails. So the URL will fail.
How to manage the app name with slash in url that is abc/test. Any help on this will be really helpful.
I have looked into this post stackoverflow, but unable to implement the same in my code. If I replace / with %2F then the app name changes. How to encode URL without affecting the actual app name

JSON: Uncaught SyntaxError: missing ) after argument list

In a rails app I have an object defined in a controller containing an icon and some values:
#data = "<i class='fa fa-circle fa-lg'></i><span>Speed: </span> #{b.speed.to_f} | Time: #{b.gps_date.try(:strftime, '%-m/%e %H:%M')}} <br />".html_safe.to_json
In view I parse it like this:
<script>
var data = JSON.parse('<%= raw #data.as_json %>');
</script>
But I get the following error:
Uncaught SyntaxError: missing ) after argument list
I works fine when I remove the icon code that contains the single quotes for class
<i class='fa fa-circle fa-lg'></i>
How can I fix this error?
You want to send the HTML string to JS so need of to_json, as this is used to convert Hash to JSON . So just use html_safe in server side.
And in client side, since you have the all HTML in string no need of as_json, just use the string as you would normally do in JS. as_json is a method used as ActiveRecord Serializer.
#data = "<i class='fa fa-circle fa-lg'></i><span>Speed: </span> #{b.speed.to_f} | Time: #{b.gps_date.try(:strftime, '%-m/%e %H:%M')}} <br />".html_safe
and
var data = <%= raw #data %>;
Basically this seems to be an issue with an unescaped ' popping up somewhere in JSON.parse('...'). You can verify the issue by looking at the HTML of the rendered page.
I think you might fix your issue by declaring (no need for the .to_json here):
#data = "<i class='fa fa-circle fa-lg'></i><span>Speed: </span> #{b.speed.to_f} | Time: #{b.gps_date.try(:strftime, '%-m/%e %H:%M')}} <br />".html_safe
And then in the view use
var data = "<%= escape_javascript #data %>";
as you are only tring to pass a string there is no need for the conversion into a JSON object and then parsing it back. (You'd need that if you wanted to pass a whole Javescript Object/Ruby Hash).
Actually for the last line there is also an equivalent shortcut/alias:
var data = "<%= j #data %>";
PS: I described how to fix the imminent issue but generally the point of MVC is to not have (or at least to minimize) presentation logic in a conroller. Generally it would be preferable to pass the data to the view and generate the HTML in the template.

Deleting Specific Record Using ObjectID

I'm defining a delete function in which, there's a delete button in each row, sending the ObjectID of that specific record to my Server Side, therefore, this ObjectId will be checked with the one stored in the database, resulting in deletion of that certain record, so far I could have make a good progress sending data's over, and checking on it, but I"m suspecting the ObjectId being sent, requires some sort of casting. Currently, the code and responses are as below;
Front-End (Index.Html)
<a href="#" class="list-group-item active" >
List Of Notes
</a>
<a href="#" class="list-group-item" ng-repeat="r in retrieve" >
{{r.create_at}}
<button style="float:right" type="button" ng-click="delete_note(r.ObjectId)"
class="btn btn-danger btn-xs">
Delete <i class="fa fa-trash"></i>
</button>
</a>
AngularJS (main.ctrl.js)
$scope.delete_note = function (data_id) {
$http.get('/delete_note', {
params: data_id
}).success(function(data){
console.log(data)
});
}
Back-End (Root.py)
#cherrypy.expose
#cherrypy.tools.json_out()
#cherrypy.tools.json_in()
def delete_note(self,*args,**kwargs):
res2=self.my_app.delete_note(kwargs)
return "<h1>delete success </h1>" +str(res2)
pass
Back-End (App.py)
def delete_note(self, index):
return self.db.notes.remove({'_id': index})
The current message appears in Google Chrome Console.log is this :
<h1>delete success </h1>{'ok': 1, 'n': 0}"
Which is obviously stating that, nothing has been changed within the database, I'm using Cherrypy, Mongodb, and Angularjs, any consideration is appreciated.
It'll be hard to locate the exact problem, but there are a few things that call for attention:
As nnnnnn already pointed out, nesting a button in an anchor (a) element is odd and might lead to weird issues.
The directive ng-click="delete_note(r.ObjectId)" looks odd: Does your python code really remap the _id field to a field called ObjectId? ObjectId is the type of (default) keys in MongoDB, the convention for the name is _id.
To find out, take a look at the network inspector when you GET the original data (i.e., $scope.retrieve) - what does it send? It's also helpful for debugging to output <pre>{{retrieve | json}}</pre> so you can see what ends up at angular
You're apparently deleting using a GET. While there's nothing that prevents you from doing that, writing with GETs is bad practice. If you possibly can, delete using an HTTP DELETE. If that's completely impossible for whatever reason, at least use a POST. But a GET should be nullipotent, i.e. it shouldn't change the server state at all.
The parameter to a REST request should be part of the URL, so your delete should read
DELETE /notes/:noteId, e.g. DELETE /notes/54fadec1e4259ded64c7576a
Putting the identifying parameter somewhere else violates the idea of resource urls.

Categories