I have been trying to update database without refreshing page. I got solution of using AJAX however, there is some issue and not able to work it out. Would you mind to have a look and suggest change.
I have added <script> for file path of .js file already. However, not able to update data in mysql. I am able to get data in html but not able to update.
app.py
#app.route('/update', methods=['GET', 'POST'])
def update():
# all_data = BankData.query.all()
if request.method == 'POST':
start_date = request.form.get('start_date')
end_date = request.form.get('end_date')
searched_data = db.session.query(BankData).filter(
BankData.process_date.between(start_date, end_date))
# db.session.add(searched_data)
# db.session.commit()
# start_date=start_date, end_date=end_date,
return render_template('update.html', start_date=start_date, end_date=end_date, searched_data=searched_data)
#app.route('/update_two', methods=['POST'])
def update_two():
# searched_data = session.get('searched_data')
if request.method == 'POST':
new_data = BankData.query.get(request.form['id'])
for data in new_data:
print(data.id)
new_data.id = request.form['id']
new_data.process_date = request.form['date']
new_data.description = request.form['description']
new_data.debit = request.form['debit']
new_data.category = request.form['category']
db.session.commit()
print("data submitted")
return jsonify({'result': 'success'})
app.js
$(document).ready(function () {
$('.updateButton').on('click', function () {
var data_id = $(this).attr('data.id');
var date = $('#dateInput' + data.id).val();
var description = $('#descriptionInput' + data.id).val();
var debit = $('#debitInput' + data.id).val();
var category = $('#categoryInput' + data.id).val();
req = $.ajax({
url: '/update_two',
type: 'POST',
data: { date: date, description: description, debit: debit, category: category, id: data_id }
});
req.done(function (data) {
$('#dataSection' + data_id).fadeOut(1000).fadeIn(1000);
// $('#dataNumber' + data_id).text(data.search_data);
});
});
});
Bellow is corrected code. and it is working fine.
$(document).ready(function () {
$('.updateButtonInvoice').on('click', function () {
var data_id = $(this).attr('data_id');
var invoiceNumber = $('#invoiceNumberInput' + data_id).val();
var invoiceDate = $('#invoiceDateInput' + data_id).val();
var weekEndDate = $('#weekEndDateInput' + data_id).val();
var storeNumber = $('#storeNumberInput' + data_id).val();
var description = $('#descriptionInput' + data_id).val();
var totalExGst = $('#totalExGstInput' + data_id).val();
var category = $('#categoryInput' + data_id).val();
req = $.ajax({
url: '/updatetwoInvoice',
type: 'POST',
data: { invoiceNumber: invoiceNumber, invoiceDate: invoiceDate, weekEndDate: weekEndDate, storeNumber: storeNumber, description: description, totalExGst: totalExGst, category: category, id: data_id }
});
req.done(function (data) {
$('#dataSectiontwoInvoice' + data_id).fadeOut(1000).fadeIn(1000);
});
});
});
Related
I implemented an Ajax CRUD. My Model has one ManyToMany field(category). If i choose only one item for this field everything will be good, but if choose multi items it shows form invalid error. Please tell me what should I do.
model.py:
class BusienssCategory(models.Model):
title = models.CharField(max_length=20, unique=True)
slug = models.SlugField(unique=True)
description = models.CharField(max_length=45)
def __str__(self):
return self.title
class BusienssProfile(models.Model):
title = models.CharField(max_length=20)
description = models.CharField(max_length=40)
category = select2.fields.ManyToManyField(BusienssCategory)
image = models.ImageField(upload_to=upload_image_path, null=True,
blank=True)
def __str__(self):
return self.title
form.py:
class BusinessForm(forms.ModelForm):
class Meta:
model = BusienssProfile
fields = ('title', 'category', 'shortDescription')
view.py:
def save_business_form(request, form, template_name):
data = dict()
form = BusinessForm(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
form.save()
data['form_is_valid'] = True
businesses = BusienssProfile.objects.all()
data['html_business_list'] = render_to_string('business/business_profile/partial_business_list.html', {
'businesses': businesses
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context,
request=request)
return JsonResponse(data)
ajax.js:
var saveForm = function() {
var form = $(this);
var data = new FormData($('form').get(0));
var categories = $("#id_category").val();
var featured = $('#id_featured').prop('checked');
var active = $('#id_active').prop('checked');
data.append("image", $("#id_image")[0].files[0]);
data.append("title",$("#id_title").val());
data.append("category", categories);
data.append("description",$("#id_Description").val());
$.ajax({
url: form.attr("action"),
data: data,
processData: false,
contentType: false,
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
Command: toastr["success"]("The profile has been
deleted.", "Success");
}
else {
Command: toastr["error"]("Something has gone wrong!", "Failure")
}
},
error: function(XMLHttpRequest, textStatus, errorThrown, url) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
return false;
};
I've already tested the form without Ajax and it doesn't show any error. I think something must be wrong in Multiselect return value.
Finally I solved the problem by using both of serializeArray and FormData together. I used Formdata to handle image field and serializeArray to serialize manytomanyField (and other fields). Here is my final js file:
var saveForm = function() {
var form = $(this);
serialData = form.serializeArray();
// We need to use FormData to upload image or file
var data = new FormData($('form').get(0));
data.append("image", $("#id_image")[0].files[0]);
var other_data = form.serializeArray();
$.each(other_data,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
url: form.attr("action"),
data: data,
type: form.attr("method"),
dataType: 'json',
cache: false,
processData: false,
contentType: false,
success: function (data) {
...
}
return false;
};
I'm new to jquery/ajax/javascript. I try to get data from an API, everything works, except, I can't print the data to my html-page. Somehow the appendChild-method doesn't work. What do I do wrong here? Thanks in advance!
function openkvk() {
var urls = "https://overheid.io/api/kvk?";
var keyset = {
"ovio-api-key": '041be6bc5818ad9bfe0ff9c9a9637a24b2fd1ec817cd8c3d102f61afc8006dd2'
};
var postcode = document.getElementById('plaats').value;
var naam = document.getElementById('bedrijfsnaam').value;
var kvk = document.getElementById('kvk').value;
console.log("tot aan hier1");
if(postcode != ""){
urls = urls + "&filters[postcode]=" + postcode;
}
if(naam != ""){
urls = urls + "&filters[handelsnaam]=" + naam;
}
if(kvk != ""){
urls = urls + "&filters[dossiernummer]=" + kvk;
}
console.log("tot aan hier2");
$.ajax({
type: 'GET',
url: urls,
headers:{"ovio-api-key":'041be6bc5818ad9bfe0ff9c9a9637a24b2fd1ec817cd8c3d102f61afc8006dd2',"Content-Type":"application/json"},
dataType: 'json',
complete: function(data) {
var response = data.responseJSON;
console.log(response);
var container = document.getElementById('result-kvk');
container.innerHTML = "";
console.log(data);
console.log("data geprint");
$.each(response._embedded.rechtspersoon, function(index,item){
console.log(item);
console.log("items geprint");
var kvknummer = document.createElement("P");
kvknummer.innerHTML = item.dossiernummer;
//console.log(kvknummer);
var handelsnaam = document.createElement('P');
handelsnaam.innerHTML = item.handelsnaam;
console.log("hwiueh");
//failed
container.appendChild(kvknummer);
container.appendChild(handelsnaam);
});
}
});
}
REQUEST URL http://localhost:9090/rest-api/fetchDetailedProductInfo?prodId=1&tempId=123
fetchDetailedProductInfo: function (prodId) {
var self = this;
var URL = 'http://localhost:9090/rest-api/fetchDetailedProductInfo'
$.ajax({
url: URL,
dataType: 'json',
contentType:'json',
type:'GET',
data: {
'prodId':prodId,
'tempId':123
},
success:function(responce) {
self.renderUI(responce.json);
},
error: function (err) {
console.log('ERROR',err)
}
});
},
# SERVER SIDE
router.get('/rest-api/fetchDetailedProductInfo', function (req, res) {
var prodId = req.param('prodId');
var tempId = req.param('tempId');
res.send(prodId + '----' + tempId);
}
I think you confused with req.params and req.query. Here is link to another question
Use req.query
var prodId = req.query.prodId;
var tempId = req.query.tempId;
Please see this
I'm using cascading drop down lists in my MVC application, and it works fine.
I have added the jQuery mobile library to make it look better in mobile devices browser and I have kind of bug.
An example:
if I choose first time Chevrolet it populate child drop down with Chevrolet models. - as expected
if I choose second time another make I still see the models from previous make, but if I select it I see the new model. It looks like it cashing the models from previous make.
Here is my code:
$(document).ready(function () {
$('select#Makes').change(function () {
getModels();
});
});
function getModels() {
var make = $('#Makes').val();
var myselect2 = $("select#Models");
myselect2[0].selectedIndex = 3;
myselect2.selectmenu("refresh");
$.ajax({
type: "POST",
url: "/Services/CarService.asmx/Models",
data: "{makeId: '" + make + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var models = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#Models').attr('disabled', false).removeOption(/./); //.addOption('', ' -- Select Model -- ');
var select = document.getElementById("Models");
for (var i = 0; i < models.length; i++) {
var val = models[i];
var text = models[i];
$('select#Models').addOption(val, text, true);
}
var myselect = $("select#Models");
myselect[0].selectedIndex = 3;
myselect.selectmenu("refresh");
}
});
}
#Html.DropDownList("Makes", "Please select make")
#Html.DropDownListFor(x => x.Models, new SelectList(Enumerable.Empty<SelectListItem>(), "value", "text"), "Select a Model", new { id = "Models" })
I am using fullcalendar to upload dates times to my database and i have the following script
$dialogContent.dialog({
modal: true,
title: "New Listing",
close: function() {
$dialogContent.dialog("destroy");
$dialogContent.hide();
},
buttons: {
save : function () {
calEvent.id = id;
id++;
calEvent.start = new Date(startField.val());
calEvent.end = new Date(endField.val());
calEvent.title = titleField.val();
calEvent.body = bodyField.val();
$.ajax({
type: "POST",
url: "addnew.php",
data: (
{
'st':new Date(startField.val()),
'et':new Date(endField.val()),
'title':titleField.val(),
'body':bodyField.val()
}
),
success: function(msg){
alert( "Data Saved: " + msg );
}
});
However my date values are not being sent at all. Its wrong but I don't know how or why.
the Date constructor does not parse any old date string. use fullCalendar's parsing function instead (provided you are using ISO8061 format):
http://arshaw.com/fullcalendar/docs/utilities/parseDate/
What value of date do you get in server side?
May be, you should to send simple data type like UNIX timestamp or using .serialize() for your form.
I have been playing around with ParseDate but I'm just not getting results, seems I have the concept all wrong;
dayClick : function(date, allDay, jsEvent, view) {
var $dialogContent = $("#event_edit_container");
y = date.getFullYear();
m = date.getMonth();
d = date.getDate();
h1 = date.getHours();
m1 = date.getMinutes();
h2 = h1 + 1;
m2 = m1;
calEvent = { title: 'New Calendar Event', editable:true, distributor: '', etype: '', location: '', website: '', start: new Date(y, m, d, h1, m1), end: new Date(y, m, d, h2, m2), allDay: false };
$calendar.fullCalendar("renderEvent",calEvent, true);
resetForm($dialogContent);
var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
var titleField = $dialogContent.find("input[name='title']").val(calEvent.title);
var distributorField = $dialogContent.find("input[name='distributor']").val(calEvent.distributor);
var etypeField = $dialogContent.find("select[name='etype']").val(calEvent.etype);
var locationField = $dialogContent.find("input[name='location']").val(calEvent.location);
var websiteField = $dialogContent.find("input[name='website']").val(calEvent.website);
var bodyField = $dialogContent.find("textarea[name='body']");
//var start_date = eval($.fullCalendar.parseDate(this_one['start']).getTime()) / 1000;
$dialogContent.dialog({
modal: true,
title: "New Listing",
close: function() {
$dialogContent.dialog("destroy");
$dialogContent.hide();
},
buttons: {
save : function () {
calEvent.id = id;
id++;
calEvent.start = $.fullCalendar.parseDate(new Date(startField.val()));
calEvent.end = new Date(endField.val());
calEvent.title = titleField.val();
calEvent.distributor = distributorField.val();
calEvent.etype = etypeField.val();
calEvent.location = locationField.val();
calEvent.website = websiteField.val();
calEvent.body = bodyField.val();
//$.fullCalendar.parseDate(calEvent.start);
//calEvent.st = start_date.val();
//$.fullCalendar.parseDate(startField.val());
$.ajax({
type: "POST",
url: "addnew.php",
data: (
{
'st':calEvent.start,
'et':new Date(endField.val()),
'title':titleField.val(),
'distributor':distributorField.val(),
'etype':etypeField.val(),
'location':locationField.val(),
'website':websiteField.val(),
'body':bodyField.val()
}
),
success: function(msg){
alert( "Data Saved: " + msg );
}
});
I'm at a brick wall with this I've tried tons of variations of hte code but its all just guess work. If there is an example of the date filed being passed or even printed out I'd really appreciate it just to see how this should work. Trial and error is not working for me in this case.
Thanks
It's late and i haven't used Javascript in a while, but surely it's input.value not input.val()