Doesn't send the $scope to the html - ajax

I started to work in Angular few days ago, and I have a problem that I don't know how to fix.
My website is calling a controller.js and this controller calls to an ajax function. The ajax function sent back a correct response, but I can't see it in the web. Here is the code:
var myApp = angular.module('myapp',[]);
myApp.controller('ResolveProduct', ['$scope', function($scope) {
productInformation = function($scope) {
var something;
$.ajax({
type: "GET",
dataType : "json",
async : true,
url : "/ajax/reference/200-B2",
success : function(data) {
something = data.david;
alert(JSON.stringify(something));
$scope.helper = JSON.stringify(something);
},
complete : function($scope) {
$scope.helper = JSON.stringify(something);
alert($scope.helper);
}
});
};
}]);
This sent me a correct answer, but when I do this in the HTML I don't see the answer. (Even if the alert has all the info)
<div ng-controller="ResolveProduct">
<input ng-model="info"></input> information is: {{ $scope.helper }}
<input type="button" id="commitAction" class="slim-button" value="Resolve" onclick="productInformation('')"/>
</div>

You don't need to call $scope in the html side, so change {{$scope.helper}} to {{helper}}
<div ng-controller="ResolveProduct">
<input ng-model="info"></input> information is: {{ helper }}
<input type="button" id="commitAction" class="slim-button" value="Resolve" onclick="productInformation('')"/>
</div>
Update
You have passed empty values to the $scope from the onclick="productInformation('')" method. So the $scope values are cleared .
Please copy and past my code instead of your code.
Js code
var myApp = angular.module('myapp',[]);
myApp.controller('ResolveProduct', ['$scope', function($scope) {
$scope.productInformation = function()
{
var something;
$.ajax({
type: "GET",
dataType : "json",
async : true,
url : "/ajax/reference/200-B2",
success : function(data){
something = data.david;
alert(JSON.stringify(something));
$scope.helper = JSON.stringify(something);
},
complete : function($scope){
$scope.helper = JSON.stringify(something);
alert($scope.helper);
}
});
};
}]);
Html Code
<div ng-controller="ResolveProduct">
<input ng-model="info"></input> information is: {{ helper }}
<input type="button" id="commitAction" class="slim-button" value="Resolve" **ng-click="productInformation()"**/>
</div>
Also, I have changed onclick to ng-click in your button and assigned the function with $scope in your js side ( see the change productInformation to $scope.productInformation)

You should use {{ helper }} instead of {{ $scope.helper }}.
Also, after $scope.helper = JSON.stringify(something); you should add $scope.$apply().
You need to call $scope.$apply() because you are assigning a value to $scope.helper outside the digest loop (because you are using $.ajax from jQuery).
An explanation for the digest loop in angular can be found here: How do I use $scope.$watch and $scope.$apply in AngularJS?

Please check whether it works
<div ng-controller="ResolveProduct">
<input ng-model="info"></input> information is: {{helper }}
<input type="button" id="commitAction" class="slim-button" value="Resolve" onclick="productInformation('')"/>
</div>
You can't use $scope here
Refer this for help:
http://www.bennadel.com/blog/2457-accessing-scope-on-the-dom-using-angularjs.htm

Related

Laravel Ajax Update 1 Column of record

I have a user schedule record that I can update easily without one form field called disabled_dates. disabled_dates is setup to store an array of dates a user can add one at a time. What I did was add a form field with its own button using a javascript function disable() in the onclick attribute to update the record.
<div class='input-group text-center'>
{!! Form::text('disabled_dates', null , ['class' => 'form-control text-center datetimepicker15', 'id' => 'disable_date', 'placeholder' => '']) !!}
<span class="input-group-btn">
<button type="button" onclick="disable();" class="btn btn-fab btn-round btn-success">
<i class="material-icons">add</i>
</button>
</span>
Then created the disable(); like so
function disable() {
var CSRF_TOKEN = '{{ csrf_token() }}';
var disabled_date = document.getElementById('disable_date').value;
$.ajax({
type:'PUT',
url:'/schedule',
data:{_token: CSRF_TOKEN, blocked_date: disabled_date},
success:function(response) {
console.log(response);
}
});
}
The controller function used is
public function add_blocked_day(Request $request)
{
$schedule = User::find(auth()->user()->id)->schedule;
$current_blocked_dates = $schedule->disabled_dates;
$schedule->disabled_dates = $current_blocked_dates. ','.$request->blocked_date;
$schedule->save();
exit;
}
All Im getting now is too many redirects. The solution Im thinking is to seperate disabled_dates and enclose in its own form tags, because its calling the original form route somehow
I got it to work by changing the function to this
$(document).on("click", ".add-day" , function() {
var CSRF_TOKEN = '{{ csrf_token() }}';
var disabled_date = document.getElementById('disable_date').value;
$.ajax({
type:'POST',
url:'schedule/blocked-day',
data:{_token: CSRF_TOKEN, blocked_date: disabled_date},
success:function(response) {
console.log(response);
}
});
});

MVC 4.x Validate dropdown and redirect to next page

Beginner question:
I have an MVC app where there are three dropdowns on a page. Currently I'm using AJAX to evaluate a drop down on form submission and modify a CSS class to display feedback if the answer to the question is wrong.
HTML:
<form method="post" id="formQuestion">
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<p>This is a question:</p>
</div>
<div class="col-md-4">
<select id="Question1">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="col-md-4 answerResult1">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button class="btn btn-success" type="submit" id="btnsubmit">Submit Answer</button>
</div>
</div>
</form>
AJAX:
#section scripts {
<script>
$(document).ready(function () {
$("#formQuestion").submit(function (e) {
e.preventDefault();
console.log($('#Question1').val())
$.ajax({
url: "/Home/DSQ1",
type: "POST",
data: { "selectedAnswer1": $('#Question1').val() },
success: function (data) { $(".answerResult1").html(data); }
});
})
});
</script>
}
Controller:
public string DSQ1(string selectedAnswer1)
{
var message = (selectedAnswer1 == "3") ? "Correct" : "Feed back";
return message;
}
I have three of these drop downs, that all get evaluated by AJAX in the same way. My question is, how would I go about evaluating all three and then returning a particular View if all three are correct.
I would like to avoid using hard-typed http:// addresses.
You could declare a global script variable prior to your document ready function, this will determine if the fields are valid. See var dropdown1Valid = false, ....
Then on your ajax success function, you could modify the values there. Say in the ajax below, your answering with first dropdown, if your controller returned Correct, set dropdown1Valid to true.
Lastly, at the end of your submit function, you could redirect check if all the variables are true, then redirect using window.location.href="URL HERE or use html helper url.action window.location.href="#Url.Action("actionName");
#section scripts {
<script>
var dropdown1Valid = false;
var dropdown2Valid = false;
var dropdown3Valid = false;
$(document).ready(function () {
$("#formQuestion").submit(function (e) {
e.preventDefault();
console.log($('#Question1').val())
$.ajax({
url: "/Home/DSQ1",
type: "POST",
data: { "selectedAnswer1": $('#Question1').val() },
success: function (data) {
$(".answerResult1").html(data);
if(data == "Correct"){
// if correct, set dropdown1 valid to true
dropdown1Valid = true;
}
// option 1, put redirect validation here
if(dropdown1Valid && dropdown2Valid && dropdown3Valid){
// if all three are valid, redirect
window.location.href="#Url.Action("actionName","controllerName", new { })";
}
}
});
// option 2, put redirect validation here
if(dropdown1Valid && dropdown2Valid && dropdown3Valid){
// if all three are valid, redirect
window.location.href="#Url.Action("actionName", "controllerName", new { })";
}
})
});
</script>
}

how to fix occasional return data when uploading file with ajax

I have a problem with my code. I created upload file with ajax in Laravel. I am using tutorial from here, and yes it is working. But, it working sometimes.
I have no idea where the problem is. But I have changing max_execution_time in php.ini into 0 value. I also included <code>csrf_token()</code> in ajax headers
I wish there somebody help me with this code. I don't know, but the code looks good for me. Here is the code
blade view
<form class="form-main" enctype="multipart/form-data" method="post" id="formbank" >
<div class="field file" data-title="Upload File">
<input type="file" id="myfile" name="myfile" accept="image/*">
<label for="myfile"><i class="fa fa-upload"></i> <span id="file-title">Select File</span></label>
</div>
<div class="field" data-title="Action">
<button class="but-main">Submit</button>
</div>
</form>
JS script
$(document).ready(function(e){
$('#formbank').on('submit',function(e){
e.preventDefault();
var fd = new FormData(this);
fd.append('myfile',$('#myfile')[0].files[0]);
$.ajax({
async: true,
type:'post',
data:fd,
contentType: false,
cache:false,
processData: false,
headers: {
'X-CSRF-TOKEN' : "{{ csrf_token() }}"
},
url: "{{ route('post.bank') }}",
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
});
});
post.bank controller
public function createBank(Request $request){
if ($request->hasFile('myfile')) {
$file = $request->file('myfile');
return $file->getClientOriginalName();
}
else {
$text = 'empty';
return $text;
}
In this case, I only try to return name of uploaded file. Here is the result.
https://drive.google.com/file/d/1zK5YmO8f8cGR110X-oi2bTVMiaMCXYi9/view?usp=sharing "result"
Thank you for all suggestion. Many thanks. After several trial and errors, I find a trick to resolve it by calling main function with setTimeOut(). And i put _token validation in controller. When token is empty, it will return a value that let setTimeOut() do the rest of time until token is loaded correctly.
I guess that way is suited for me. And I will be happy if there is a better answer to resolve it in a better way. Thank you anyway..

Laravel ajax return 404

I'm trying to send data to back-end and i'm getting 404 error with this explanation in network tab:
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
Route
Route::middleware('verified')->group(function () {
Route::post('/snaptoken/{id}', 'Admin\PayController#token')->name('securepaymentnow');
});
Controller
public function token(Request $request, $id)
{
//Find project
$project = Project::findOrFail($id);
//rest of data
}
Blade
//form and button
<form id="payment-form" method="POST" action="{{route('securepaymentnow', $project->id)}}">
#csrf
<input type="hidden" name="result_type" id="result-type" value="">
<input type="hidden" name="result_data" id="result-data" value="">
</form>
<button class="btn-sm bg-success pay-button" data-id="{{$project->id}}" type="submit"><i class="fas fa-fas fa-shield-alt"></i> Secure Payment</button>
//javascript
$('.pay-button').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/securepaymentnow")}}/'+encodeURI(prdfoId),
type: "POST",
cache: false,
success: function(data) {
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
}
});
});
Any idea?
.........................................................................................................................
if you are using url() function, you should use the {{ url('/snaptoken') }}.
But if you want to use the "name" from the "securepaymentnow", use route() function with this example {{ route('securepaymentnow', $theId) }}.
Both should works.
Refer Laravel NamedRoute for details.

Using ng-repeat after $http call

I'm learning Angular (1.6.6), so I'm hoping/assuming I'm missing something basic.
I'm populating a drop-down menu on ng-init, which is working as expected. I'm returning JSON from the DB, and console.log() shows me that the JSON is pulling through as expected.
I'm stuck with ng-repeat, trying to display the data in another div.
My Controller
app.controller('RandomTownCtrl', [
'$scope',
'$http',
function($scope, $http){
window.MY_SCOPE = $scope;
$scope.getAllRegions = function() {
$http({
method: 'GET',
url: '/all-regions'
}).then(function successCallback(response) {
$scope.regions = response.data;
}, function errorCallback(response) {
console.log('error');
});
};
$scope.getRandomTown = function() {
var guidEntity = $scope.guidEntity;
if (typeof guidEntity === 'undefined') { return };
$http({
method: 'GET',
url: '/region-name?region-guid=' + guidEntity
}).then(function successCallback(response) {
$scope.randomTown = response.data;
console.log($scope.randomTown);
}, function errorCallback(response) {
});
};
}
]);
The Markup
<div class="column col-sm-5 content-column">
<form ng-controller= "RandomTownCtrl" ng-init="getAllRegions()" ng-submit="getRandomTown()">
<h3>Generate Random Town</h3>
<div class="form-group">
<select name="nameEntity"
ng-model="guidEntity"
ng-options="item.guidEntity as item.nameEntity for item in regions">
<option value="" ng-if="!guidEntity">Choose Region</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Generate!</button>
</form>
</div>
<div class="column col-sm-5 content-column" id="output-column">
<div class="header">
<h4>Region Name:</h4>
</div>
<div ng-controller='RandomTownCtrl'>
<p ng-repeat="item in randomTown">
{{ item.name_region }}
</p>
</div>
</div>
You are mixing $scope and self together, you need also ng-repeat needs an array not an object.
$scope.randomTown = response.data;
Beginner Angular mistake: I didn't understand that the ng-controller directive created an isolate scope, and the output I was expecting wasn't happening because the data simply wasn't there in that scope.

Resources