integrating geojson query to generate http requests in angularjs - javascript

i am trying to integrate geoshape query from elastic search into my angularjs code to make an http request to fetch the data that is residing on elasticsearch local instance but the console throws error that invalid XMLhttp parameters. I guess it is related to how i am adding the geojson with my URL. Following is the function where i am creating the http request
function spatialsearch() {
var _url = '127.0.0.1:9201/_search?';
var b = {
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"geo_shape": {
"metadata.o2r.spatial.geometry": {
"shape": {
"type": "polygon",
"coordinates": [
[
[-22.0, 76.0],
[-27.0, 65.0],
[-57.0, 65.0],
[-59.0, 76.0],
[-22.0, 76.0]
]
]
},
"relation": "contains"
}
}
}
}
}
};
_url += b;
return $http.get(_url);
console.log("hello");
}
Here is how i am calling http request in my js file in angularjs
function callingspatialsearch(){
var deferred = $q.defer();
httpRequests.
spatialsearch()
.then(cb1)
.catch(errorHandler);
return deferred.promise;
function cb1(response){
$log.debug('result of search: %o', response);
deferred.resolve(response);
}
function errorHandler(e){
$log.debug('search error: %o', e);
deferred.resolve(e);
}
}
In my HTML i am adding a button so that when user clicks on button the results are displayed.
<md-button ng-click="vm.button()" class="search-button md-primary md-raised white-font">Spatial</md-button>

i am using $http.post(_url) instead of GET and that helps me in retrieving results

Related

Unable to load the payment options in paytm js checkout

I am working with Paytm gateway and I want to implement JS Checkout, but I'm unable to load the banks and options of payment.
Below is all the code that I'm using:
async function onScriptLoad(){
var data = await fetch(`http://localhost:5000/api/payment`,{
method:"GET",
headers:{
Accept:"application/json",
"Content-Type":"application/json"
},
}).then(response=>response.json()).catch(err=>console.log(err));
var Jsondata = JSON.parse(data)
console.log(JSON.parse(data))
var token = await fetch(`https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=Muctvj23768431537109&orderId=${Jsondata.body.orderId}`,{
method:"POST",
headers:{
Accept:"application/json",
"Content-Type":"application/json"
},
body:data
}).then(response=>response.json()).catch(err=>console.log(err));
console.log(token)
var config = {
"root": "",
"flow": "DEFAULT",
"data": {
"orderId": Jsondata.body.orderId, /* update order id */
"token": token, /* update token value */
"tokenType": "TXN_TOKEN",
"amount": "1.00" /* update amount */
},
"payMode": {
"order": ['CARD']
},
"handler": {
"notifyMerchant": function(eventName,data){
console.log("notifyMerchant handler function called");
console.log("eventName => ",eventName);
console.log("data => ",data);
}
}
};
if(window.Paytm && window.Paytm.CheckoutJS){
window.Paytm.CheckoutJS.onLoad(function excecuteAfterCompleteLoad() {
// initialze configuration using init method
window.Paytm.CheckoutJS.init(config).then(function onSuccess() {
// after successfully updating configuration, invoke JS Checkout
console.log("success")
window.Paytm.CheckoutJS.invoke();
}).catch(function onError(error){
console.log("error => ",error);
});
});
}
}
I am new to this; any assistance would be greatly appreciated.
Please check whether you are using the correct mid and other configurations or not. If details are correct please raise a query at Paytm Developers support

How to customize controller's response with specific exits from helper?

I'm using Sails.js v1.2.2 and organizing my controllers with single file rather than action 2. Also I use helpers in my controllers.
Now when the helper triggers some exit other than success, the controller will automatically response with the specific format like
{
"cause": {
"name": "Exception",
"code": "ParameterError",
"exit": "ParameterError",
"traceRef": {},
"raw": {
"msg": "My custom message"
}
},
"isOperational": true,
"code": "ParameterError",
"exit": "ParameterError",
"traceRef": {},
"raw": {
"msg": "My custom message"
}
}
How can I custom the response data when the helper exits no-success?
I've tried custom exits in helper file, but not working.
U can use sails generator. sails generate response myCustomHandler. Check docs for custom responses.
Then just try catch helper like in example:
try {
await sails.helpers.test()
.intercept({ code: 'test' }, ()=>{ return new Error('err1') })
} catch (e) {
if (e.message === 'err1') {
return res.badRequest('Test Bad request')
} else if (e.code === 'ParameterError') {
return res.serverError('Parameter Error Message in server error')
} else {
return res.myCustomHandler('Test Custom handler')
}
This is an example with intercept u can use to do more custom stuff. Just ignore it if u don't need that. If u use actions2, then return with this statement. return this.res.myCustomHandler('Some error').
In myCustomHandler.js file, u can format error. Check this docs.

Method working when data is static and filed when data is getting from promise

I have a scenario like I need to get some data from api request and based on that show images on the screen.
return Class.extend({
loadData: function (callbacks) {
callbacks.onSuccess(
[
{
"id":"1",
"title":"Apple",
"img" : "static/img/fruit/apple.png"
},
{
"id":"2",
"title":"Banana",
"img" : "static/img/fruit/banana.png"
},
{
"id":"3",
"title":"Grapes",
"img" : "static/img/fruit/grapes.png"
},
{
"id":"4",
"title":"Orange",
"img" : "static/img/fruit/orange.png"
},
{
"id":"5",
"title":"Peach",
"img" : "static/img/fruit/peach.png"
},
{
"id":"6",
"title":"Pear",
"img" : "static/img/fruit/pear.png"
}
]
);
}
});
When I use the above code it works perfectly, But I need data from api so I have implemented a method to get data and I have created a promise also, But this one is not working
return Class.extend({
// You will probably want to do something more useful then returning static data
loadData: function (callbacks) {
callbacks.onSuccess(
evtBind().then(function (res) {
console.log("res", res);
return res;
})
);
}
});
function evtBind() {
var device = RuntimeContext.getDevice();
var get = function () {
return new Promise(function (resolve, reject) {
// do a thing, possibly async, then…
device.executeCrossDomainGet('http://localhost:3000/result', {
onSuccess: function (responseObject) {
resolve(responseObject);
},
onError: function (response) {
reject(response);
}
});
});
};
return get();
}
My code looks like the above one. Can someone help me to resolve this .
If you're getting the correct array in res, then why don't you call your onSuccess with the array? At the moment you're passing a promise to onSuccess so the code there would have to be adjusted if you did that.
loadData: function (callbacks) {
evtBind().then(callbacks.onSuccess);
}
Which is short for:
loadData: function (callbacks) {
evtBind().then(res => callbacks.onSuccess(res));
}

Disappearing/re-appearing JSON data

I'm using Angular, and have a JSON response where one of the property values is disappearing (is empty), but if you look at it directly, it appears (and has the proper values). The property that is supposed to have data is the vehicles property.
The JSON data
{
"data": {
"blocks": [
{
"vehicles": [
{
"agency": "ZGM Bike Share",
"mode": "bikeshare",
"name": "Research Chemistry Lab",
"space_count": 4
},
{
"agency": "ZGM Bike Share",
"mode": "bikeshare",
"name": "ENG North",
"space_count": 4
},
{
"agency": "ZGM Bike Share",
"mode": "bikeshare",
"name": "Research South",
"space_count": 6
}
]
}
],
"screen": {}
}
}
The console
Below are 2 console.log() from this. One is the full response, and the other is accessing the vehicles property directly. As you can see, in the full response, it is empty, but when accessed directly it contains data.
The problem
We are using Angular and after some JS manipulation, which happens after the console.log() above, we are passing this object to a template. Because it's being passed as a full object, it passes it with vehicles empty.
The code snippet
This is the part that makes the call and handles the response.
tsApp.service('updateService', function($http, $q, jsonResponse, $timeout, $interval, $log, $location) {
// Cut out a bunch of code that happens after getUpdate()
function getUpdate() {
var request = $http({
method: 'get',
dataType: 'json',
url: '/data/' + id + '.json',
timeout: updateRequestTimeout
});
return (request.then(handleSuccess, handleError));
}
function handleSuccess(response) {
console.log(response.data);
console.log(response.data.data.blocks[0].vehicles);
return response.data;
}
return updateService;
});
So I understand the following from your question:
You requested a resource from a remote server, got it, but the angular service returns nothing when its being called from a controller etc.
The problem is, that you initiated the request itself, and you returned the value of the handleSuccess function to the service itself, not to the caller of it.
Here's the fixed code:
tsApp.service('updateService', function($http, $q, jsonResponse, $timeout, $interval, $log, $location) {
var serviceObj = { vehicles: [] };
// Cut out a bunch of code that happens after getUpdate()
function getUpdate() {
var request = $http({
method: 'get',
dataType: 'json',
url: '/data/' + id + '.json',
timeout: updateRequestTimeout
});
request.then(handleSuccess, handleError);
}
function handleSuccess(response) {
console.log(response.data);
console.log(response.data.data.blocks[0].vehicles);
serviceObj.vehicles = response.data.data.blocks[0].vehicles;
}
return serviceObj;
});
Now, when you will need the vehicles object, you will call:
updateService.vehicles
Note that it will be empty until the response retrieved. To make sure you got it before you use it, you can also add a broadcast event on the rootScope. That way, the controller / directive that want to use it, will be able to determine if its already sent:
// Broadcast the handleSuccess event
serviceObj.ready = true;
$rootScope.$boradcast("updateService.vehicles.success", true);
// Listen to this event from other controller / directive to make sure the request finished up
if(updateService.ready === true) {
successFunc()
}
$rootScope.$on("updateService.vehicles.success", successFunc);

I am not getting the JSON data, though it is getting loaded properly, why does that happen so? It is showing blank alert box

Following is my code, I want to get the JSON data, I am doing a railway app in office 365 Napa, my JSON is getting loaded but not showing me the data, and I am passing station code that is passed in the string through which HMAC signature is generated by passing it in URL I get the JSON which I have to read,
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
$.getJSON(
siteurl,
function(data){
alert(data.message);
});
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
The JSON response is:
{
"response_code": 200,
"stations": [
{
"name": "Kanpur Central",
"code": "CNB",
"state": "UP",
"zip": null,
"railway_zone": "",
"location": {
"lat‌​": "26.4528466",
"lng": "80.3237478"
},
"about_text": null,
"about_link": null
},
{
"name": "‌​Chandari",
"code": "CNBI",
"state": "UP",
"zip": null,
"railway_zone": "",
"location": {
"la‌​t": "26.4279135",
"lng": "80.3604594"
},
"about_text": null,
"about_link": null
}
]
}
You are trying to alert data.message but your JSON doesn't have a message property. Look at properties that actually exist in the data.
Loading mixed (insecure) active content on a secure page
Don't make Ajax requests to HTTP end points from HTTPS pages. The data isn't secure, can be intercepted and might compromise the security of the page (especially if JSONP gets used for cross-origin requests).

Categories

Resources