I'm stuck for days on that, so i come here if someone has the kindess to help me. My probleme is that when I use fetch to post an image to my database with my body taking a formdata of my image with an image picker, it just gave me back that (Note that when i just use google chrome to test the .php , it work well) :
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="fileToUpload" value=""/>
<div>
<button type="submit" name="fileToUpload">UPLOAD</button>
</div>
</form>
</div>
My fetch with the image :
console.log( NewImg)
const data = new FormData();
const url = 'https://jaimeleshommes.online/pub.php?Token=' + await AsyncStorage.getItem('TokenProfile')
data.append("name", 'fileToUpload');
data.append("file_attachment", NewImg.base64);
fetch(url,
{
method: 'POST',
body: data,
headers: {
'Content-Type': 'multipart/form-data; ',
},
})
.then((response) => response.text())
.then((ResponseData) => {
console.log(ResponseData)
});
When i just change 'NewImg.base64' to 'NewImg', I just got Network error... Thanks a lot
Related
I am really new to the mobile development world and trying my hands on it using IonicFramework.
I am creating a login form and on successful login the user gets take to another state which is called viewMyList. Everything seems to be working fine when I run the command ionic serve I am able to login and proceed to the next state and all seems to be fine on iOS simulator as well but on Android simulator on clicking the login button nothing happens, I don't see any error either.
My attempt
login.html
<ion-view title="Login">
<ion-content class="has-header" padding="true">
<form class="list">
<h2 id="login-heading3" style="color:#000000;text-align:center;">Welcome back!</h2>
<div class="spacer" style="width: 300px; height: 32px;"></div>
<ion-list>
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" placeholder="" ng-model="credentials.username">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="text" placeholder="" ng-model="credentials.password">
</label>
</ion-list>
<div class="spacer" style="width: 300px; height: 18px;"></div>
<a class="button button-positive button-block" ng-click="login()">Sign In</a>
</form>
</ion-content>
</ion-view>
ng-click is linked with login()
Here is my loginCtrl which contains the login() function
.controller('loginCtrl', function ($scope, $state, $ionicHistory, User) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function () {
User.login($scope.credentials)
.then(function (response) {
console.log(JSON.stringify(response));
//Login should not keep any history
$ionicHistory.nextViewOptions({historyRoot: true});
$state.go('app.viewMyList');
})
};
$scope.message = "this is a message loginCtrl";
})
Here is my User service that takes care of the login logic
angular.module('app.user', [])
.factory('User', function ($http) {
var apiUrl = 'http://127.0.0.1:8000/api';
var loggedIn = false;
return {
login: function (credentials) {
console.log(JSON.stringify('inside login function'));
console.log(JSON.stringify(credentials));
return $http.post(apiUrl + '/tokens', credentials)
.success(function (response) {
console.log(JSON.stringify('inside .then of login function'));
var token = response.data.token;
console.log(JSON.stringify(token));
$http.defaults.headers.common.Authorization = 'Bearer ' + token;
persist(token);
})
.error(function (response) {
console.log('inside error of login function');
console.log(JSON.stringify(response));
})
;
},
isLoggedIn: function () {
if (localStorage.getItem("token") != null) {
return loggedIn = true;
}
}
};
function persist(token) {
window.localStorage['token'] = angular.toJson(token);
}
});
Here is the route behind the login
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
})
I am really clueless at the moment as I cant seem to figure out why nothing happens on Android, from my troubleshooting all I could find was when I click on login button the code does not seem to be going inside the following function.
$scope.login = function () {
User.login($scope.credentials)
.then(function (response) {
console.log(JSON.stringify(response));
//Login should not keep any history
$ionicHistory.nextViewOptions({historyRoot: true});
$state.go('app.viewMyList');
})
};
Any help will really be appreciated.
Install whitelist plugin first.
cordova plugin add cordova-plugin-whitelist
add following code in your config.xml file under your root directory of project
<allow-navigation href="http://example.com/*" />
or:
<allow-navigation href="http://*/*" />
If still you are facing any issue, then you can check console while you are running in android device using chrome remote debugging
Connect your device with your machine.(Make sure USB debugging should be enable on your mobile).
write chrome://inspect in browser in your desktop chrome.
you will see connected device, select inspect and check console for log.
I am creating a hybrid android app using wordpress json api, ionic and angularjs.
I am stuck at just one thing : I am unable to list the posts in a particular category.I got the list of categories but unable to pass some parameters.
Here's the code
controller.js
.controller('CatsCtrl', function($scope, $http) {
// You can change this url to experiment with other endpoints
var categoriesApi = 'http://shayarihunt.com/wp- json/taxonomies/category/terms?_jsonp=JSON_CALLBACK';
// This should go in a service so we can reuse it
$http.jsonp( categoriesApi, {cache:true} ).
success(function(data, status, headers, config) {
$scope.categories = data;
console.log( data );
}).
error(function(data, status, headers, config) {
console.log( 'Post load error.' );
});
})
.controller('CatsPostsCtrl', function($scope, $http) {
// You can change this url to experiment with other endpoints
var postsApi = 'http://shayarihunt.com/wp-json/posts?filter[cat]=' + the parameter has to come here, (I dont know what!!!) + '&_jsonp=JSON_CALLBACK';
// This should go in a service so we can reuse it
$http.jsonp( postsApi, {cache:true} ).
success(function(data, status, headers, config) {
$scope.posts = data;
console.log( data );
}).
error(function(data, status, headers, config) {
console.log( 'Post load error.' );
});
})
The CatsCtrl display all categories but CatsPostsCtrl should display all posts in category which it doesn't.
Any help is appreciated.
Thanks!
You're looking for $stateParams from ui-router. Please have a look at the docs for more details.
Below is a demo usage. Click on the second icon to show the posts in category hindi-shayari. You can also find the same code at jsfiddle.
angular.module('demoApp', ['ionic'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
views: {
home: {
templateUrl: 'home.html',
controller: 'CatsCtrl'
}
}
})
.state('category', {
url: '/category/:slug',
views: {
category: {
templateUrl: 'category.html',
controller: 'CatsPostsCtrl'
}
}
});
$urlRouterProvider.otherwise('/');
})
.controller('CatsCtrl', function($scope, $http) {
// You can change this url to experiment with other endpoints
var categoriesApi = 'http://shayarihunt.com/wp-json/posts?_jsonp=JSON_CALLBACK';
// This should go in a service so we can reuse it
$http.jsonp( categoriesApi, {cache:true} ).
success(function(data, status, headers, config) {
$scope.posts = data;
console.log( data );
}).
error(function(data, status, headers, config) {
console.log( 'Post load error.', status, headers);
});
})
.controller('CatsPostsCtrl', function($scope, $http, $stateParams) {
console.log($stateParams);
// You can change this url to experiment with other endpoints
var postsApi = 'http://shayarihunt.com/wp-json/posts?filter[category_name]=' + $stateParams.slug + '&_jsonp=JSON_CALLBACK';
$scope.category = $stateParams.slug;
// This should go in a service so we can reuse it
$http.jsonp( postsApi, {cache:true} ).
success(function(data, status, headers, config) {
$scope.posts = data;
console.log( data );
}).
error(function(data, status, headers, config) {
console.log( 'Post load error.' );
});
})
<script src="http://code.ionicframework.com/1.0.1/js/ionic.bundle.min.js"></script>
<link href="http://code.ionicframework.com/1.0.1/css/ionic.min.css" rel="stylesheet"/>
<div ng-app="demoApp">
<script id="post-partial.html" type="text/ng-template">
<div ng-repeat="post in posts">
<h2 ng-bind-html="post.title"></h2>
<p ng-bind-html="post.content"></p>
</div>
</script>
<script id="home.html" type="text/ng-template">
<!-- The title of the ion-view will be shown on the navbar -->
<ion-view view-title="Home">
<ion-content>
<!-- The content of the page -->
<!--<a ui-sref="category({slug:'hindi-shayari'})">Go to hindi-shayari category!</a>-->
<div ng-include="'post-partial.html'"></div>
</ion-content>
</ion-view>
</script>
<script id="category.html" type="text/ng-template">
<!-- The title of the ion-view will be shown on the navbar -->
<ion-view view-title="Category">
<ion-content>
<!-- The content of the page -->
<h1 ng-bind-html="category"></h1>
<div ng-include="'post-partial.html'"></div>
</ion-content>
</ion-view>
</script>
<ion-tabs class="tabs-positive">
<ion-tab icon="ion-home" ui-sref="home">
<ion-nav-view name="home"></ion-nav-view>
</ion-tab>
<ion-tab icon="ion-navicon-round" ui-sref="category({slug:'hindi-shayari'})">
<ion-nav-view name="category"></ion-nav-view>
</ion-tab>
</ion-tabs>
</div>
Hii i am doing a simple phone gap application.i want to display my data in list view in phonegap using ajax.but i am facing one problem in listview.my list view showing only one value at a time.means i want to show all titles in list view.but it showing only one title..how can i show all databse calumns value in listview.how can i loop it.pls help.
$.ajax({
url: 'http://url/display.php',
type: 'GET',
dataType: "json",
success: function(data){
$('#list').append('<li >'+data.title+'</li>');
$("#list").listview("refresh");
alert('Data successfully display');
},
error: function(){
alert('There was an error');
}
});
#html
<div data-role="content">
<div class="example-wrapper">
<ul data-role="listview" id="list" data-divider-theme="a" data-inset="true</ul>
</div>
</div>
php
<?php
include_once('config/config.php');
$sql="select * from myapp";
$result=mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$array = $row;
}
echo json_encode($array);
?>
You are currently getting one row of data using your PHP code, I have modified your code,
<?php
include_once('config/config.php');
$sql="select * from myapp";
$result=mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$array[] = $row;
}
echo json_encode($array);
?>
And ajax code like this,
$.ajax({
url: 'http://url/display.php',
type: 'GET',
dataType: "json",
success: function(data){
for(i=0;i<data.length;i++){
$('#list').append('<li >'+data[i].title+'</li>');
}
$("#list").listview("refresh");
alert('Data successfully display');
},
error: function(){
alert('There was an error');
}
});
You did not close <ul> tag. Change like this,
<div data-role="content">
<div class="example-wrapper">
<ul data-role="listview" id="list" data-divider-theme="a" data-inset="true">
</ul>
</div>
</div>
Check this too,
$.ajax({
url: 'http://url/display.php',
type: 'GET',
dataType: "json",
success: function(data){
var li_tag='';
$(data).each(function( index,value ) {
console.log( index + ": " + value );
li_tag=li_tag+'<li>'+value+'</li>'
});
$('#list').append(li_tag);
$("#list").listview("refresh");
alert('Data successfully display');
},
error: function(){
alert('There was an error');
}
});
I am developing one application in PhoneGap in that application i want to share text-message in Facebook,twitter and LinkedIn. for ANDROID-LinkedIn i am searching many Google links but i am getting good one. please help me i am struck here
I am implementing this sample:
<html>
<head>
<title>OAuthSimple w/ LinkedIn</title>
<script src="OAuthSimple.js"></script>
<script>
/*
You must edit the two following lines and put in your consumer key and shared secret
*/
var consumer_key = "ibmay1qostgk";
var shared_secret = "4HqeDRZ2ZKAvASlM";
/*
Nothing below here needs to be edited for the demo to operate
*/
var oauth_info = {};
var oauth = OAuthSimple(consumer_key, shared_secret);
function parse_response(response, callback)
{
response.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { oauth_info[$1] = $3; });
callback.call();
}
function authorize_url()
34{
set_url("https://www.linkedin.com/uas/oauth/authenticate?oauth_token=" + oauth_info.oauth_token, document.getElementById("au"));
}
function access_token_url(pin) {
oauth.reset();
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {oauth_verifier: pin}, signatures: oauth_info}).signed_url;
set_url(url, document.getElementById("at"));
}
function fetch_profile_url() {
oauth.reset();
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/v1/people/~", signatures: oauth_info}).signed_url;
set_url(url, document.getElementById("fp"));
}
function set_url(url, element) {
element.value = url;
var span = document.createElement("span");
span.innerHTML = " <a href='" + url + "' target='_blank'>Open</a>";
element.parentNode.insertBefore(span, element.nextSibling);
}
window.onload = function() {
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/requestToken", parameters: {oauth_callback: "oob"}}).signed_url;
set_url(url, document.getElementById("rt"));
}
</script>
</head>
<body>
<h1>OAuthSimple w/ LinkedIn</h1>
<label for="rt">Request Token URL:</label> <input type="text" size="100" name="rt" id="rt" >
<br><br>
<label for="rtr">Request Token Response:</label><br><textarea rows="5" cols="75" name="rtr" id="rtr"></textarea>
<br>
<button onclick="javascript:parse_response(document.getElementById('rtr').value, authorize_url)">Parse Response</button>
<br><br>
<label for="au">Authorize URL:</label> <input type="text" size="100" name="au" id="au">
<br><br>
<label for="vp">Verifier PIN Code:</label> <input type="text" size="100" name="vp" id="vp">
<button onclick="javascript:access_token_url(document.getElementById('vp').value)">Get Access Token URL</button>
<br><br>
<label for="at">Access Token URL:</label> <input type="text" size="100" name="at" id="at">
<br><br>
<label for="atr">Access Token Response:</label><br><textarea rows="5" cols="75" name="atr" id="atr"></textarea>
<br>
<button onclick="javascript:parse_response(document.getElementById('atr').value, fetch_profile_url)">Parse Response</button>
<br><br>
<label for="fp">Fetch Profile URL:</label> <input type="text" size="100" name="fp" id="fp">
</body>
</html>
thanks in advance
Heres a full example of login and sending msg linkedIn using Phonegap
ref = window.open('https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=APIKEY&scope=w_messages r_network r_emailaddress r_fullprofile&state=APISECRET&redirect_uri=SOMEACTIVESITE','_blank','location=no');
ref.addEventListener('loadstart', function(e){
$.mobile.loading( 'show' );
if(e.url.indexOf('?code=') >=0 ){
if(e.url.match(/=[^]+&/)){
var code = e.url.match(/=[^]+&/)[0].substring(1).replace('&','');
window.sessionStorage.setItem('code', code);
ref.close();
$.ajax({
url: 'https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code='+code+'&redirect_uri=http://janbeeangeles.com&client_id=jwwwdjplwubu&client_secret=ygMy3EpVcs6IAORE',
success: function(a){
$.ajax({
url : 'https://api.linkedin.com/v1/people/~/mailbox?oauth2_access_token='+a.access_token,
type: 'post',
headers : {
'Content-Type' : 'application/json',
'x-li-format' : 'json'
},
data: JSON.stringify({
"recipients": {
"values": [
{
"person": {
"_path": "/people/~",
}
}]
},
"subject": "asdasdasd on your new position.",
"body": "You are certainly the best person for the job!"
}),
success: function(a){
alert(2222)
},
error: function(a){
alert(JSON.stringify(a))
}
})
},
error: function(a){
alert(JSON.stringify(a))
}
})
}
}
});
I'm trying to send a getJson call from my app (login form) to get an external JSON from PHP file. and there if login and password are ok. My app will redirect from login.html to home.html.
This is my script located in login.html shown below
<script>
function testlogin() {
var login = $('#login').val();
var password = $('#password').val();
$.ajax({
url: "http://http://10.0.2.2/YasmineMarket.php",
data: { login: JSON.stringify(login), password: JSON.stringify(password) },
dataType: "jsonp",
success: function(json, textstatus) {
if (json.d == 'Login Success') {
var url = "acceuil.html";
$(location).attr('href', url);
}
else {
alert("Wrong Username or password");
var url = "index.html";
$(location).attr('href', url);
}
},
error: function(xmlHttpRequest, textStatus, errorThrown) {
if (xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0)
return;
else
alert(errorThrown);
}
});
}
</script>
<!DOCTYPE HTML>
<html >
<form id="loginForm" method="GET" >
<table border="0" align="center">
<tr><td></td></tr>
<tr><td align="center"><input type="text" name="login" id="login" /></td></tr>
<br>
<tr><td align="center"><input type="password" name="password" id="password" /></td></tr>
<tr><td align="center"><input type="submit" value="Connexion" onlick="testlogin();" class="button" /></td></tr>
</table>
</form>
</body>
This code is not sufficient to find the actual problem here. But this link might help you to write a server authentication. Please go through my old post about jsonp ajax request to a web server using jquery mobile and phonegap.