Cant get ajax response to place nice with python code - javascript

Question: For some reason I can't seem to figure out why my ajax call will not return a value for success if my wo_data query comes up empty. What I want to happen is if I put a value into id_work_order and its not found in my db pop up an alert saying workorder was not found- otherwise if it is found return success which works. Any help would be greatly appreciated!
What happens is I get this if a workorder is not found in my browser console
typeerror: data[0] is undefined
if it is found I get this
success
Here is what my data looks like if the workorder is found in my response
0: object
purch_order: "1"
success: "success"
part_rev: "A"
part_number: "12345"
work_o: "W0000001"
customer_name: "TEST"
if it isn't found I get nothing back in my response
here is my views.py
def get_work(request):
if request.is_ajax():
q = request.GET.get('workorder_id', '')
wo_data = Dim_work_order.objects.filter(base_id__icontains = q )[:1]
results = []
for x in wo_data:
x_json = {}
if wo_data.exists():
x_json['success'] = 'success'
x_json['work_o'] = x.base_id
x_json['customer_name'] = x.name
x_json['part_number'] = x.part_id
x_json['part_rev'] = x.part_rev
x_json['purch_order'] = x.customer_po_ref
results.append(x_json)
else:
x_json['success'] = 'workorder_not_found'
results.append(x_json)
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)
else:
data = 'fail'
return render(request, 'app/sheet_form_create')
here is my workorder_ajax.js
$(document).ready(function () {
//$('#id_work_order').click(function () {
// getwork();
//});
$('#work_search').click(function () {
pop_other_fields();
});
//function getwork(){
// $('#id_work_order').autocomplete({
// source: "/sheet/sheet_form_create.html/get_work",
// minLenght: 2,
// });
//}
function pop_other_fields() {
var url = "/sheet/sheet_form_create.html/get_work?workorder_id=" + $('#id_work_order').val();
var work_order = document.getElementById('id_work_order').value;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
data: '',
success: function (data) {
if (data[0].success = "success") {
console.log(data[0].success);
$('#id_customer_name').val(data[0].customer_name);
$('#id_part_number').val(data[0].part_number);
$('#id_part_revision').val(data[0].part_rev);
$('#id_purchase_order').val(data[0].purch_order);
}
if (data.success = "workorder_not_found") {
alert("workorder not found :(")
}
}
});
}
});

the code here is never reached:
else:
x_json['success'] = 'workorder_not_found'
results.append(x_json)
because if if wo_data.exists(): is not true, then for x in wo_data: would never have any iterations in the first place.
Try:
def get_work(request):
if request.is_ajax():
q = request.GET.get('workorder_id', '')
wo_data = Dim_work_order.objects.filter(base_id__icontains = q )[:1]
results = []
if wo_data.exists():
for x in wo_data:
x_json = {}
x_json['success'] = 'success'
x_json['work_o'] = x.base_id
x_json['customer_name'] = x.name
x_json['part_number'] = x.part_id
x_json['part_rev'] = x.part_rev
x_json['purch_order'] = x.customer_po_ref
results.append(x_json)
else:
results.append({'success': 'workorder_not_found'})
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)

Related

An access to list values in AJAX

There is a request using AJAX. I'm sending data to the server and getting a response. There are no problems with this. But:
alert(response) returns [object Object].
alert(response.data[0]) returns undefined.
function requestFromCalendar() {
var first = selected[0];
var second = selected[1];
first.month = first.month+1;
second.month = second.month+1;
$.ajax({
data: {
first: JSON.stringify(first),
second: JSON.stringify(second)
},
type: 'POST',
dataType: 'json',
url: '/get_selected_values'
}).done(function(response) {
alert(response);
alert(response.data[0]);
})
}
#app.route('/get_selected_values', methods=['POST'])
def get_selected_values():
values = request.form.get("first")
first_date = json.loads(values)
values = request.form.get("second")
second_date = json.loads(values)
t = time(0, 0, 0, 0)
d = date(year=first_date['year'], day=first_date['day'], month=first_date['month'])
start_date = datetime.combine(d, t)
start_date = start_date + timedelta(microseconds=123456)
d = date(year=second_date['year'], day=second_date['day'], month=second_date['month'])
end_date = datetime.combine(d, t)
end_date = end_date + timedelta(microseconds=123432)
data = fetch_selected_date(start_date=start_date, end_date=end_date, login=current_user.get_id())
if data:
return jsonify({'data': data})
return jsonify({'data': []})
What's the matter? How to fix?
EDIT 1
console.log(response) returns {data: Array(0)}
console.log(response.data[0]) returns undefined
EDIT 2
The sending data stores in python code. It is seen in debug mode, so problem is not there for sure

How to correctly pass an array into JSON through an AJAX response, current response with empty objects?

I am looking pass an array into JSON through an AJAX response. As it stands when logged in the console the reply is as an empty object. It would fine if a single object is passed.
Would I be right in thinking I would need the .each() to separate out the array. I have tried this but with no luck.
Below is the server side JSON response creation:
$answers = answers::where('question_id', $question_id);
// Response
if ($request->ajax())
{
// JSON creation
return Array(
'enquiry' => $enquiry_id,
'question_title' => $question_title,
'answers' => $answers,
'q' => $q
);
}
Response::json([ 'enquiry' => $enquiry_id, 'question_title' => $question_title, 'q' => $q, 'answers' => $answers]);
}
And the client side response as part of .done()
.done(function(response){
console.log("Done!");
$('#myModal').modal('show');
var enquiry_number = response.enquiry;
var question_title = response.question_title;
var answers = response.answers;
console.log(question_title);
console.log(answers);
$('#myModal_title').html(response.question_title);
})
Whole AJAX
$('#continue_btn').on('click', function () {
var form = $("#form_1"); // or $("form"), or any selector matching an element containing your input fields
var app = $("[name='appliance']", form).val();
var a = $('#form_1').serialize();
var url = $('#form_1').attr('action');
var type = $('#form_1').attr('method');
console.log(a);
$('#form_1').submit(function(event) {
event.preventDefault();
var formElem = $(event.currentTarget);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type : type,
url : url,
data : a,
dataType : 'json'
})
.done(function(response){
console.log("Done!");
$('#myModal').modal('show');
var enquiry_number = response.enquiry;
var q = response.q;
var question_title = response.question_title;
var answer = response.answers;
console.log(q);
console.log(question_title);
console.log(answer);
$('#myModal_title').html(response.question_title);
})
.fail(function(jqXHR, textStatus, errorThrown){
console.log("Fail!", jqXHR, textStatus, errorThrown);
});
});
$('#form_1').submit();
});
RESPONSE
{"enquiry":65,"question_title":"Washing Machine Diagnosis","answers":{},"q":{"id":1,"appliance_id":1,"question":"Washing Machine Diagnosis","created_at":null,"updated_at":null}}

How to make remote jquery validation for tied fields?

Let's say I have couple of input fields - their combination must be unique.
Each of them causes remote validation method triggering - and it's the same method for both fields. If combination is unique - it returns true.
The problem is following: when after validation error I change the field, that is not marked as erroneous, the erroneous field keeps being considered erroneous, even if method returns true (the couple is unique)!
I even don't need to make extra request to server, because the couple is unique! I just need to clear error for field, marked erroneous. However, I have not managed to do this - seems like jquery does not offer functionality for this.
Any ideas?
The relevant code is pretty huge, but the key parts are here:
this.clearErrors = function ($elements) {
var $validator = $elements.first().closest('form').validate();
$elements.each(function(index, item) {
var $parent = $(item).parent();
var element = $(item).get(0);
if ($parent.is('td')) {
$parent.removeClass(window.resources.errorCellClass);
}
$parent.find('span.' + window.resources.errorSpanClass).remove();
$validator.successList.push(element);
delete $validator.invalid[element.name];
delete $validator.submitted[element.name];
});
};
//Fixing remote method, since original one returned "pending" status all the time, as reported in other stackoverflow question
$.validator.addMethod('synchronousRemote', function (value, element, param) {
if (this.optional(element)) {
return 'dependency-mismatch';
}
var previous = this.previousValue(element);
if (!this.settings.messages[element.name]) {
this.settings.messages[element.name] = {};
}
previous.originalMessage = this.settings.messages[element.name].remote;
this.settings.messages[element.name].remote = previous.message;
if (typeof param == 'string') {
param = { url: param }
}
if (previous.old === value) {
return previous.valid;
}
previous.old = value;
var validator = this;
this.startRequest(element);
var data = {};
data[element.name] = value;
var valid = 'pending';
$.ajax($.extend(true, {
url: param,
async: false,
mode: 'abort',
port: 'validate' + element.name,
dataType: 'json',
data: data,
success: function (response) {
validator.settings.messages[element.name].remote = previous.originalMessage;
valid = response === true || response === 'true';
if (valid) {
var submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
delete validator.invalid[element.name];
validator.showErrors();
} else {
var errors = {};
var message = response || validator.defaultMessage(element, 'remote');
errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
validator.invalid[element.name] = true;
validator.showErrors(errors);
}
previous.valid = valid;
validator.stopRequest(element, valid);
}
}, param));
return valid;
});
$root.filter(':input[data-excluded-values-method]:not([readonly])').add($root.find(':input[data-excluded-values-method]:not([readonly])')).each(function () {
var $element = $(this);
$element.validate({
onkeyup: false
})
var $entityContainer = $element.closest('[data-entity]');
var $keyFields = $entityContainer.filter('INPUT[data-is-key]:not([disabled])').add($entityContainer.find('INPUT[data-is-key]:not([disabled])'));
var localizedNames = [];
$keyFields.each(function () {
localizedNames.push($(this).attr('localized-name'));
});
$element.rules('add',
{
synchronousRemote: function () {
var key = [];
var keyIsUnique = true;
$keyFields.each(function () {
key.push($(this).val());
});
return {
url: $element.attr('data-excluded-values-method'),
type: 'POST',
async: false,
data: JSON.stringify({
key: key,
entityType: $entityContainer.attr('data-entity')
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
dataFilter: function (isUnique) {
keyIsUnique = isUnique;
return isUnique;
},
complete: function () {
if (keyIsUnique === 'true') {
window.commonUtils.clearErrors($keyFields.filter('[name!="' + $element.attr('name') + '"]:input[data-excluded-values-method]:not([readonly])'));
}
}
}
},
messages: {
synchronousRemote: $.validator.format(window.resources.notUniqueValidationError)(localizedNames.join(' + '))
}
});
});
I've debugged jquery validate method and found what yet should be set to clear validation error:
$validator.previousValue(element).valid = true;
Now everything works.

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

Test object has a value in it or not in javascript

I have one class in javascript :
function Quotation(){
if(typeof Quotation.instance === 'object'){
return Quotation.instance;
}
Quotation.instance = this;
var self = this;
this.getQuotation = function(customerID,numRow){
var result = "";
var urlDefault = "mysite.com/getDefaultQuote" + "?id="+ customerID +"&count=" + numRow;
var url = "mysite.com/getQuote" + "?id="+ customerID +"&count=" + numRow;
$.ajax({
url:url,
type:type,
dataType:datatype,
contentType: contenttype,
data : JSON.stringify(data),
success:function(res){
result = res;
},
error:function(res){
result="";
},
async : false
});
return result;
};
}
This is where my view call Quotation object :
var quotation = new Quotation();
var HomeView = Backbone.View.extend({
initialize: function() {
},
render: function(){
console.log(quotation.getQuotation(10,12));
}
});
I want to test in getQuotation :
if quotation.getQuotation(10,12) has value in it, then getQuotation will take url = "mysite.com/getQuote" as an ajax request URL.
Otherwise if quotation.getQuotation(10,12) no record, then getQuotation will take urlDefault = "mysite.com/getDefaultQuote";.
Here the result in the console :
Any help is much appreciated.
You should check res inside the success callback and perform an extra AJAX request to load the default quote when res is null.
I would probably implement this logic server-side so that you always perform a single request.

Categories

Resources