I want to use data from console but i dont know how to do it.
my code :
var Success = true;
var url = new URL(`https://${link}`);
var req = https.get(
url,
function (res) {
res.statusCode === 200 ? (Success = true) : (Success = false);
console.log(res);
}
};
The problem is that Success variable can't be used in in function(res).
I want to use that in here so i would know if the url can be access or not.
<td
className={`px-4 py-3 ${
Success
? `text-emerald-500`
: `text-red-500`
} text-center`}
>
{Success ? Success : Failed}
</td>
Related
This is my routes.py
#app.route('/test', methods=['POST', 'GET'])
def test():
# form = BrandChoice()
# email = request.form['email']
# name = request.form['name']
choice = request.form['choice']
print(choice)
q = session.query(Brand.brand).filter(Brand.pid == choice)
print(q)
return jsonify({'choice': q })
And this is my test.js file
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
name : $('#nameInput').val(),
email : $('#emailInput').val(),
choice : $('#brandInput').val()
},
type : 'POST',
url : '/test'
})
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
}
else {
$('#errorAlert').text(data.choice).show();
$('#successAlert').text(data.name).show();
// $('#errorAlert').hide();
}
});
event.preventDefault();
});
});
I don't quite get why is it that I cannot get the query result to show up. If I were to replace my 'q' with name for example, it works as intended.
How do I go about returning my query result so that I can display it in my errorAlert?
Thank you for the help everyone. I understand the issue with my code right now. q is a Query object. I did not even execute the query.
type_pid = session.query(LenSize.type_pid).filter(LenSize.pid == choice)
type_pid_result = session.execute(type_pid)
type_pid_count = type_pid_result.first()[0]
print(type_pid_count)
q = session.query(Type.initial).filter(Type.pid == type_pid_count)
print(q)
result = session.execute(q)
print(result)
id_count = result.first()[0]
print(id_count)
return jsonify({'name': id_count})
The amendments I have made was to execute my query and in return I would get a result proxy. Apply the first() method to obtain my desired output. That output was JSON serialisable. No changes were really made to my js file. A simplified version of my correction is below. Hope this helps!
q = session.query(Model.id).filter(Model.pid == choice)
result = session.execute(q)
row_id = result.first()[0]
I have been using the following code to successfully read the contents of an external webpage as a string - I haven't used this program in a month or so but it has suddenly stopped working even though the code has not been changed. I suspect the YQL API has been updated but I couldn't find any documentation that I could understand on this. (I am a beginner at JS). If someone could point me to how to update my code it would be much appreciated!
Code:
function formSubmitted(raceID) {
if(raceID.length < 4 && raceID > 0){
savedRaceID = raceID;
raceUrl = "http://www.bbk-online.net/gpt/lap"+raceID+".htm";
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0].replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
//THE ERROR IS COMING FROM ABOVE - REPLACE IS BEING CALLED ON A NULL OBJECT??
//SUGGESTS NO DATA RETURNED?
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: raceUrl,
type: 'GET',
success: function(res) {
processData(res.responseText);
}
});
}
else{
alert("Please enter a valid race number...");
}
}
I have highlighted where the error is coming from - it appears that the function is not returning any 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);
i am trying to call function in other js file using require.all these the parameters
> Login = require("LoginRequest");
Create = require("CreateView");
var params = { username : username.value , password : password.value};
var type ="POST";
var URL = "https://localhost/post_auth.php";
var Result; </li>
and here the call funcion from LoginScreen.js
b2.addEventListener('click',function(e)
{
alert(params.username);
if (username.value != '' && password.value != '')
{
Result=Login.Request(params,type,URL);
}
else
{
// warning alert
alert("Username/Password are required");
}
if (Result.logged == true)
{
alert("Welcome " + Result.name + ", Please answer the following question");
Create();
}
else
{
alert(Result.message);
}
});
when i try to pass the parameters to LoginRequest.
function Request(params,type,url){
var Result;
var loginReq = Titanium.Network.createHTTPClient();
loginReq.open(type,url);
loginReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
//send parameters
loginReq.send(JSON.stringify(params));
loginReq.onload = function()
{
var json = this.responseText;
Result = JSON.parse(json);
alert (Result.logged);
alert (Result.name);
};
return Result;
};
exports.Request = Request;
the calling return undifiend object , where is my wrong here ?
That's because you are making an async call.
when you call loginReq.send() the call will be made and it will continue executing the rest of the code without waiting for the async call to be finished, that's why the function returns undefined.
To fix this you can make a sync call instead of an async call (this is a bad bad bad idea) or you could restructure your code, maybe LoginRequest could return the loginReq instance instead of the result
I have a issue in getting response in Kony application. this is the code
function getServerResponceOption(url){
alert(url);
var httpclient2 = new kony.net.HttpRequest();
var requestMethod = constants.HTTP_METHOD_GET;
var async = true;
httpclient2.open(requestMethod, url,async);
if(getAccessToken() != null && getAccessToken() != ""){
httpclient2.setRequestHeader("AuthToken",getAccessToken());
}
httpclient2.send();
httpclient2.onReadyStateChange = HandleResponce(httpclient2);
}
function HandleResponce(obj)
{
alert("Getting data "+obj.readyState+" Status "+obj.status+" Response "+obj.response );
if(obj.readyState == 4 )
{
if (obj.response != null && obj.response != "")
{
var jsonObj = obj.response;
handleResponseOption(0,jsonObj);
return;
}
else
{
}
}else{
var state = obj.status;
alert("Readystate "+obj.readyState+" Status = "+state);
}
if (obj.response != null && obj.response != "")
{
var jsonObj = obj.response;
handleResponseOption(1,jsonObj);
}
}
Here i got server response if i put the alert message in HandleResponce(obj) without the alert i didn't get any response. the ready state is 1 and status is 0. What is the problem occurred if i remove the alert message?
Note: URL and getAccessToken() is getting values.
You are calling function in line, When you use HandleResponce(httpclient2) function is immediately executed.
httpclient2.onReadyStateChange = HandleResponce(httpclient2);
Change your code as
httpclient2.onReadyStateChange = function(){ HandleResponce(httpclient2) };