set variable in angular without interrupting form post - javascript

I need to use an asp.mvc form post. I use some angularjs on the client side. I know this question is not doing everything the "angular way".
What I need to do is set a variable $scope.IsUploadingData when the post happens so I can disable the buttons and show something to indicate progress. I have tried using ng-click, but it seems to stop the post from happening. Is there anyway to set the variable without interrupting the form post?
#using (Html.BeginFormAntiForgeryPost(Url.Action("Accept", "Members", new { area = "Testing" })))
{
other form stuff here
<span class="input-group-btn">
<button ng-disabled="IsUploadingData == true" name="accept" type="submit">Submit</button>
<button class="btn btn-default" ng-disabled="IsUploadingData == true" name="reject" type="submit">Reject</button>
<img ng-show="IsUploadingData" src="/SiteMedia/spinner[1].gif" />
</span>
}

It looks like you could use ng-submit to control the submission process and set $scope.IsUploadingData in the function you call from ng-submit. This is a decent write-up on ng-submit: http://learnwebtutorials.com/angularjs-tutorial-submitting-form-ng-submit

Related

How to add a new webpage to ASP.NET MVC

Right now I am making a MVC that has a default page that loads up. From this page, the user can press a button to go to the next page. So far, I have made the first page work and a button that goes to a specified URL for the second page. The only issue I am having is making the view that I want to correspond to the second page have the correct URL.
Here is the code for my button link to the next URL
<input type="button" value="Create" onclick="location.href='#Url.Action("IndexA", "HomeController")'" />
I guess my question is how do I make my view have the specified URL that I want so it can be accessed?
I used something like this in my own project.
#if (Request.UrlReferrer != null && Request.UrlReferrer.Host == Request.Url.Host)
{
<a href="#Request.UrlReferrer" class="dbtn btn-11">
<i class="fa fa-undo"></i>
#Resources._Action_Back
</a>
}
only came from within the domain that was published I said let the button appear.
there is something like add controller in default settings controller name + controller. So just write the name there.
I had to put "home" in the URL.Action instead of "HomeController"
Please see this photo.
https://ibb.co/4SS5nYh
You add a new controller and a new view for that new page (also a model). I have called mine Test.
Then in the button. you call them with url action.
<input type="button" value="Create" onclick="location.href='#Url.Action("Index", "Test")'" />

How to listen the 400 (Bad Request) with Angular *ngIf?

I won't paste any code, since this is a general question. I need to figure out how to listen if nothing returns. I can't get any objects, since nothing exists. I only receive on my GET request a message "400 (Bad Request)".(console).
How can I disable a button if there is a "400 (Bad Request)" (nothing exists)?
Is there a way to listen this on frontend?
Thanks
In Angular2 you would need to capture the error from the response.
badRequest: boolean = false;
this.appService.myHttpCall.subscribe(
data => // do something with success,
error => {
if(error.status == 400){
this.badRequest = true;
}
});
And use the result in your template. If you really want to go the *ngIf route you would do this:
<button *ngIf="badRequest" type="button" disabled>My Button</button>
<button *ngIf="!badRequest" type="button">My Button</button>
You would essentially have to code two buttons, both with *ngIf statements to get the result you want.
If you want to use the [disabled] attribute you would do this:
<button [disabled]="badRequest" type="button">My Button</button>
However, I would not disabled a button if a BadRequest happens, because then how would the user resubmit the form after correctly filling it out? For example, if the user leaves a required field blank, the server returns a BadRequest and disables the button. Then the user cannot correct the missing field and re-submit the form.
What I would do instead is to toggle the button's disabled attribute based on the validity of the form like this:
<form (ngSubmit)="onSubmit()" #myForm="ngForm">
...inputs....
<button type="submit" class="btn btn-success" [disabled]="!myForm.valid">SUBMIT</button>
</form>
Hope this helps.

Submitting a post request through Vuejs and axios to a laravel back-end

I need some help in implementing a basic ajax request through vue to my laravel back-end, I have a boolean named completed on a table called courses, and I have a view that fetches all courses assigned to a specific user and allows them to press a button to change the current status of the course, either completed or not, that's it, that's all I wanna do, right now I can do it normally through get and post requests, obviously results in a refresh of the page, I want that to be dynamic with just refreshing the dom, I am so frustrated that I couldn't figure this out on my own because I think It should be easy, turns out I know nothing when it comes to using vuejs.
Here is the significant part of my CoursesController:
public function toggling($name)
{
$course = Course::where(['name' => $name])->first();
$course->completed = !$course->completed;
$course->save();
// return redirect()->back();
return response()->json(['course' => $course], 202);
}
And here is the significant part of the view that provides the courses to the user, it's a part of a table:
<td>
<form method="POST" #submit.prevent="onSubmit" action="{{ route('course.completed', $course->name) }}" id="form-submit">
{{-- {{ method_field('PUT') }} --}}
{{ csrf_field() }}
#if ($course->completed == true)
<button type="submit" class="btn btn-sm" id="coursetogglingtrue">Done!</button>
#else
<button type="submit" class="btn btn-sm" id="coursetogglingfalse">Not Yet!</button>
#endif
</form>
</td>
For some reason the #submit.prevent method is not working, it worked a couple of times but then It just didn't, and the form kept submitting as usual.
These are the scripts inside app.blade.php, I don't know how/where should I compile this, it's just sitting there in the main layout of my project, should I transfer it to public/js/app.js? or compile it using gulp? if you have something in mind please let me know:
<!-- Scripts -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue#2.1.10/dist/vue.js"></script>
<script src="/js/app.js"></script>
<script>
new Vue({
el: '#app',
data: {
course: {}
},
methods: {
onSubmit() {
// course = $event.target;
axios.post('/MyCourses/{{course.name}}').then(console.log(course));
}
}
});
</script>
I want to have course be equal to whatever value of the request was, so that I can then target the value of the name of the course that was submitted and inject it to the route as I'm trying to do, but I'm not sure how to do that, I tried a few different things, all failed.
And here is routes/api.php
Route::post('/MyCourses/{name}', 'CoursesController#toggling')->name('course.completed');
ofc right now this is not working, the form is submitting, and I'm redirected to a route where I get back the json response, and that's it, I just want to refresh the dom so that the button would have the new id depending on that status of the course, and the course itself to be updated and saved in the background without refreshing the page.
I am fairly new to this, I understand that the form should probably be re-written, and I know I've done a lot of mistakes, but I just want it to work, so help would be very appreciated.
UPDATE
After a lot of hours of trial and error, I'm done with the ajax part and I'm almost there with the rest I just need to do a few things, this is what I've managed to do so far,
In the view:
<form method="POST" #click.prevent="onSubmit" action="{{ route('course.completed', $course->name) }}" id="form-submit">
{{ csrf_field() }}
#if ($course->completed == true)
<button type="button" class="btn btn-sm" id="coursetogglingtrue">Done!</button>
#else
<button type="button" class="btn btn-sm" id="coursetogglingfalse">Not Yet!</button>
#endif
Changing the type of the button from submit to button allowed the .prevent method to actually fire, now the form doesn't submit anymore, the form still needs work in order to output the proper class depending on the status of the course but regardless,
This is the script that I have now:
<script>
new Vue({
el: '#app',
data: {
course: {
name: '',
bool: false
}
},
methods: {
onSubmit: function() {
this.course.bool = !this.course.bool,
axios.post('/MyCourses/{{$course->name}}')
.then(function (response){
// {{$course->completed}} = response.course.completed;
});
}
}
});
</script>
Somehow right now, I'm actually sending the post request to the correct route, but there's a problem which has the highest priority right now, $course is referencing the latest course that was added to the page, and not the course that I chose by pressing on the button, now whichever button I press, the last course gets injected to $course, and then ofc to the route in axois, I don't know how to figure that out yet, but so far that course gets updated, and if I inspected the network tab in chrome, I see the response and that value of the completed column gets updated, I believe that there are still some mistakes in the code, but I'll keep trying, if you can point out some more things please let me know, thanks
An improvement to the answer above would be to use Template Literals introduced in ES6.
Instead of:
axios.post('/MyCourses/' + course.name).then(console.log(course));
You can do:
axios.post(`/MyCourses/${course.name}`).then(console.log(course));
More information on Template Literals functionality and syntax can be found here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
The syntax you are using is wrong in following line:
axios.post('/MyCourses/{{course.name}}').then(console.log(course));
It should be :
axios.post('/MyCourses/' + course.name).then(console.log(course));

Ajax on button click, but no forms involved

I would like to make an Ajax call on a button click, but I do not want the button placed within a form. Is this possible?
Yes, Ajax doesn't involve forms. It's basically a request that you create yourself to the server - either GET or POST. Make the request and pass whatever data you need to
Use this bit of code
<button onclick=function()>Button</button>
It is possible:
<form action="example.com" method="post">
...
</form>
<button name="button" id="button">Submit</button>
Way 1: use jquery selector and bind an event.
$('#button').click(function(e) {
//--> actions here
});
Way 2: or call a function in the button:
<button name="button" onclick="javascript:action();">Submit</button>
There's a lot to choose from.

How to perform a check on ng-disabled in angularjs?

I am using a fuelUX Wizard and Angularjs. I would like the next button to be enabled or disabled basing on this controller method:
$scope.canMoveForward = function(){
switch($("#moduleWizard").wizard("selectedItem").step){
case 1:
//check if the module on the first step is valid*/
return $scope.validSelection && $scope.linkedPredicateForm.$valid;
case 2:
//check if the table is empty
return !linkingDataSource.isEmpty();
case 3:
var enab= ($scope.saveModeForm.$valid && $scope.newSourceForm.$valid) ||
($scope.saveModeForm.$valid && $scope.appendSourceForm.$valid)
}
};
So indeed this is how I decleared the buttons:
<div class="actions">
<button class="btn btn-mini btn-prev" ng-click="refresh()"> <i class="icon-arrow-left"></i>Prev</button>
<button class="btn btn-mini btn-next" data-last="Finish" id="wizard-next" ng-disabled="!canMoveForward()"
ng-click="handleStepResult()">
Next<i class="icon-arrow-right"></i></button>
</div>
And it works fine, except when I get back from the second page to the first page: if the next button is disabled in the second page it will be this way even on the first page, unless I don't edit the form there. Is there anyway to refresh the ng-disabled binding?
I guess AngularJS cannot check if the output of canMoveForward() has changed or not. I found that for this kind of things it's easier to rely on scope variables. You could do something like this:
ng-disabled="!canMoveForward"
Then in your controller just set the property to true/false as needed:
$scope.canMoveForward = false;
I have had the same problem and I've discovered that the problem is with the ! operator.
This fails:
ng-disabled="!canMoveForward()"
But this will work:
ng-disabled="canNotMoveForward()"

Categories