Good starting point for calling api in ionic framework - swift

I am new in ionic framework so i don't have much idea. I want to know that how do i call api using ionic in my app? please anybody have any idea then suggest me.

Integrating a API Service with AngularJS in Ionic
angular.module('ionicApp', [])
.controller('MainCtrl', function($scope, $http) {
$http.get('https://cors-test.appspot.com/test').then(function(resp) {
console.log('Success', resp);
// For JSON responses, resp.data contains the result
}, function(err) {
console.error('ERR', err);
// err.status will contain the status code
})
})
More...

angular.module('ionicApp', [])
.controller('MainCtrl', function($scope, $http) {
$http({
method: method,//GET/POST/DELETE
url: url,
data: data,//JSON DATA FOR POST
dataType: 'json',
headers: {
"Content-Type": "application/json"
}
}).success(function (data) {//Success handling
console.log(data);
}).error(function (data, status) {//Error handling
console.log(status + data);
});
)}
Above method works for any type of HTTP(Get/Post/Delete/Put) request.
Regards

Related

Vuejs soap client

I'm considering moving a project to Vuejs and I have a lot of .net soap webservices already created and tested. I know that I can use axios to interact with REST webservices, but can i consume the .net soap webservices from vue ? I already serch and I can't find anything that fits... any idea ?
Basically I need to replace this code without use jquery:
$.ajax({type: 'POST', url: webservice_url , data: data_to_send,
contentType: 'application/json; charset=utf-8', dataType: 'json',
success: function (response) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
Yes, you can interact with Soap from Vue via Axios.
Your code will look like this:
axios({
method: 'post',
url: webservice_url,
data: data_to_send
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
https://github.com/axios/axios - axios documentation with extended examples and good example with SOAP is this link:
https://stackoverflow.com/a/49153096/5808830

WP REST Api post posts into a remote wordpress website

I have seen many examples on how to get posts from wordpress websites, but I haven't seen any example on how to post a post into a wordpress website using WP REST Api, except this update title example that is incomplete:
$.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
Could someone please show me a full working example of how to post a post into a remote wordpress website, thank you.
$( document ).ready(function(){
//alert('a');
//Perform Ajax request.
$.ajax({
url: "http://apibind.com/wp/wp-json/wp/v2/posts",
type: "POST",
headers: { "Authorization": "Bearer ***************');},
data: {"title" : " tttt","content":"some test content" },
success: function (data) {
console.log(data);
},
error:function(data){
console.log(data);
}
});
});

Logout user with services not working

I am working on a mobile app which I will be deploying using Phonegap.
Now I am able to login using Drupal 7 services and I am also getting the session name and session id. But I am not able to Logout the user. When even I am doing that.. I see this issue on my chrome console: 406 (Not Acceptable:)
I tried sending headers as "Cookie" then "sessionname=sessionid" format.. but that didn't work. Can someone please suggest a way.
You need to add the CSRF token from YOUR_SITE/services/session/token, and then add it to the header in the same way you added the Cookie, something like
'X-CSRF-Token: ' + $token
And make sure it's PUT, there is a nice example here:
http://pastebin.com/N35SN7Xj
The relevant section looks like this:
$.ajax({
url: "http://your_url/endpoint/user/logout.json",
type: 'post',
dataType: 'json',
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", token);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Failed to logout');
alert(JSON.stringify(jqXHR));
alert(JSON.stringify(textStatus));
alert(JSON.stringify(errorThrown));
},
success: function (data) {
alert("You have been logged out.");
}
});
This works for me.
$http({
method: 'POST',
url: drupal_instance + api_endpoint + 'user/logout',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'X-CSRF-Token': user.token
}
})
.success(function (data, status, headers, config) {
alert('Success');
})
.error(function (data, status, headers, config) {
alert('Error');
});

How to serve 404's using AngularJS and a RESTful API

Let's say you have an AngularJS application hooked up to a RESTful API and you have a route for "/item/:itemId".
.when('/item/:itemId', {
templateUrl: '/static/partials/item-detail.html',
controller: ItemDetailController
})
angular.module('angServices', ['ngResource']).factory('Item', function($resource) {
return $resource('/api/item/:itemId', {}, {
query: { method: 'GET', params: { itemId: '' }, isArray: true }
});
});
If the user goes to "/item/9" and an object with the itemId 9 does not exist, Angular will receive a 404 from the API, but will not naturally return a 404 to the user.
In other questions, I've seen people suggest creating an interceptor and having Angular redirect to a 404 error page when a resource is not found.
var interceptor = ['$rootScope', '$q', function(scope, $q) {
...
function error(response) {
if (response.status == 404) { window.location = '/404'; }
...
$httpProvider.responseInterceptors.push(interceptor);
However, I want to return a correct 404 with the original requested URL for SEO purposes.
Also, the solution above first loads the page and then redirects (just like Twitter used to do), so its sub-optimal.
Should I check server-side to first see if the resource exists before passing the request on to the Angular app? The downside of this is that it wouldn't work for broken links within the application.
What is the best way to approach this?
Maybe this jsfiddle can help you.
http://jsfiddle.net/roadprophet/VwS2t/
angular.module('dgService', ['ngResource']).factory("DriveGroup", function ($resource) {
return $resource(
'/', {}, {
update: {
method: 'PUT'
},
fetch: {
method: 'GET',
// This is what I tried.
interceptor: {
response: function (data) {
console.log('response in interceptor', data);
},
responseError: function (data) {
console.log('error in interceptor', data);
}
},
isArray: false
}
}
);
});
var app = angular.module('myApp', ['ngResource', 'dgService']);
app.controller('MainController', ['$scope', 'DriveGroup', function ($scope, svc) {
$scope.title = 'Interceptors Test';
svc.fetch(function (data) {
console.log('SUCCESS');
}, function () {
console.log('FAILURE');
});
}]);
I tried with this and works fine. I only change the fetch method to get.
In your case, you will need to change the console.log('FALIURE'); to $location.path('/404');.
GL!

making jquery AJAX POST to resful API

I'm trying to convert a REST call using Cordova plugin to a JQuery AJAX POST. I don't have the JQuery code right, the call is getting a connection refused error (hitting localhost). I'm successfully making GET requests to my localhost, so there isn't a connectivity issue.
The REST API code:
#Path("/track")
public class TrackResource {
...
The method in TrackResource class i'm trying to hit :
#POST
#Path("{trackid}")
#Consumes("application/json")
#Produces("application/json")
public Response addToResource(#PathParam("trackid") String trackid, String bodyJson) {
The AJAX code:
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I'm not sure if i'm using the data option in the ajax call correctly, but it's my understanding that is where you would put the data you want to pass server side.
I do have other GET calls to this same TrackResource class working, so i know the base part of the URL is correct. I know the trackid value is populated correctly as well.
If you're posting a JSON string make sure you also set contentType: "application/json".
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/json",
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I needed to use the router address of my computer, 192...., in order to hit my localhost... I was running the application on an actual Android device, however, I guess trying to use localhost or 127.0.0.1 in the AJAX call must have been causing issues.