Best practices angularjs ajax request and redirect - ajax

I have a originCtrl template and controller. In this one i have a button to go to another template and controller. But on the destCtrl, i need information from an ajax request.
This is a part of my controller code:
.controller('OriginCtlr', function ($scope, $rootScope, $http, $location, $cookies) {
$scope.startTest = function () {
$http.post(API_URL + 'creates/tests.json', {'id':$scope.dic.id, 'nbQuestion':$scope.nbquestion}).success(function (data) {
$rootScope.words = angular.toJson(data.words);
$location.path('/questions');
});
};
})
.controller('DestCtrl', function ($scope, $http, $location, $cookies) {
$rootScope.$watch('words', function(newValue, oldValue) {
scope.word = scope.counter + 1;
});
})
I want to know where i have to do my ajax request:
1) do ajax request in the originCtlr, data in rootScoope, and redirect after success
2) do ajax request in the originCtlr, data in rootScoope, and redirect
3) pass argument in $location.pathand do ajax request in the destCtlr
4) ???

If you want to share data between controllers you should be using a service.
.service('testsService', function ($http, $location) {
this.words = {};
this.createTests = function (id, question) {
$http.post(API_URL + 'creates/tests/json', {id: id, nbQuestion: question})
.success(function (data) {
this.words = angular.toJson(data.words);
$location.path('/questions');
}.bind(this));
}
})
Then you can inject testsService into your controllers and access words from the service instead of using $rootScope.

Related

How to send object for request in Laravel controller from Vue JS frontend by GET request?

I have created a function in my controller that receives a request and does some calculations after that and stuff. Currently I am just showing the request array for checking:
public function check_availability(Request $request){
dd($request->all());
//other works to use this request values
}
Now when I am sending a request to the route which hits this function using postman like this:
So it is working perfectly from postman. But the same request is returning blank request array when I am sending the request from my vue js application.
var data= {
"qty": 1000,
"id": 1
}
var config = {
method: 'get',
url: 'http://127.0.0.1:8000/api/check_quantity',
data: data
};
axios(config)
.then(function (response) {
console.log("returned :", response)
commit('set_products', payload);
})
.catch(function (error) {
console.log("this is error:",error);
});
This is returning blank array! This is working when I am configuring the whole system in POST method. How can I solve this using get method?
to pass data in get method you have to add them in query params like ?=foo=bar
so your code should like like
var data= {
qty: 1000,
id: 1
}
var config = {
method: 'get',
url:`http://127.0.0.1:8000/api/check_quantity?qty=${data.qty}&id=${data.id}`,
};
axios(config)
.then(function (response) {
console.log("returned :", response)
commit('set_products', payload);
})
.catch(function (error) {
console.log("this is error:",error);
});

CSRF token mismatch while uploading image using ajax in CakePHP 3.6

I have tried
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
$this->getEventManager()->off($this->Csrf);
}
public function ajaxEdit($id = null)
{
$this->autoRender = false;
debug($id);
debug($this->request->getData());
}
And I am using ajax code
$(document).ready(function(){
$('#user-profile').change(function(){
$('.loader-body').show();
var form = $('#user-profile-image')[0];
var formData = new FormData(form);
var tutorial_id = $('#user-file-id').val();
$.ajax({
url :"/users/ajax-edit/"+tutorial_id,
method:"POST",
data:formData,
contentType:false,
cache: false,
processData:false,
success:function(data){
let parseData = $.parseJSON(data);
if (parseData.status === true) {
location.reload();
var value = parseData.url;
console.log(value);
} else {
alert(parseData.message);
}
}
});
});
});
I have followed help from these links
CakePHP ajax CSRF token mismatch
2 https://book.cakephp.org/3.0/en/controllers/components/csrf.html
Getting CSRF token mismatch (see attached image)
https://i.stack.imgur.com/FsVZu.png
First of all if your are using POST method in your ajax call then you should send tutorial_id as data instead of sending it in the url.
You can resolve this by sending you CSRF token through a special X-CSRF-Token header in your ajax call.
https://book.cakephp.org/3.0/en/controllers/components/csrf.html
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
},
OR
You can disable CSRF component[Not recommended by the Cakephp] for your ajax action like:
public function beforeFilter(Event $event) {
if (in_array($this->request->action, ['ajaxEdit'])) {
$this->eventManager()->off($this->Csrf);
}
}

Updating View in Angular js on ajax success callback

I am working on a project where I am getting list of the offers from a service.
Each offer is Active or Inactive. I am displying only Active offers on a view on tabular format by giving ajax call and using ng-repeat.
When I click on the link Inactivate Offer
then I am giving another ajax request to inactivate that offer in database. So once I inactivate offer it should not be displyed on view.
My code to fect offer and Inactivate the offer is :
mPosServices.factory('mosServiceFactory',function($http,$rootScope){
return{
viewAllOffers:function(){
var allOffers = $http({
method: "get",
url: "http://myServiceUrl/omnichannel/merchant/offer/view/all?enrollmentId="+$rootScope.enrollMentId,
});
return allOffers;
},
inActivateOffer : function(id){
var inactivate = $http({
method:'get',
url : "http://myServiceUrl/omnichannel/merchant/offer/"+id+"/status/INACTIVE?enrollmentId="+$rootScope.enrollMentId,
});
return inactivate;
}
}
});
and controller code is to fect the offers and inactivate offer is :
var mPosController = angular.module('mPosController', []);
mPosController.controller('offerController', ['$scope', '$rootScope', 'mosServiceFactory', 'ngDialog', function ($scope, $rootScope, mosServiceFactory, ngDialog) {
mosServiceFactory.viewAllOffers().then(function (data) {
$scope.offers = data.data.offers;
console.log($scope.offers);
});
$scope.inActivate = function (id) {
mosServiceFactory.inActivateOffer(id).then(function (data) {
console.log(data);
});
}
}]);
Offer is getting successfully inactivated in response of $scope.inActivate method but that perticular offer is still visible in view.
So how to display on Active offers once I inactivate a offer using service call ?
Your code correctly performs a GET request to inactivate the offer, however you do not "tell" Angular that the offer has been inactivated. What you need to do is remove the offer from the offers list $scope.offers once the offer is successfully inactivated (ie. when the inActivateOffer promise is resolved). You could try something like this:
$scope.inActivate = function (id) {
mosServiceFactory.inActivateOffer(id).then(function (data) {
for (var i = 0; i < $scope.offers.length; i++) {
if ($scope.offers[i].id === id) {
$scope.offers.splice(i, 1);
}
});
}

Angularjs change $get source on click

I have a web page that uses
app.controller('listCtrl', function ($scope, $http) {
$http.get("http://data.com/?region=north").success(function (data) {
$scope.properties = data;
});
});
On the click of a button, I'd like to reload the source from a different URL
$http.get("http://data.com/?region=south").success(function (data) {
$scope.properties = data;
});
Is there a way of doing this?
Encapsulate the getting of the resource in a function that is parameterized, so you can call it once when the controller is initializing, and any time they click the button after that.
app.controller('listCtrl', function ($scope, $http) {
function getResource(region) {
$http.get("http://data.com/?region=" + region).success(function (data) {
$scope.properties = data;
});
}
$scope.changeRegion = getResource; // provide function for button click
getResource('north'); // initialize default
});
View:
<button type="button" ng-click="changeRegion('south')">Change Region</button>

Post Function in jQuery is not working

I am using Ajax function to add product in cart in MVC 3
In Ajax i have a function for adding product, inside that function i want to call a another function but its not working..
My Ajax function is
var AjaxCart = {
addproductvarianttocart: function (urladd, formselector) {
if (this.loadWaiting != false) {
return;
}
this.setLoadWaiting(true);
$.ajax({
cache: false,
url: urladd,
data: $(formselector).serialize(),
type: 'post',
success: this.successprocess,
complete: this.resetLoadWaiting,
error: this.ajaxFailure
});
refreshPage();
},
refreshPage: function () {
$.post('/ShoppingCart/OrderSummaryChild', function (data) {
alert("Inside2");
// Update the ItemList html element
$('#CartUpdatePanel').html(data);
alert("Out");
});
}
};
The link is from where i am calling addproductvarianttocart function
<a onclick="AjaxCart.addproductvarianttocart( '/addproductvarianttocart/25/1/');return false;">
The ajax call is asynchronous. You should put the function refreshPage inside the success or complete function. This way the refreshPage function will be called right after the ajax call is finished and the page is ready to be refreshed with the new data.
Extracted from jQuery api:
Description: Perform an asynchronous HTTP (Ajax) request.

Resources