hi im new in vertx and i want use https://github.com/vert-x/mod-mysql-postgresql for a service
i use this code for my web server
var vertx = require('vertx');
var console = require('vertx/console');
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
req.bodyHandler(function (data) {
//data is json {name:foo, age:13} i want insert this in any table in postgre
//do
var dataresponse= messagefrompostgre;//e: {status:"ok", code:200, message: "its ok"}
req.response.putHeader("Content-Type", "application/json");
req.response.end(dataresponse);
});
}
and this is my event click button
$.ajax({
data: {name:foo, age:13} ,
url: '/foo',
type: 'post',
dataType: 'json',
complete: function (response) {
alert(JSON.stringify(response));
}
});
I found how to do it:
var vertx = require('vertx');
var console = require('vertx/console');//TODO: remove
var eventBus = vertx.eventBus;
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
req.bodyHandler(function (data) {
//data is json {name:foo, age:13}
var jsona={
"action" : "raw",
"command" : "select * from test"
}
eventBus.send("PostgreSQL-asyncdb",jsona, function(reply) {
req.response.putHeader("Content-Type", "application/json");
req.response.end(JSON.stringify(reply));
});
});
}
and this return:
{"message":"SELECT 6","rows":6,"fields":["testt"],"results":[["lol"],["lolŕ"],["lol2"],["lol2"],["testlol"],["testlolp"]],"status":"ok"}
Related
I have used both PUT and POST request to modify and create a data. But the thing is POST request is not working properly. When i click on add() button , automatically POST request is generating id in the json-data before filling the information in the text fields.
Moreover data should be updated when I click on the save() button . Below I have pasted my code, if I have made any mistake tel me know and I appreciate every one whomever gives any information.
HTMl :
<button class="btn btn-info" ng-click="addmode()"> Add </button>
<button class="btn btn-success" ng-show="editMode" ng-click="saveinfo()"> Save </button>
Angular JS :
$scope.addmode = function(information) {
var postinfo = information;
$http({
url:'http://localhost:3000/contacts' ,
method : 'POST',
data : postinfo
})
.then(
function successCallback(response) {
$scope.selectedcontact = '';
console.log(response.data)
},
function errorCallback(response) {
console.log("Error : " + response.data);
});
};
First create services/api.js
angular.module('app')
.factory('api', function ($rootScope,ApiEndpoint, $http, $q,$timeout,$cookies) {
var get = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.GET};
return this.call(config);
};
var del = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.DELETE};
return this.call(config);
};
var post = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.POST, data: data};
return this.call(config);
};
var put = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.PUT, data: data};
return this.call(config);
};
return {call: call, get: get, post: post, del: del, put: put};
});
After create service/apiendpoint.js
angular.module('app')
.constant('ApiEndpoint', {
ServerUrl: 'http://localhost/',
BaseUrl: 'http://localhost/',
Methods: {GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE'},
Models: {
test:"fe_api/test",
},
URLS: {
QUERY: 'app/'
},
getUrl: function (url) {
var host=window.location.host;
var protocol=window.location.protocol ;
return protocol+"//"+host+"/"+url;
}
});
**Create model handler **
angular.module('app')
.factory('ApiService', function (api, ApiEndpoint) {
var getModel = function (url_part)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.get(url);
};
var getModelViaPost = function (url_part, data)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.post(url, data);
};
var postModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.post(url, data);
};
var putModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.put(url, data);
};
var deleteModel = function(model_name, id) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name + '/' + id;
return api.delete(url);
};
return {
getModel: getModel,
postModel : postModel,
putModel : putModel,
deleteModel : deleteModel,
getModelViaPost : getModelViaPost
};
});
write API call in the controller
var data = {
wut_token: $cookies.data,
};
ApiService.postModel(ApiEndpoint.Models.test, data).then(function (response) {
if (response.SUCCESS == "FALSE") {
} else {
}
})
I have similar issue like this one.
I'm trying to make AJAX login using Laravel 5.3 Auth.
Here's what I got so far:
var login = function()
{
var data = {};
data["email"] = $('#email').val();
data["password"] = $('#password').val();
if($('#remember').is(':checked'))
data["remember"] = "on";
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
// window.location.href = "/dashboard";
}
});
};
I'm sending CRSF token as X-CSRF-TOKEN header.
The problem is that when I successfully login, I say on the same page,
but in Network tab I can see that /dashboard page is loaded by I'm not
redirected.
In the same manner, when I pass wrong credentials, I stay on the same page,
but I can see that /login page is loaded in the separate call with an error message that should be actually displayed.
Also, I've tried without headers : { 'Content-Type': 'application/json' },
and sending data as: data = data, but I get the same thing.
Why the browser doesn't redirect to that page since it is loading it in the "background"?
Edit: I'm getting correct page as request response as well, I can see it
in console (console.log(data);).
//Login FORM
$(document).on('submit', 'form#FormID', function(e) {
e.preventDefault();
var forms = document.querySelector('form#FormID');
var request = new XMLHttpRequest();
var formDatas = new FormData(forms);
request.open('post','/login');
request.send(formDatas);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
if (request.responseText == 'success') {
setTimeout(function() {
window.location.href = "/dashboard";
}, 5000);
}else{
};
}
}
}
});
//Controller
public function authUser(Request $request){
$data = $request->except('_token');
$validate = \Validator::make($data, [
'email' => 'email'
]);
if ($validate->fails())
return 'Invalid email format for username.';
if (\Auth::attempt($data)) {
return 'success';
}else{
return 'Invalid username or password';
}
}
//Route
Route::post('/login', 'YourController#authUser');
The problem might be with the response AJAX request is expecting before redirect.
Try the above code.
in the controller method
function login(Request $request){
if(\Auth::attempt($request)){
return response()->json('success');
}else{
return response()->json('wrong username or pass', 401);
}
}
in ajax
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
window.location.href = "/dashboard";
},
error : function(data){
alert(data);
}
});
Here's an interesting solution.
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
if ($request->ajax()) {
return response()->json([
'error' => Lang::get('auth.failed')
], 401);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => Lang::get('auth.failed'),
]);
}
And this:
var loginForm = $("#loginForm");
loginForm.submit(function(e) {
e.preventDefault();
var formData = loginForm.serialize();
$('#form-errors-email').html("");
$('#form-errors-password').html("");
$('#form-login-errors').html("");
$("#email-div").removeClass("has-error");
$("#password-div").removeClass("has-error");
$("#login-errors").removeClass("has-error");
$.ajax({
url: '/login',
type: 'POST',
data: formData,
success: function(data) {
$('#loginModal').modal('hide');
location.reload(true);
},
error: function(data) {
console.log(data.responseText);
var obj = jQuery.parseJSON(data.responseText);
if (obj.email) {
$("#email-div").addClass("has-error");
$('#form-errors-email').html(obj.email);
}
if (obj.password) {
$("#password-div").addClass("has-error");
$('#form-errors-password').html(obj.password);
}
if (obj.error) {
$("#login-errors").addClass("has-error");
$('#form-login-errors').html(obj.error);
}
}
});
});
I know this is a known issue but I'm having difficulty on fixing my problem. It seems that I don't receive anything from my UI5 Application when I sent an image via FileUploader to my server. I am new to HCP and this is my first time handling XSJS file. I hope you can help me.
UI5.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("sample.controller.View1", {
handleUploadPress : function(oEvent)
{
var fileLoader =this.getView().byId("FileLoader");//XML View
var fileName = fileLoader.getValue();
jQuery.sap.require("sap.ui.commons.MessageBox");
if (fileName === "" )
{
sap.ui.commons.MessageBox.show("Please choose File.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
}
else
{
var uploadUrl = "https://xxxxxx/services/Sample.xsjs?file_name="+fileName;
var formEle = jQuery.sap.domById("UpdateContact--FileLoader");
var form = $(formEle).find("form")[0] ;
var fd = new FormData(form);
$.ajax({
url: uploadUrl,
type: "GET",
beforeSend: function(xhr)
{
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(data, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
$.ajax({
url: uploadUrl,
type: "POST",
processData :false ,
contentType: false,
data: fd,
beforeSend: function(xhr)
{
xhr.setRequestHeader("X-CSRF-Token", token);
},
success: function(data, textStatus, XMLHttpRequest)
{
var resptext = XMLHttpRequest.responseText;
jQuery.sap.require("sap.ui.commons.MessageBox");
sap.ui.commons.MessageBox.show(resptext, sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
if(data === "Upload successful"){
sap.ui.commons.MessageBox.show("File uploaded.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
}
},
error: function(data, textStatus, XMLHttpRequest)
{
sap.ui.commons.MessageBox.show("File could not be uploaded.", sap.ui.commons.MessageBox.Icon.ERROR, "Error");
}
});
}} ) ;
}
}
});
XSJS Service:
$.response.contentType = "text/html";
try
{
var conn = $.hdb.getConnection();
var filename = $.request.parameters.get("file_name");
var headers = $.entity.headers.length;
var pstmt = conn.prepareStatement("INSERT INTO \"XXX_ASSETS\".\"XXX\" VALUES('1',?,'test',CURRENT_USER,CURRENT_TIMESTAMP)");
if($.request.entities.length > 0){
var file_body = $.request.entities[0].body.asArrayBuffer();
pstmt.setBlob(1,file_body);
pstmt.execute();
$.response.setBody("[200]:Upload successful!");
}
else
{
$.response.setBody("No Entries");
}
pstmt.close();
conn.commit();
conn.close();
}
catch(err)
{
if (pstmt !== null)
{
pstmt.close();
}
if (conn !== null)
{
conn.close();
}
$.response.setBody(err.message);
}
}
My code was built based on the tutorials I have found on the internet. Thank You.
A good way to save the image is converting(Base64) and save as blob in HANA table.
Regards
I have scenario that first onload page i put data into one pouchdb and with same pouchdb with other event of click it have to go server and fetch data in same pouch but it create two id ,but i need is second time it have into same pouch with first time create id how can i do this??
out put:
first time:
ressss---->:{"rows":[{"value":{"existing":[{"pattano":1843,"surveyNo":"156 ","subdivNo":"3B","ownerDetails":[{"relNo":1,"ownerNo":1,"RelationCode":"3","status":"Existing","udsRatio":"0","MaxOwnNumb":"1","relation":"மகள்","owner":"த்ஃப்க்","surveyNo":"156 ","statofown":"E","relative":"த்ஃப்க்","subDivNo":"3B"}]}],"_id":"6163ED1A-B1E8-4A90-8EEF-BF4B1A1E6132","_rev":"1-dea5c55e64c7543a26f24192ec5e94a5"}}]}
second time:
ressss---->:{"rows":[{"value":{"existing":[{"pattano":1843,"surveyNo":"156 ","subdivNo":"3B","ownerDetails":[{"relNo":1,"ownerNo":1,"RelationCode":"3","status":"Existing","udsRatio":"0","MaxOwnNumb":"1","relation":"மகள்","owner":"த்ஃப்க்","surveyNo":"156 ","statofown":"E","relative":"த்ஃப்க்","subDivNo":"3B"}]}],"_id":"6163ED1A-B1E8-4A90-8EEF-BF4B1A1E6132","_rev":"1-dea5c55e64c7543a26f24192ec5e94a5"}},{"value":{"existing":[{"pattano":457,"surveyNo":"111","subdivNo":"4","ownerDetails":[{"relNo":2,"ownerNo":1,"RelationCode":"1","status":"Existing","udsRatio":"0","MaxOwnNumb":"4","relation":"மகன்","owner":"மணிவேல்","surveyNo":"111","statofown":"E","relative":"ஆலப்பன்","subDivNo":"4"}]}],"_id":"E421B84D-2481-4ED1-ABDD-0C0B24BAEB91","_rev":"4-6713d5be5336f69b0f6c776b5c343d49"}}]}
my function is:
function fetchOwners(existingOwnersObj)
{
//alert("in fetch owners");
var inputVal = JSON.stringify(existingOwnersObj);
//alert("inputVal===> "+inputVal);
var hash1 = cal_hmac(inputVal);
var m = "";
document.getElementById('imgdiv')
.style.display = 'block';
$
.ajax(
{
url: urlService + serviceName + '/getPattaOwnersforJoint?jsoncallback=?',
headers:
{
"emp_value": ses,
"signature": hash,
"roleId": roleId,
"timestamp": t,
},
type: 'POST',
dataType: 'jsonp',
data: inputVal.toString(),
// jsonpCallback:"aaa",
contentType: "application/json",
success: function(data)
{
// alert("im in success===>"+JSON.stringify(data));
existown = {};
existown.existing = data;
//existown.slNno=slNno++;
str = JSON.stringify(existown);
//alert("str----->"+str);
var str1 = JSON.parse(str);
//new Pouch('idb://tamilNilamExist', function(err, db)
Pouch(puch, function(err, db)
{
var doc = existown;
db.put(doc, function(err, doc)
{
if (err)
{
return console.error(err);
}
else
{
//alert("Data Locally Stored Successfully adkkdd exizthhh");
$("#imgdiv")
.hide();
}
});
});
// getexist();
//
},
error: function(jqXHR, exception)
{
// alert("Error:"+JSON.stringify(jqXHR));
alert("Error Occured");
document.getElementById('imgdiv')
.style.display = 'none';
}
});
}
It looks like you are using a very old version of PouchDB. If you update to 3.4.0, you should be able to easily do something like:
// only need to instantiate the PouchDB once
var db = new PouchDB('mydb');
// inside of asynchronous functions, just call the db directly
function asyncSomething() {
function asyncSomethingElse() {
db.put(...)
}
}
I want to get all post parameters.
This is my vertx code:
var vertx = require('vertx/http');
var console = require('vertx/console');
var Server= vertx.createHttpServer();
Server.requestHandler(function(req) {
console.log(req.path());
console.log(req.method());
console.log(req.params());
// nothing
if(myPostparametersContainAnyitem){ //do anything}
else{
var file = req.path() === '/' ? 'index.html' : req.path();
req.response.sendFile('html/' + file);}
}).listen(8081)
This is my button click code:
$.ajax({
data: {name:'foo',age:'13'},
url: '/somedir',
type: 'post',
dataType: 'json',
success: function (response) {
alert(response);
}
});
I discovered how to do it thanks
var vertx = require('vertx');
var console = require('vertx/console');
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
console.log(req);
req.bodyHandler(function (data) {
//data is json {name:foo, age:13}
//do
req.response.end(data);
});
}