How get json parameters if I use post method in vertx? - javascript

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);
});
}

Related

Passing jQuery variables to Controller via AJAX

I am trying to send the variables from the GetTelephoneFunction to the AJAX query so it can reach the controller, but what I have tried does not work. Please help and thank you.
jQuery:
$.ajax({
type: "POST",
url: "/Status/GetUrlSource",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "url": $("#urlInput").val(), "user": $("#user").val(), "pass":$("#pass").val(),"freq": $("#freqInput").val() }),
dataType: "html",
success: function (result, status, xhr) {
//Code
}
function GetUrlTelePhone(html, status, result) {
var geturlUser = url.split('?username=')[1].split('&password')[0];
var geturlPass = url.split("&password=")[1];
var getUrlMain = url.split("?")[0];
var geturlParameters = url.split("aspx")[1];
}
Controller
public string GetUrlSource(string url, string freq, string user, string pass)
{
//user = user.Substring(0, 10) != "?" ? "?" + user : user;
//pass = pass.Substring(0,20) != "&" ? "&" + pass : pass;
url = url.Substring(0, 4) != "http" ? "http://" + url : url;
string htmlCode = "";
using (WebClient client = new WebClient())
{
try
{
htmlCode = client.DownloadString(url);
}
catch (Exception)
{
return "Not Found";
}
}
//SqlConnect(url);
Hangfire(url,freq,user,pass);
return htmlCode;
}

javascript works on localhost but fails on hosting server

When i click on add-to-basket button i see an error which appears in my browser console saying :
Here is my basket.js file :
$(document).ready(function() {
initBinds();
function initBinds() {
if ($('.remove_basket').length > 0) {
$('.remove_basket').bind('click', removeFromBasket);
}
if ($('.update_basket').length > 0) {
$('.update_basket').bind('click', updateBasket);
}
if ($('.fld_qty').length > 0) {
$('.fld_qty').bind('keypress', function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
updateBasket();
}
});
}
}
function removeFromBasket() {
var item = $(this).attr('rel');
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket_remove.php',
dataType: 'html',
data: ({ id: item }),
success: function() {
refreshBigBasket();
refreshSmallBasket();
},
error: function() {
alert('An error has occurred');
}
});
}
function refreshSmallBasket() {
$.ajax({
url: '/home/u919084925/public_html/mod/basket_small_refresh.php',
dataType: 'json',
success: function(data) {
$.each(data, function(k, v) {
$("#basket_left ." + k + " span").text(v);
});
},
error: function(data) {
alert("An error has occurred");
}
});
}
function refreshBigBasket() {
$.ajax({
url: '/home/u919084925/public_html/mod/basket_view.php',
dataType: 'html',
success: function(data) {
$('#big_basket').html(data);
initBinds();
},
error: function(data) {
alert('An error has occurred');
}
});
}
if ($(".add_to_basket").length > 0) {
$(".add_to_basket").click(function() {
var trigger = $(this);
var param = trigger.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket.php',
dataType: 'json',
data: ({ id : item[0], job : item[1] }),
success: function(data) {
var new_id = item[0] + '_' + data.job;
if (data.job != item[1]) {
if (data.job == 0) {
trigger.attr("rel", new_id);
trigger.text("Remove from basket");
trigger.addClass("red");
} else {
trigger.attr("rel", new_id);
trigger.text("Add to basket");
trigger.removeClass("red");
}
refreshSmallBasket();
}
},
error: function(data) {
alert("An error has occurred");
}
});
return false;
});
}
function updateBasket() {
$('#frm_basket :input').each(function() {
var sid = $(this).attr('id').split('-');
var val = $(this).val();
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket_qty.php',
data: ({ id: sid[1], qty: val }),
success: function() {
refreshSmallBasket();
refreshBigBasket();
},
error: function() {
alert('An error has occurred');
}
});
});
}
// proceed to paypal
if ($('.paypal').length > 0) {
$('.paypal').click(function() {
var token = $(this).attr('id');
var image = "<div style=\"text-align:center\">";
image = image + "<img src=\"/images/loadinfo.net.gif\"";
image = image + " alt=\"Proceeding to PayPal\" />";
image = image + "<br />Please wait while we are redirecting you to PayPal...";
image = image + "</div><div id=\"frm_pp\"></div>";
$('#big_basket').fadeOut(200, function() {
$(this).html(image).fadeIn(200, function() {
send2PP(token);
});
});
});
}
function send2PP(token) {
$.ajax({
type: 'POST',
url: '/mod/paypal.php',
data: ({ token : token }),
dataType: 'html',
success: function(data) {
$('#frm_pp').html(data);
// submit form automatically
$('#frm_paypal').submit();
},
error: function() {
alert('An error has occurred');
}
});
});
I tried to resolve it but couldn't find a proper solution.
Help me with this, I cannot understand the cause of this error.
This is mainly due to Rules of Origins (CORS), for some reason the javascript(browser) sees the request as not residing in the same server. And the reason for that, I believe, is because /home/u919084925/public_html/mod/basket.php is not seen as a valid url on the server, it should start with http://{hostname}/{path}.
It looks like your ajax url is totally wrong and the browser interpret that is cross origin ajax request. Please simply check in browser's address bar if your ajax provided urls are valid.

Inserting image to SAP HANA Table using XSJS

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

how to use PostgreSQL mod for vertx in js?

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"}

django request.user.is_authenticated() isn't returning true after page refresh (sometimes)

I have a registration form. After it is submitted, the page refreshes and I get some information back based on request.user. Sometimes request.user.is_authenticated() is returning True and everything works fine.... and sometimes False seemingly randomly.
I appreciate any insight into why this might be happening.
Registration form code
$('#reg_form').submit(function(e) {
e.preventDefault();
e.stopPropagation();
var serializedData = $(this).serializeArray();
var names = serializedData.map(function(r) {
return r.name;
});
var index_user = names.indexOf("regusername");
var index_pass = names.indexOf("regpassword1");
var index_email = names.indexOf("regemail");
var data2 = {};
data2["username"] = serializedData[index_user].value;
data2["password1"] = serializedData[index_pass].value;
data2["password"] = serializedData[index_pass].value;
data2["password2"] = serializedData[index_pass].value;
data2["email"] = serializedData[index_email].value;
console.log(data2);
var serializedFormData = $(this).serialize();
$.ajax({
url: window.url_root + '/accountsjson/register/',
type: 'POST',
dataType: 'json',
data: data2,
success: function(data) {
console.log(data); //remove
if (data.hasOwnProperty('success')) {
console.log("successful registration detected!!");
utils.loginAfterRegister(data2);
$('.register').slideUp();
$('.frame').hide();
} else {
utils.showRegister();
}
},
error: function() {
console.log("ERROR posting registration request. Abort!");
},
});
Function called from loginAfterRegister which has the refresh
function sendRating(rating, reload_on_return) {
$.ajax({
type: "POST",
dataType: 'json',
url: window.url_root + "/savecommentrating/1/" + rating.cid + "/",
data: {
"rating": rating.r2 / 100.0
},
success: function(data) {
if (data.hasOwnProperty('success')) {
console.log("data was sent!");
if (reload_on_return) {
location.reload();
}
}
},
error: function() {
console.log("rating didn't get sent!!");
}
})
}
mobile function within views.py
def mobile(request):
create_visitor(request)
os = get_os(1)
disc_stmt = get_disc_stmt(os, 1)
return render_to_response('mobile.html', context_instance = RequestContext(request, {'url_root' : settings.URL_ROOT,
'loggedIn' : str(request.user.is_authenticated()).lower(),
'client_data': mobile_client_data(request),
'client_settings': get_client_settings(True),
}))
create_visitor()
def create_visitor(request):
# See if we need to create a visitor here
if not request.user.is_authenticated() and not request.session.get('visitor_id', False):
visitor = Visitor()
visitor.save()
request.session['visitor_id'] = visitor.id

Categories

Resources