I have an angularJs application that has an api call with a click on a link . but everytime i click on the link it sends 2 same api calls to the server. Why this occurs and how can i resolve this.
my service is like: SomethingService
function getData() {
return apiSettings.getApiInformation().then(function (response) {
var url = response.data.Url + "/odata/Something?$expand=Something";
var data = {
url: url,
type: "GET",
token: response.data.Token,
data: {},
async: true,
cache: false,
headers: {
"accept": "application/json; charset=utf-8",
'Authorization': 'Bearer ' + response.data.Token
},
dataType: "json",
success: {},
error: {},
complete: {},
fail:{}
};
return $http(data);
});
}
Api Settings :
angular.module('myApp.services')
.factory('apiSettings', apiSettings);
apiSettings.$inject = ['$http'];
function apiSettings($http) {
return {
getApiInformation: function () {
return $http.get(baseUrl+ '/api/GetApiInformation', {cache: true});
}
}
}
SomethingController:
var vm = this;
function getSlots(filterCriteria, selectedValue) {
somethingService.getData().then(function (response) {
if (response && response.value.length > 0) {
vm.someData = response.value;
}
});
View:
clicking on this link calls getSlots that sends duplicate request
<a ui-sref="something" class="action-icons" id="slotNav"><i class="fa fa-square-o fa-fw"></i>
something
</a>
this view displays data
<div ng-repeat="data in vm.someData">
<p> {{data.Name}}</p>
</div>
Issue: For a single trigger browser sends duplicate requests like the following. the first call doesn't have callback but the second call has callback:
someuls?$expand=something&_=1432722651197
someuls?$expand=something&_=1432722651197
I had a similar problem which I fixed by checking this answer. I had declared "ng-controller" in HTML as well as routed to it using routeProvider. Fixed the issue by removing the "ng-controller" property in HTML.
Hope this helps.
Related
I have an Sdk to call which returns an applicationID that I need to store in my django application so that if the user is approved, then he can move to the next page. I am trying to save in JS sessionStorage than pass the data to another html page where I'm using ajax to pass it to my django views. The problem is that I need to have this data unique for the user that is logged in.
How can I link this data to the current user logged in and so on?
const widget = window.getidWebSdk.init({
apiUrl: '',
sdkKey: '',
containerId: "targetContainer",
flowName: '',
onComplete: (data) => {
console.log(JSON.stringify(data))
let appId = data;
console.log(data)
sessionStorage.setItem("appId", JSON.stringify(appId))
window.location.href = "/kycsubmit";
return;
},
onFail: ({ code, message}) => { console.log("something went wrong: " + message )},
});
second html page:
let application = JSON.parse(sessionStorage.getItem("appId"));
let kycStatus = application.applicationId
$.ajax({
type: "GET",
dataType: "json",
url: `api/application/${kycStatus}`,
headers: {
'Content-Type': 'application/json',
'X-API-Key': '',
},
success: function(data) {
document.getElementById("test").innerHTML = data.overallResult.status
document.getElementById("test-1").innerHTML = application.applicationId
console.log(data.overallResult.status)
}
})
I'm developing a website with express and ejs. I got into a trouble where i need to call an api via ajax. The problem is on a button onclick i'm passing two values to ajax data. but it gives error ,i tried a lot of ways and i'm messed up. i'm a newbie , find my code below.
const parsedData = JSON.parse(localStorage.getItem('myData'));
const container = document.getElementById('s1');
parsedData.data.rows.forEach((result, idx) => {
var a = result.master_id;
var b = result.session_name;
console.log(a,b,"a","b")
var userData = {"pid":a,"session" :b};
console.log(userData,"userData");
sessionStorage.setItem("user", JSON.stringify(userData));
console.log(userData,"data for api");
const card = document.createElement('div');
card.classList = 'card';
const content = `
<div class="row">
<div class="card-body" onclick="graphApi()">
</div>
</div>
`;
container.innerHTML += content;
});
function graphApi(){
var apiValue =JSON.parse( sessionStorage.getItem("user"));
console.log(apiValue, "value from card");
$.ajax({
type: "POST",
data: apiValue,
dataType:"json",
url: "http://localhost:5000/graphFromcsv",
success: function(data) {
console.log(data,"graph api");
}
error: function(err){
alert("graph api failed to load");
console.log(err);
},
});
i'm always getting this pid in api value undefined and 400 badrequest . but if i use raw data like,
{
"pid":"WE6",
"session":"W.csv"
}
instead of apiValue my ajax is success and i'm gettig the data. i'm using this data to plot a multiple line graph. Any help is appreciated.
You need to correct data key and their value(value must be string in case of json data) and also add contentType key like
$.ajax({
type: "POST",
data: sessionStorage.getItem("user") || '{}',
dataType: "json",
contentType: "application/json",
url: "http://localhost:5000/graphFromcsv",
success: function (data) {
console.log(data, "graph api");
},
error: function (err) {
alert("graph api failed to load");
console.log(err);
},
});
Note: In backend(ExpressJS), make sure you are using correct body-parser middleware like app.use(express.json());
Let assume your apiValue contain {"pid":"WE6", "session":"W.csv" } then body: { apiValue } will be equal to:
body: {
apiValue: {
"pid":"WE6",
"session":"W.csv"
}
}
But if you use the link to the object like body: apiValue (without brackets) js will build it like:
body: {
"pid":"WE6",
"session":"W.csv"
}
I'm having trouble trying to show the view I want after calling the controller method from Ajax.
This is the JavaScript function where I call the controller Method 'create_pedido' with an Ajax post.
$('.small-box').on('click', function(e) {
e.preventDefault();
let camarero_id = document.getElementById('id_camarero').value;
let mesa_id = e.currentTarget.parentElement.attributes.idMesa.value;
let mesa_estado = e.currentTarget.parentElement.attributes.disponible.value;
console.log('ID Mesa: ' + mesa_id);
console.log('Disponible: ' + mesa_estado);
console.log('ID Camarero: ' + camarero_id);
if (mesa_estado == 1) {
console.log('Crear')
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: 'create_pedido',
data: { mesa: mesa_id, camarero: camarero_id }
}).done(function(msg) {
console.log('Success');
});
} else {
console.log('Editar')
}
});
This is the controller method which does everything but returning the view where it should go after.
public function create(Request $request)
{
$mesa = Mesa::find($request->mesa);
$camarero = Trabajador::find($request->camarero);
$alimentos = Alimento::all();
$categorias = Categoria::all();
Log::channel('stderr')->info($mesa);
Log::channel('stderr')->info($camarero);
return view('pedido.create', compact('mesa', 'camarero','categorias', 'alimentos'));
}
Instead of going to the 'pedidos.create' view after the 'Log::channel...' stay in the same view where it was called.
Here are my routes:
Route::resource('/', 'IndexController');
Route::resource('inicio', 'IndexController');
Route::resource('trabajador', 'TrabajadorController');
Route::resource('pedido', 'PedidoController');
Route::post('create_pedido','PedidoController#create');
Route::resource('alimento', 'AlimentoController');
Route::resource('orden', 'OrdenController');
Route::resource('mesa', 'MesaController');
Route::post('mesa_changestate', 'MesaController#change_state');
Its likely returning to the same view because you are not telling it the base URL of the app. Laravel has a nice method to help here, which will prepend the route with the appropriate base:
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: '{{url("create_pedido")}}', // use blade to add in the Laravel url() method here
data: { mesa: mesa_id, camarero: camarero_id }
}).
Also for the return statement in the controller create method - is the folder 'pedido' or 'pedidos' - make sure to call the right view :)
I need to Add an event from my database to outlook calendar for which I have been trying to make an ajax call to the outlook auth API first which looks like this
$scope.authorizeOutlook = function () {
let redirect = 'http://localhost:51419';
let clientId = 'xxx';
var authData = 'client_id=' + clientId + '&response_type=code&redirect_uri=' + redirect + '&response_mode=query&scope=https%3A%2F%2Fgraph.microsoft.com%2Fcalendars.readwrite%20&state=12345';
debugger
$.ajax({
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
type: 'POST',
host: 'https://login.microsoftonline.com',
contentType: "application/x-www-form-urlencoded",
contentLength: "600",
data: authData,
success: function (response) {
debugger;
alert(response.status);
//alert("success");
},
error: function (response) {
alert(response.status);
//alert("fail");
}
});
}
But I am getting response status as 0. What does that mean? Where am I doing it wrong?
If you use Oauth2.0, you need to add " token-type: Bearer ".
Reference from:
Get access tokens to call Microsoft Graph
I have a function :
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
return response.data;
});
}
and the function work perfectly, but i want my page change to datalist and refresh datalist after insert() true. my function insert() run in the route "localhost/learn/#!/administrator" so i want it change to route "localhost/learn/#!/" after insert() true. i used location.href='#!/' but it not work for refresh datalist automaticaly, just change location.
If you want to update an object from a service call, you can do the following. I have added an onError function too, to help with debugging.
Tip: Research adding service calls into a Service that AngularJS framework provides. It helps for writing maintainable and structured code.
$scope.objectToUpdate;
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
$scope.objectToUpdate = response.data.d;
}, function(e){
alert(e); //catch error
});
}
Optional Service
Below is an example of how to make use of Angular Services to make server calls
app.service('dataService', function ($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function (url, data) {
// $http() returns a $promise that we can add handlers with .then() in controller
return $http({
method: 'POST',
url: './sys/' + url + '.php',
dataType: 'json',
data: data,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
};
});
Then call this service from your controller, or any controller that injects DataService
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
dataService.getData('mac', data).then(function (e) {
$scope.objectToUpdate = e.data.d;
}, function (error) {
alert(error);
});