I developed a web service using nusoap, seems that the web service works fine, in fact is very simple, I put here the code:
<?php
// Pull in the NuSOAP
require_once('lib/nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
//(MyService is name of our service)
$server->configureWSDL('WebService', 'urn:WebService');
// Character encoding
$server->soap_defencoding = 'utf-8';
//Register Insert user function
$server->register(
'InsertData', //Name of function
array('Id' => 'xsd:int',
'userName' => 'xsd:string',
'Pass' => 'xsd:string',
'Mail' => 'xsd:string'), //Insert Values
array('return' =>'xsd:boolean'), //return Values
'urn:ServiceWsdl', //Namespace
'urn:ServiceWsdl#InsertData', //SoapAction
'rpc', //style
'literal', //can be encoded but it doesn't work with silverlight
'Insert function to register users'
);
//Register GetData function
$server->register(
'GetData',
array('Id' => 'xsd:int'),
array('Id' => 'xsd:int',
'userName' => 'xsd:string',
'Pass' => 'xsd:string',
'Mail' => 'xsd:string'), //return values
'urn:ServiceWsdl',
'urn:ServiceWsdl#GetData',
'rpc',
'literal',
'Get all users function'
);
function InsertData($id, $userName, $Pass, $Mail) {
$connect = mysql_connect("server","userDB","passDB");
if ($connect) {
if(mysql_select_db("database", $connect)) {
mysql_query( "INSERT INTO `Users`(`Id`, `UserName`, `Pass`, `Mail`) VALUES (`".$id."`,`".$userName."`,`".$Pass."ยด,`".$Mail."`);");
return true;
}
}
return false;
}
function GetData($Id) {
$connect = mysql_connect("server","userDB","passDB");
if ($connect) {
if(mysql_select_db("database", $connect)) {
$sql = "SELECT * FROM Users";
$result = mysql_fetch_array(mysql_query($sql));
return $result['Id']."-".$result['UserName']."-".$result['Pass']."-".$result['Mail'];
}
}
return false;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
And my code on the Android Xamarin project (working from Visual Studio 2013) is very simple too:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = (Button) FindViewById<Button>(Resource.Id.MyButton);
TextView labelText = (TextView)FindViewById<TextView>(Resource.Id.editTextUserName);
button.Click += delegate
{
//showMessageWithName(labelText.Text);
AvitecWS service = new AvitecWS();
if (service.InsertData(69, "AnUser", "anUserPassword", "anUser#mail.com"))
{
//the following method just show a message :)
showMessageWithName("Message has been send!");
}
else
{
showMessageWithName("Upss... something was wrong :(");
}
};
}
Then, when I click the button and the app should to do the insert I 've got the following exception:
I think that it is happening because the format of the SOAP object is not correct, but I can't view where is error :(
I REALLY appreciate any help.
Thanks in advance.
This exception throws when the client side cannot establish a connection with the server. In this case (I'm using Hostinger) I changed the numeric server IP for mysql.hostinger.com, the translated domain name, in fact is the same... but for a reason that I don't know it's just works using the translated domain name.
My code:
<?php
// Pull in the NuSOAP
require_once('lib/nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
//(MyService is name of our service)
$server->configureWSDL('AWebService', 'urn:AWebService');
// Character encoding
$server->soap_defencoding = 'utf-8';
//Register Insert user function
$server->register(
'InsertData', //Name of function
array('userName' => 'xsd:string',
'Pass' => 'xsd:string',
'Mail' => 'xsd:string'), //Insert Values
array('return' =>'xsd:boolean'), //return Values
'urn:AwebServiceWsdl', //Namespace
'urn:AwebServiceWsdl#InsertData', //SoapAction
'rpc', //style
'literal', //can be encoded but it doesn't work with silverlight
'Insert function to register users'
);
function InsertData($userName, $Pass, $Mail) {
$connect = mysqli_connect("mysql.hostinger.es", [USER], [PASSWORD], [DATABASE]);
if ($connect) {
mysqli_query($connect, "INSERT INTO `Users`(`UserName`, `Pass`, `Mail`) VALUES ('".$userName."','".$Pass."','".$Mail."')");
return true;
}
return false;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
By the way, I changed the mysql_connect() method to mysqli_connect() method, because the first is deprecated. Another mysql methods are changed too.
More info here:
Deprecated: mysql_connect()
Related
hello guys i developed an android app that http post req some data like latitude, longitude and IMEI to server that post in database. everything is working fine, but now comes the second part of the project. I need to make an web application that shows me on map a market with the lat and long saved in database and i don't understand how. I understood i should use querys but i don't understand who to use them.
this is my server side.
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
//connect to mongodb:
/*mongoose.connect('mongodb+srv://tudorstanciulescu:19970826#test-
srqul.mongodb.net/test?retryWrites=true&w=majority', {useNewUrlParser:
true} );
*/
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
//app.use(bodyParser.urlencoded({extended:true}));
//app.use(bodyParser.json());
app.use(bodyParser.json());
//var mongoose = require('mongoose');
app.post('/postBazaDate',(req,res)=> {
var latitudine = req.body.latitudine;
var longitudine = req.body.longitudine;
var imei = req.body.imei;
var dateTime = new Date();
;
var data = {
"latitude" : latitudine,
"longitute" : longitudine,
"imei" : imei,
"dateTime" : dateTime
}
// data.save()
// .then(item => {
// res.send("item saved to database");
// })
// .catch(err => {
// res.status(400).send("unable to save to database");
// });
MongoClient.connect(url, { useNewUrlParser: true }, function(err,
db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("date_locatie").insertOne(data, function(err, res)
{
if (err) throw err;
console.log("1 document inserted");
});
});
i don't have any errors, everything is working fine, but i can't understand how to use the data from database in a script from an html
In Node.js, same place where you have added app.post
app.get('/getBazaDate',(req,res)=> {
MongoClient.connect(url, { useNewUrlParser: true }, function(err,
db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("date_locatie").find({}, function(err, data)
{
if (err) throw err;
res.send(data); // here data is containing all saved data in array
//format
});
});
in html file
<!DOCTYPE html>
<html>
<body>
<h2>The = Operator</h2>
<p id="demo"></p>
<script>
const userAction = async () => {
fetch('http://localhost:3000/getBazaDate')
.then(response => response.json())
.then(json => console.log(json))
}
userAction();
document.getElementById("demo").innerHTML = response.json;
</script>
</body>
</html>
Simple REST Explanation
Ok so first is first, an html file is static and its contents can only be manipulated through javascript or css or someother language. Therefore, either you fetch the data before you load the page and send the data with the page , or you create an ajax call to get the data.
In a rest architecture you have GET , PUT , PATCH, POST ,DELETE Requests, each request is to either create ,read , or update the database.
A GET is to send data from server -> client, therefore a client requests data from the server and the server fetches and prepares the data for the client and sends it back.
Both PUT and PATCH updates the data in the database
A POST is to send from client -> server and save data
A DELETE to delete a row from the database
For more information about restfull you can visit this website: https://www.restapitutorial.com/lessons/httpmethods.html
or do a quick google search rest tutorial and you will find many !
Code Time
SERVER SIDE (USE ONE OF THESE) :
// app.js
// THIS GETS ONE ROW AND RETURNS OBJECT FROM THE DATABASE ACCORDING TO YOUR QUERY
app.get("/", (req,res,next) {
dbo.collection("date_locatie").find({}, function(err, res) {
if (err) throw err;
res.send(data);
});
})
// THIS GETS MANY ROWS AND RETURNS ARRAY FROM THE DATABASE ACCORDING TO YOUR QUERY
app.get("/", (req,res,next) {
dbo.collection("date_locatie").findAll({}, function(err, res) {
if (err) throw err;
res.send(data);
});
})
Now that your server is setup to get accept a GET REQUEST AND send back the data
All you have to do is call the url using an ajax call in javascript and your data will be sent to the client's pc.
To show the data you need to loop (if its array) and append data to HTML.
CLIENT SIDE :
In an html file you can write javascript in a script tag. This allows for the DOM elements to be manipulated. Supposed you have an empty with id locationData
and you want to fill it with the data that you saved
//index.html
//Assuming you are using jQuery
<div id="locationData"></div>
<script>
// WHEN HTML IS FULLY LOADED SENDS A GET REQUEST TO YOUR SERVER TO FETCH
// THE DATA
$( document ).ready(function() {
$.ajax({url: "http://localhost:3000/", success: function(result){
// PUTS THE DATA IN THE DIV WITH ID : locationData
$("#locationData").html(result);
}});
});
<script>
I've created a web service in codeigniter.
so here my controller:
public function insertsebab(){
$id=$this->input->post('id_konsultasi');
$sebab=$this->input->post('kd_sebab');
$data = array(
'id_konsultasi' =>$id,
'kd_sebab' => $sebab,
);
$konsultasi = $this->class_model->insertsebab($data);
if(count($konsultasi) > 0 ){
$json["STATUS"] = "SUCCESS";
$json["MESSAGE"] = "Data Berhasil Di Simpan";
$json["DATA"] = (object) array();
}
else{
$json["STATUS"] = "GAGAL";
$json["MESSAGE"] = "No data found in database";
$json["DATA"] = (object) array();
}
echo json_encode($json);
}
The code above explains how to insert data more than one in checkbox,but actually data save only one.
checkbox
so,how to create insert multiple check box in web service codeigniter?
I think u need to do a foreach with the post name.
here a same question :
Get multiple values of checkbox in codeigniter
I wish it helps you.
I wrote this code to connect to a database, make some queries and send them by json like web api.
I want to create plugin that will work like a WEB API. Then upload it on WP modules on internet and people may install them on their sites to connect my android App. Anywhere.
This is my php code (include db_connect and sending json and respond to my Android App)
<?php
if(!isset($_REQUEST ['id']))
echo "id is not set";
if (isset ( $_REQUEST ['id'] )) {
$id = $_REQUEST ['id'];
$response = array ();
mysql_connect('localhost','db_admin','password') or die(mysql_error());
mysql_select_db('db_name') or die(mysql_error());
$sql= "select * from employee";
$run=mysql_query($sql);
if (mysql_num_rows ($run) > 0) {
while ($row= mysql_fetch_array($run)){
$product = array ();
$product ["id"] = $row [0];
$product ["name"] = $row [1];
$product ["salary"] = $row [2];
$response [] = $product;
}
echo json_encode ( $response );
}
}
?>
My manager wants me not to use the default Woocommerse WORDPRESS API,so I have to create new plugin. and want to know how can I convert it to standard module?
Is it possible at all ?
If I was you I will created like this:
First off would create handler for the request, either via ajax (im not sure if this way is supported in android ) like this;
function get_some_information(){
$user_id = $_REQUEST['id'];
if(!isset($user_id) || empty($user_id)){
return json_encode([
'success' => false,
'message' => 'Empty Request'
]);
}
$data = get_info_from_data($user_id);
if(!empty($data)){
echo json_encode($data);
exit;
}else{
echo json_encode([
'success' => false,
'message' => 'Error while processing data'
]);
exit;
}
}
add_action('wp_ajax_get_some_information', 'get_some_information'); //for auth users
add_action( 'wp_ajax_nopriv_get_some_information', '_get_some_information' ); //for the rest
Note: there is an exit; you always need to terminate the application to be able to get the json, otherwise the output it will be 0
With this now we have an access point to data and validation; and it looks a bit more clean.
function get_some_information($id){
$result = [];
// do all things and added to the array
return $result;
}
I am having an issue with a Titanium App, the issue is only with Android, iOS is fine.
So I have a login form that queries the database, pretty straightforward. But for some reason it is not passing the params to the login script.
My JS function in app, have set the alert on the else statement to print out the $.email.value and password values which read fine. But with the current $response which is just a json it shows the values as being blank? The php form is also below. As I have said this is working fine on iOS
function login(e) {
//function to use HTTP to connect to a web server and transfer the data.
var sendit = Ti.Network.createHTTPClient({
onerror : function(e) {
Ti.API.debug(e.error);
alert('There was an error during the connection');
},
timeout : 100000,
});
//Here you have to change it for your local ip
sendit.open('GET', 'http://soyo.taylorhoganit.co.uk/post_auth.php');
var params = {
email : $.email.value,
password : $.password.value,
};
sendit.send(params);
//Function to be called upon a successful response
sendit.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == true)
{
var landing = Alloy.createController("landing").getView();
$.index.close();
landing.open();
// Ti.App.Properties.setString('email', $.email.value);
// Ti.App.Properties.setString('password', $.password.value);
//alert("Username: " + response.username);
}
else
{
alert($response);
}
};
};
PHP Script
<?php
// Connect to the database(host, username, password)
$con = mysql_connect('replaced values');
if (!$con)
{
echo "Failed to make connection.";
exit;
}
$db = mysql_select_db('soyo');
if (!$db)
{
echo "Failed to select db.";
exit;
}
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE email = '" . $email . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
$response = array(
'logged' => true,
'email' => $row['email']
);
echo json_encode($response);
}
else
{
// Else the username and/or password was invalid! Create an array, json_encode it and echo it out
$response = array(
'logged' => false,
'message' => $email + $password
);
echo json_encode($response);
}
?>
You did a mistake by using $response in the alert. It is a PHP variable not JS.
var response = JSON.parse(json);
// ...
alert($response); // Here should be just `response`
Edit: The another problem is that you are sending GET request while in PHP you accept POST ,so you can't get any params...
There is a mistake when you want to show alert.
You are using now is alert($response);
Remove $ from $response and use alert(response);, it will work properly.
Is it possible to communicate an android Application with cakePhp website and share data? If it is possible, I want to create an application that can login into the website; my doubt is:
How to pass user name and password from our application to cakephp websites login page? Can anybody show me an example program?
How cakephp controller handle this request and respond to this request? Please show me an example program?
(I am a beginner in android and cakephp.)
Quick answer -- YES!
We just finished pushing an Android app to the market place that does this exact thing. Here's how we did it:
1) Download and learn to use Cordova PhoneGap (2.2.0 is the latest version) within Eclipse. This makes the whole thing so much easier with just some HTML and a lot of Javascript.
2) In your JS, create methods that push the login information using AJAX parameters. Example:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
$("#login").click(function() {
$email = $("#UserEmail").val();
$pass = $("#UserPassword").val();
$.ajax({
url : yourURL + 'api/users/login',
async : false,
data : {
'email' : $email,
'password' : $pass
},
dataType : 'json',
type : 'post',
success : function(result) {
/**
* do your login redirects or
* use localStorage to store your data
* on the phone. Keep in mind the limitations of
* per domain localStorage of 5MB
*/
// you are officially "logged in"
window.location.href = "yourUrl.html";
return;
},
error : function(xhr, status, err) {
// do your stuff when the login fails
}
});
}
}
3) In Cake / PHP, your Users controller here will take the username and password data in the AJAX call and use that for its authentication.
<?php
class UsersController extends AppController {
public $name = 'Users';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('api_login');
}
public function api_login() {
$this->autoRender = false;
if ($this->request->data && isset($this->request->data['email']) && isset($this->request->data['password'])) {
$arrUser = $this->User->find('all',array(
'conditions'=>array(
'email'=> $this->request->data['email'],
'password' => $this->Auth->password($this->request->data['password']),
)
)
);
if (count($arrUser) > 0) {
$this->Session->write('Auth.User',$arrUser[0]['User']);
// Do your login functions
$arrReturn['status'] = 'SUCCESS';
$arrReturn['data'] = array( 'loginSuccess' => 1,'user_id' => $arrUser[0]['User']['id'] );
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
echo json_encode($arrReturn);
}
}
?>
That's pretty much it. You are now authenticated to CakePHP.
You do not need to use "api_", you can use any function name you want, but this helped us keep a handle on what we allowed mobile users to do versus web users.
Now, these are just the building blocks. You basically have to create a whole version of your site on the phone using HTML and Javascript, so depending on your application it may be easier just to create a responsive design to your site and allow mobile browsing.
HTH!
Use Admad JWT Auth Plugin
If you use cakephp3 change your login function with this one :
public function token() {
$user = $this->Auth->identify();
if (!$user) {
throw new UnauthorizedException('Invalid username (email) or password');
}
$this->set([
'success' => true,
'data' => [
'token' => JWT::encode([
'sub' => $user['id'],
'exp' => time() + 604800
],
Security::salt())
],
'_serialize' => ['success', 'data']
]);
}
You can read this tutorial about REST Api and JWT Auth Implementation
http://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/
if rebuild most of the view pages in cakephp into ajax will seem defeat the purposes of using cakephp as it is.