Jquery post response not available - javascript

I'm new to javascript, and this problem may be trivial but I need help.
My goal is to send a post to a python server based on tornado.
In the following function :
var machin = $.post( '/room/testroom', function( data ) {
truc = data;
return truc;
I never get back the content of truc.
This variable has an url inside it who will be used to create a new Websocket connection.
When I do console.dir(machin); I see the wanted responseText with the wanted url in the console, but I'm not able to get it outside of the console.
The variable data itself inside the function has my wanted data, as if I do :
alert(data)
I see an alert box with the wanted url.
Feel free to ask me for details as I may not be entirely clear.
Server side, my python code is this one:
def post(self, RoomName):
print 'je poste'
db = connect(host=config.SQLSERVER, user=config.SQLUSER, passwd=config.SQLPASS, db=config.SQLDB)
cursor = db.cursor()
uri = self.request.uri
url = uri.split('/')
RoomName = url[2]
sql = 'SELECT RoomID FROM abcd_un WHERE RoomName = %s', [RoomName]
cursor.execute(*sql)
RoomID = cursor.fetchone()
print 'RoomID', type(RoomID)
RoomID = str(RoomID[0])
RoomID = RoomID.decode()
fullurl = 'ws://' + self.request.host + '/socket/' + RoomID
#print uri
db.close()
wsurl = {
'url': fullurl,
}
wsurl_encoded = tornado.escape.json_encode(wsurl)
self.write(wsurl_encoded)

Try:
var machin = function (){
$.post( '/room/testroom', function( data ) {
truc = JSON.parse(data);
return truc;
}
Now call the function:
var response = machin();

Try:
var machin;
$.post( '/room/testroom', function( data ) {
machin = JSON.parse(data);
return True;
})

Related

How to send an integer from ajax without jquery?

I am trying to send an integer called 'petadid' from this js to the django view called 'petadlikeview'. But it looks like the data is not going there in the view.If i print 'petadid' in the view, it shows 'None'. Can anyone please tell me what is wrong? I am new to ajax and django.
Here is my js:
<script>
$(document).ready(function(argument) {
$.ajaxSetup({cache:false});
var element = document.getElementById("likes");
var petadid = $(this).attr("data-petadid");
element.addEventListener("click",function(){
var req = new XMLHttpRequest();
req.open("POST",'/petadlike/')
req.onload = function(){
console.log(req.responseText);
console.log(petadid);
var data = JSON.parse(req.responseText);
}
req.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
var data = {
'petadid':petadid,
}
req.send(data);
});
});
</script>
And here is my django-view:
def petadlikeview(request):
print("vau")
if request.method=="POST":
print("vai")
petadid = request.POST.get('petadid')
print(petadid)
petad = PetAd.objects.get(pk=petadid)
like_count = petad.petadlikes_set.all().count()
like, created = petadlikes.objects.get_or_create(user=request.user,petad=petad)
print(created)
if created is False:
petadlikes.objects.get(user=request.user,petad=petad).delete()
like_count -= 1
liked = False
else:
like.save()
like_count += 1
liked = True
dict = {'like_count':like_count}
return JsonResponse(dict)
return HttpResponse(str(like_count)+' people have liked this')
else:
return HttpResponse('Bad Request')
XMLHttpRequest will not automatically convert an object to POST data as jQuery does, you need to create the URL-encoded string yourself.
var data = "petadid=" + encodeURIComponent(petadid);
Also
var petadid = $(this).attr("data-petadid");
should probably be
var petadid = $(element).attr("data-petadid");

Data not coming in JSON format from Splunk Javascript sdk

I am querying Splunk using javascript SDK. In the searchParams, i have given the output mode as "json_rows".
var searchParams = {
exec_mode: "normal",
output_mode: "json_rows"
};
But still when i get the output, i don't get it in a JSON format. The output is coming as an array.
Any idea what is going wrong? I tried "json_cols" and only "json" also. Same result.
Thanks in advance.
Edit:2
Some more of the code
var service = new splunkjs.Service({
username:"xxx",
password:"xxxx",
scheme:"https",
host:"xxxxxx.com",
port:"5500",
version:"5.0"
});
var searchQuery = 'search index=sn impact=1 OR impact=2 | eval time = round( strptime(impact_start,"%Y-%m-%d %H:%M:%S"), 0 )| where time >= ' + 14334627 + ' AND time<=' + 14568862 + '| bucket time span=1d | stats values(number) as incident_name by time';
var searchParams = {
exec_mode: "normal",
output_mode: "JSON"
};
service.oneshotSearch(
searchQuery,
searchParams,
function(err, results) {
if ( results ) {
var incidentResp = {};
incidentResp["data"] = results.rows;
incidentResp["error"] = null;
callback(null, incidentResp);
return;
}
else {
var errResp = {};
errResp["data"] = null;
errResp["error"] =err;
callback(null, errResp);
return;
}
}
);
I'm not 100% sure what you're asking, but let me try to help.
output_mode just tells the REST API how to serialize and return the results, usually either JSON, XML, or CSV
Given you're using the JavaScript SDK to pull data into your application and not actually having the results written to file, I would leave this as is (JSON default)
You'll find the actual data in the 'results' of the response.
eg.
service.oneshotSearch( query, params,
function(err, response) {
if (err) throw new Error ( err );
console.log( response.results );
});
Try changing this line:
incidentResp["data"] = results.rows;:
To this:
incidentResp["data"] = results.results;
... but yes, this will be an array of results.
Hope this helps

Unable to receive POST body from Ajax request using Play Framework

I am trying to send a POST request to my backend with some JSON data. The call from the frontend looks like this:
function register() {
var user = $("#form_reg_username").val();
var pass = $("#form_reg_password").val();
var referal = $("#form_reg_referal").val();
var postbody = {};
var url = "http://" + location.host + "/api/admin/register";
postbody.username = user;
postbody.password = pass;
postbody.referal = referal;
var jsonbody = JSON.stringify(postbody);
console.log(jsonbody);
$.ajax({
type: "POST",
url: url,
data: jsonbody,
dataType: "json",
success: registerHandler()
});
}
The generated log looks like this:
{"username":"jakob","password":"11111","referal":"urgotislove"}
Which is fine.
Here is the start of how I handle the request on the backend (I am using play 2.4)
public Result adminRegister() {
// Generate JSON from postbody
ObjectNode json = Json.newObject();
Logger.info("Body: " + request().body().asText());
JsonNode body = request().body().asJson();
String username = body.get("username").asText();
String password = body.get("password").asText();
String referal = body.get("referal").asText();
...
}
Looking at my application log the Info log looks like this:
[info] application - Body: null
I am then getting a Nullpointer Exception in first line of trying to get the json values.
So for some reason the POST body seems not to be received correctly.
Thanks for any help in advance.
Turns out the Postbody was transferred correctly but for some reason the .asText() as well as the .asJson() method, did not work correctly and returned null.
I fixed my issue with this little workaround:
Http.RequestBody requestBody = request().body();
Map<String, String[]> body = requestBody.asFormUrlEncoded();
String username = body.get("username")[0];
String password = body.get("password")[0];
String referal = body.get("referal")[0];

Making a POST request with jQuery+HTML to display JSON data

I want to display json data on frontend but after post request though it is successful it's giving specific data I need to generalize the code.This is python code.
import json
from flask import Flask, render_template, request, jsonify
import requests
app = Flask(__name__)
def post(url, payload):
returnData={}
if url == 'http://api/my-general-api':
r = requests.post(url, data=json.dumps(payload))
else:
r = requests.get(url)
#r = requests.get()
if r.status_code == 200:
returnData["status"] = "SUCCESS"
returnData["result"] = json.loads(r.text)
else:
returnData["status"] = "ERROR"
return returnData
def processSingleHost(perfid, hostname, iteration):
hostsData = {}
payload = {
"perfid" : perfid,
"section" : {
"hostname" : hostname,
"iteration" : iteration,
"sectionname" : "sysstat_M"
}
}
returnData = post('http://api/my-general-api', payload)
payload = {
"perfid" : perfid,
"section" : {
"hostname" : hostname,
"iteration" : iteration,
"sectionname" : "sysstat_x_1sec"
}
}
returnData1 = post('http://api/my-general-api', payload)
return {
"status" : "SUCCESS",
"sysstat_M" : returnData,
"sysstat_x_1sec" : returnData1
}
#app.route("/",methods=['GET','POST'])
def home():
if request.method == 'POST':
#user inputs
value1 = request.form.get('perfid')
value2 = request.form.get('hostname')
value3 = request.form.get('iteration')
#api call
url1 = 'http://api/my-general-api'/{0}'.format(value1)
payload= {}
rdata = post(url1,payload)
hostsData = {}
if rdata["status"] == "SUCCESS":
for item in rdata["result"]:
for host in item["hosts"]:
hostsData[host["hostname"]] = processSingleHost(value1,host["hostname"], 1) //here hostname contain specific value for specific host
else:
return "";
return jsonify(hostname=hostsData); // returning all host values
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
This is my .js file for accessing data :
$(document).ready(function() {
console.log("ready!");
$('form').on('submit', function() {
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="perfid"]').val();
valueTwo = $('input[name="hostname"]').val();
valueThree = $('input[name="iteration"]').val();
console.log(valueOne)
console.log(valueTwo)
console.log(valueThree)
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'perfid': valueOne,'hostname': valueTwo,'iteration': valueThree},
success: function(data) {
var x = parseInt(data.hostname.sysstat_M.result.sectoutput.summarystats.Avg.AVG); //here hostname is variable I am planning to use that will help to generalize access.
if(x>80)
{
var p = '<p><div class="isa_warning"><i class="fa fa-warning"></i>CPU may be overloading.</div></p>';
$('#result').append(p);
}
else
{
var p = '<div class="isa_success"><i class="fa fa-check"></i>CPU Usage is Normal.</div><p></p>';
$('#result').append(p);
}
},
error: function(error) {
console.log(error)
}
});
});
});
$('input[type="reset"]').on('click', function(e){
e.preventDefault();
$('#result').empty();
})
But as screenshot showing it demands me to make access specifically by giving hostname = 10.161.146.94/10.161.146.90
As mention in above .js
var x = parseInt(data.hostname.10.161.146.94/10.161.146.90.sysstat_M.result.sectoutput.summarystats.Avg.AVG);
But in future this hostname will be different.So I need to generalize it what can I do please suggest ??
SideNote:
If you are using hostname or IPs to identify each client its not adviced; since it is ought to fail.
You must use sessions for that.
Anyways, if your simply looking for how you can modify your javascript code to access the JSON response when you are not aware of the keys:
for(key in data){
console.log(key);
console.dir(data[key]);
}
Edit:
Showing in select box using jQuery can be done as:
var options = "";
for (key in data) {
options += '<option value="' + key + '">' + key + '</option>';
}
$("#my_dropdown").html(options);

How to send JSON data to CGI Perl Script in AngularJS and read back in Perl

I am using the following code for sending JSON Data to perl script.
ProductService.AddNewProduct = function(NewProduct) {
var ProductData = {};
ProductData = NewProduct;
ProductData = JSON.stringify(ProductData);
alert (ProductData);
var req = {
method: 'POST',
url: "cgi-bin/AddNewProduct2.pl",
params: { NewProduct: ProductData }
};
$http(req).success(function()
{
alert ('New Product Added!');
})
.error(function()
{
alert ('New Product Add Error!');
});
}
The alert is alerting this data.
{"ProductID":873,"ProductName":"sds","ProductImagePath":"/images/adidas/873.png","SubCategoryID":"153","SubCategoryName":"Cream Biscuits","BrandID":"162","BrandName":"Adidas","Variants":[]}
In perl script trying to get this data as follow:
my $cgi = CGI->new();
my $DecodedData = decode_json($cgi->param("NewProduct"));
my $product_id = $DecodedData->{'ProductID'};
my $product_name = $DecodedData->{'ProductName'};
my $product_description = 'Desc';
my $image_path = $DecodedData->{'ProductImagePath'};
my $brand_id = $DecodedData->{'BrandID'};
my $subcatty_id = $DecodedData->{'SubCategoryID'};
But none of the Perl variables are getting filled with data.
What is the issue? Can please someone help me.

Categories

Resources