How does Flask handle JSON? - javascript

I'm working on editable table using FLASK, JSON and Jquery
I have serialised form and sent via $.getJSON you can see in the bottom of my JS code:
Here is the JS code:
$(function(){
$('tbody').on('click', 'td', function() {
displayForm( $(this) );
});
function displayForm (cell) {
var column = cell.attr('name'),
id = cell.closest('tr').attr('id'),
cellWidth = cell.css('width')
prevContent = cell.text(),
form = '<form action="javascript: this.preventDefault"><input type="text" name="newValue" size= "4" value="'+prevContent+'"/><input type="hidden" name="id" value= "'+id+'" />'+'<input type="hidden" name="column" value="'+column+'"/></form>';
cell.html(form).find('input[type=text]')
.focus()
.css('width', cellWidth);
cell.on('click', function() {return false;});
cell.on('keydown', function(e) {
if (e.keyCode == 13) {
changeField(cell, prevContent);
} else if (e.keyCode == 27) {
cell.text(prevContent);
cell.off('click');
}
});
}
function changeField(cell, prevContent) {
cell.off('keydown');
var url = '/jsonurl?',
input = cell.find('form').serialize();
$.getJSON(url+input, function(data){
if (data.success)
cell.html(data.value);
else {
alert('There was a problem updating the data.');
cell.html(prevContent);
}
});
cell.off('click');
}
});
and in the Processing side I use Flask to handle this data but when I edit the form and press enter to submit form it says: File "/Users/Team/Desktop/Flask/routes.py", line 72, in
jsonurl column = request.args.GET('column')
AttributeError: 'ImmutableMultiDict' object has no attribute 'GET'
What does this mean? It seems like I handle the JSON in the wrong way. Can anyone tell me what is the right way to handle this data?
Here are the codes in Processing side (which I think it is wrong and need your suggestion):
#app.route('/jsonurl')
def jsonurl():
column = request.args.GET('column')
id = request.args.GET('id')
newValue = request.args.GET('newValue')
g.db = connect_db()
cur = g.db.execute('UPDATE customer SET column = newValue WHERE rowid=id')
g.db.commit()
g.db.close()
return jsonify(success=True, value=newValue)

Use lowercase 'get' instead of 'GET' with request.args below:
request.args.get('column')
.args contain GET parameters.

Related

Modify text input value before POST in Javascript/jQuery

I'm currently trying to modify a text input's value and add a "v" as a pre-fix before the POST. This code is correctly changing the value and updating the field (i.e. I can see it add the 'v' after the submit), but if I look at the POST request in the debugger I an see the value does not contain the desired result. It just has whatever the original input was. Below is my code, what am I not connecting here?
$(document).on("ready", function() {
$('#stb-form').on("submit", function(e) {
var value = $('#gitVersionInput').val();
if (value === "") {
e.preventDefault();
return false;
}
var gitTag = 'v' + value;
$('#git-version').val(gitTag);
console.log(gitTag);
$(".modal").modal('show');
this.submit();
});
});
Try submitting the form using a normal input of type button rather than type submit.
<input type="button" id="form-submit" value="Submit">
$('#form-submit').on("click", function(e) {
var value = $('#gitVersionInput').val();
if (value === "") {
e.preventDefault();
return false;
}
var gitTag = 'v' + value;
$('#git-version').val(gitTag);
console.log(gitTag);
$(".modal").modal('show');
$('#stb-form').submit();
});

how to configure autocomplete search box to delete initial characters and not call the service

my project requirement is to create an autocomplete search box which fetches data from elastic search .
i will make it simple i have a textbox on which its onChange() event fires the autocomplete webservice and fetches the data. i am using angularjs 1.6 .
<input type="text" ng-change="fetchTags ()" ng-model="autocompleteData.text"/>
javascript
$this.fetchTags = function() {
try {
//remove special chars/
$this.autoCompleteData.text = purgerFilter($this.autoCompleteData.text);
//cancel previous timer;
if (autoCompleteTimer) {
$timeout.cancel(autoCompleteTimer);
}
//to avoid late response display suggesion list
$this.autoCompleteData.hasEmitted = false;
var txt = $this.autoCompleteData.getText();
if (typeof txt !== undefined) {
//200ms debounce.
var time = 200;
if (txt.length > 0) {
autoCompleteTimer = $timeout(function() {
$this.autoCompleteData.newTag = undefined;
initiateGetTopicTagsFromWebService();
}, time);
} else {
$this.autoCompleteData.setIsVisible(false);
}
}
} catch (e) {
throw e;
}
};
everything is working fine. dont go to other function calls. my problem is in this function.
so here is whats happening :
1.if i normally start typing everything works , i get the actucal and proper response as per keywords.
2.if i delete normally . i,e from last character to first it is working fine.
3.the problem case : if i had to remove the initial characters . eg my textbox word is java script. and i decide to remove the ending a from java . the service will be called with "jav script" which i dont want. this case should not case change function to fire.
this configuration i want in my autocomplete search textbox.
Did you expect like this..
ng-change not pass $event as variable.
angular.module("myapp", [])
.controller("MyController", function($scope) {
$scope.checkWord = "";
$scope.myData = function(event) {
// console.log(event);
if(event.keyCode == 8 || event.keyCode == 46){
// console.log(event);
if(event.srcElement.selectionEnd == $scope.checkWord.length || event.srcElement.selectionStart == $scope.checkWord.length){
$scope.msg="I'm going to call the function ";
}else{
$scope.msg="I'm not going to call the function ";
}
}
}
} );
<html><head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script></head>
<body ng-app="myapp">
<div ng-controller="MyController" >
<input type="text" ng-model="checkWord" ng-keydown="myData($event)"/>
<br><br>{{msg}}
</div>
</body>
</html>

Jquery Error validation insert div using after() but cannot remove

I want to show error validation messages next to the textbox. For that, I have used after() function and inserted a div. But the div gets appended again and again whenever the field is invalid. I just want it once. Can anybody help me with it?
Here's my code:
$(document).ready(function()
{
$("#name").blur(function()
{
var name = $("#name").val();
var txt= /^[A-Za-z\s]+$/i ;
if((txt.test(name) != true))
{
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
$("#one").empty();
}
else
{
$("#one").remove();
}
});
});
You could use HTML 5 field's validity which is the standard.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Your error message here')"
onchange="setCustomValidity('')" />
You should use additional variable to store your state. Try this logic.
$(document).ready(function() {
var flag = false;
$("#name").blur(function() {
var name = $("#name").val();
var txt = /^[A-Za-z\s]+$/i;
if (!txt.test(name) && !flag) {
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
flag = true;
}
else if (flag && txt.test(name)) {
flag = false
$("#one").remove();
}
});
});

Reselect checkboxes after Post in included file

I have page Search.asp (code below). And Filtered.asp which include Search.asp.
<%
Dim CheckForCheckboxes
CheckForCheckboxes = Request.form("chkBoxes")
response.write "CheckForCheckboxes" & CheckForCheckboxes
%>
<div id="ExSearch" name="ExSearch" >
<script>
// on page load check if this page called from POST and have passed checkboxes to select
var str = '<%=CheckForCheckboxes%>'; // {"Make[]":["AIXAM","CADILLAC","JEEP"],"selCountry[]":["5","4","8"]}
if (!str || str.length === 0) {} else {
var Checked = JSON.parse(str);
// alert works here
// This one not work
$("#ExSearch").find('div.list input[type=radio], input[type=checkbox],div.selector select').each(function () {
// alert do not work here
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value');
if (Checked[name] && Checked[name].indexOf(value) !== -1 ) {$el.prop('checked', true);}
});
};
// from here function which select checkboxes and hold them in hidden input field before submit, on submit pass this object with form
$(function() {
$('div.list input[type=checkbox], input[type=radio]').on('change',onValueChange);
$('div.selector select').on('change', onValueChange);
function onValueChange() {
var Checked = {};
var Selected = {};
// Hold all checkboxes
$('div.list input[type=radio]:checked, input[type=checkbox]:checked').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Checked[name]) === 'undefined') {Checked[name] = [];}
Checked[name].push($el.val());
});
// Hold all dropdowns
$('div.list select').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (!!$el.val()) {Selected[name] = $el.val();}
});
// Put all together to POST
$.ajax({
url: '/Search.asp',
type: 'POST',
data: $.param(Selected) + "&" + $.param(Checked),
dataType: 'text',
success: function (data) {
// Put response data to page and reselect checkboxes, this works good
$("#ExSearch").html(data).find('div.list input[type=radio], input[type=checkbox],div.selector select').each(function () {
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value');
if (Checked[name] && Checked[name].indexOf(value) !== -1 ) {$el.prop('checked', true);}
if (Selected[name]) {$el.val(Selected[name]);}
});
// Hold converted object to string values
$("<input type='hidden' value='' />").attr("id", "chkBoxes").attr("name", "chkBoxes").attr("value", JSON.stringify(Checked)).prependTo("#ajaxform");
}
});
};
});
</script>
<form name="ajaxform" id="ajaxform" action="Filtered.asp" method="POST">
</form>
</div>
So If page Search.asp starting I check if object passed via form post method, and if passed I need to select checkboxes which is in this object.
So I create object, then I convert it to string with Json.stringify and then catch form post string and convert back to object with JSON.parse
So everything look ok but checkboxes is not selecting and no errors appears.
What now is wrong?
Note what your code loading first and then loading your all divs so $("#ExSearch").find( cant find any checkboxes.
Try to put your <script></script> code after </form>

change textbox value in client side and read it in server side

I have some textbox and I change the value of this textboxes in clientside (javascript) ,value was changed but when I read in server side after postback actually value not changed. my textbox isn't read only or disable.
notice that I use updatepanel and my postbacks is async.any idea to solve this issue?
update
I use this jquery to support placeholder in ie,but it cause value of my textboxes equal to placeholder value, and this conflict when my postback is async. for solving this problem I use below jquery code:
function EndRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
//alert('end');
$('input, textarea').placeholder();
var $inputs = $('.placeholder');
$inputs.each(function () {
var $replacement;
var input = this;
var $input = $(input);
var id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch (e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': $input,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
});
}}
function safeActiveElement() {
// Avoid IE9 `document.activeElement` of death
// https://github.com/mathiasbynens/jquery-placeholder/pull/99
try {
return document.activeElement;
} catch (err) { }}
function BeginRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder').each(function () {
var input = this;
var $input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
alert($(this)[0].value);
$(this)[0].value = '';
alert($(this)[0].value);
$input.removeClass('placeholder');
input == safeActiveElement() && input.select();
}
}
});
}}
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestPostBackForUpdateControls);
prm.add_endRequest(EndRequestPostBackForUpdateControls);
});
I use this code to clear my textbox value before sending to server in add_beginRequest,and set value in add_endRequest (for placeholder in ie).
can anyone help solve this problem? thank you.
You changed the value of TextBox with javascript and the respective ViewState is not updated. You can use hidden field to store the value in javascript and get it in code behind.
Html
<input type="hidden" id="hdn" runat="server" />
JavaScript
document.getElementById("hdn").value = "your value";
Code behind
string hdnValue = hdn.Value;
Use hidden field to store the value, and retrieve it on the server side.

Categories