Python sqlite3 not updating some tables while others get updated - javascript

I am making a website with Python backend using flask and sqlite3. Most of my program is working, but I have a flask function that is called on a button click and executed in parallel with ajax request. It has 3 lines of sqlite updating 3 different table, but only the last one is making changes in the table. here is the function:
#app.route('/add_slot',methods=["POST","GET"])
def add_slot():
conn = sqlite3.connect("example.db")
sem = request.json["sem"]
sec = request.json["sec"]
sub = request.json["sub"]
teacher = request.json["teacher"]
room_no = request.json["room_no"]
time = int(request.json["time"])
day = int(request.json["day"])
cur = conn.execute("select assign_slot from teacher where teacher_name = '" + teacher + "'")
slots = cur.fetchall()[0][0]
slots = slots[:(day-1)*10 + time-1] + "1" + slots[(day-1)*10 + time:]
cur = conn.execute("select availability from room where room_no = " + room_no)
avail = cur.fetchall()[0][0]
avail = avail[:(day-1)*10 + time-1] + "0" + avail[(day-1)*10 + time:]
conn.execute("update room set availability = '" + avail + "' where room_no = " + room_no)
conn.execute("update teacher set assign_slot = '" + slots + "' where teacher_name = '" + teacher + "'")
conn.execute("update tt set subject_name = '" + sub + "', teacher_name = '" + teacher + "', room_no = " + room_no + " where semester = " + sem + " and section = '" + sec + "' and time_ = " + str(time) + " and day = " + str(day))
conn.commit()
conn.close()
return
And the JS code calling the function is:
The last sql line is working, which updates the table tt, but others don't. I tried executing the sql statements independently on the powershell, putting the same values for the variables as passed when the function is called, and they work in the powershell. So, why are they not working in the program?
function send_data(){
$.ajax({
type:'POST',
url:'/add_slot' ,
contentType: 'application/json;charset=UTF-8',
data : {'sec':document.getElementById("sec").value,'sem':document.getElementById("sem").value,'sub':document.getElementById("sub").value,'day':document.getElementById("sel1").value,'time':document.getElementById("sel2").value,'teacher':document.getElementById("sel3").value,'room_no':document.getElementById("sel_r").value}
});
close_popup();
initial_processing();
}

Related

How to insert an array with some repeating values into mysql using node.js

I'm trying to insert and values into my database and I thought having the same name for the inputs in my form would make it easier for me to insert them in bulk, I want to iterate OrderNo and quantity and insert them to a new column while keeping the other inputs such as fname the same until the values in OrderNo are done.
app.post("/send-data", (req,res)=>{
let sql = "INSERT INTO foodorder.orders (" +
"food_id," +
" qty,"+
" customer_FName," +
" customer_LName," +
" customer_number," +
" customer_email," +
" customer_facebook," +
" order_date," +
" delivery_option," +
" mode_of_payment," +
" delivery_time" +
") VALUES (" +
` ${req.body.OrderNo},` +
` ${req.body.quantity},` +
` "${req.body.fname}",` +
` "${req.body.lname}",` +
` "${req.body.Contact}",` +
` "${req.body.email}",` +
` "${req.body.facebook}",` +
` "${req.body.date}",` +
` "${req.body.delivery}",` +
` "${req.body.payment}",` +
`"${req.body.time}"` +
`)`;
con.query(sql, (err,result) => {
if(!err){
res.send(result);
}
else{
res.json(req.body);
throw err;
}
})
});
This is the code that I have and currently it only accepts 1 OrderNo and quantity and when I try to order many products with different quantities it will say column count doesn't match
value count at row 1 (see attached photo below)
[the output i get from my forms *I didnt include in the screenshot the other output details such as email etc.][1]
is there a way to just iterate the OrderNo and quantity and insert them creating new columns but with the same fname and lname etc.? or do i need to use MySql cursor?
Note that my code works and inserts if i only have selected 1 order and 1 quantity in my forms
UPDATE
Attached here is what I wanna achieve. I wanna know a way to iterate or loop the OrderNo and quantity and insert them into their respective columns while keeping the other values the same like fname and lname.
I wanna achieve this
Fixed by iterating the OrderNo. Thanks so much Diogo
app.post("/send-data", (req,res)=>{
let order = req.body.OrderNo;
let quantity = req.body.quantity;
let first = req.body.fname,
last = req.body.lname,
contact = req.body.Contact,
email = req.body.emailAdd,
fb = req.body.facebook,
date = req.body.date,
delivery = req.body.delivery,
payment = req.body.payment,
time = req.body.time,
address = req.body.address;
[order].forEach((product, index, arr)=>{
const q = quantity[index];
let sql = "INSERT INTO foodorder.orders (" +
"food_id," +
" qty,"+
" customer_FName," +
" customer_LName," +
" customer_address," +
" customer_number," +
" customer_email," +
" customer_facebook," +
" order_date," +
" delivery_option," +
" mode_of_payment," +
" delivery_time" +
") VALUES (" +
con.escape(product) + `,` +
con.escape(q) + `,` +
con.escape(first) + `,` +
con.escape(last) + `,` +
con.escape(address) + `,` +
con.escape(contact) + `,` +
con.escape(""+email) + `,` +
con.escape(fb) + `,` +
con.escape(date) + `,` +
con.escape(delivery) + `,` +
con.escape(payment) + `,` +
con.escape(time) +
`)`;
con.query(sql, (err,result) => {
if(!err){
res.redirect('thankyou.html');
}
else{
res.status(404).send('ERROR. Please Go back and Order Again');
}
})
})
});

Attempting to output to a text box with Javascript

I'm creating a communications generator that will standardise SMS communications regarding critical IT incidents for my company. I've got an IF/ELSE statement that identifies whether an issue is new, updated, or resolved to pull the necessary information together and format it accordingly. As far as I can tell, everything here is fine, however I'm having an issue writing to a text box ('smsToSend') which should allow the user to review before they copy the text across to our sms sender app, as nothing is being output into this box.
function generateSMS(){
var issueTitle = document.getElementById("incidentTitle");
var advisorImpact = document.getElementById("advisorImpact";
var incidentUpdate = document.getElementById("incidentUpdate");
var incidentStatus = document.getElementById("incidentState");
var startTime = document.getElementById("startTime");
var endTime = document.getElementById("endTime");
var incidentPriority = document.getElementById("incidentPriority");
var incidentBrand = "TechTeam";
var systemImpacted = document.getElementById("systemImpacted");
var incidentReference = document.getElementById("incidentReference");
var smsToSend = document.getElementById("smsToSend");
if (incidentStatus != "Closed"){
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT RESOLVED: " + systemImpacted + ": " + incidentUpdate + ": Start: " + startTime + " End: " + endTime + " Reference: " + incidentReference;
}
else{
if (incidentUpdate == "We are investigating this issue"){
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT ISSUE: " + systemImpacted + ": " + issueTitle + ". " + advisorImpact + ": " + incidentReference;
}
else {
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT UPDATE: " + systemImpacted + ": " + incidentUpdate + ": " + incidentReference;
}
}
}
generateSMS();
alert.getElementById(smsToSend);
Try replacing all assignments to smsToSend like this:
smsToSend = yourValue;
With this:
smsToSend.value = yourValue;
Your problem happens because smsToSend is an instance of an element, rather than a variable linked to the displayed text. To update the element's value, you have to change the value property of the element.
The Right way of setting the value to a text box is
var smsToSend = document.getElementById("smsToSend");
smsToSend.value = "Your value";

Get values from checkbox to calender

I'm new to this. And have a code. HTML form that has 4 Checkboxes
The result goes into a G-spreadsheet. From the Sheet I want the checked boxes values to polulate a Calendar event. Now it works but I get all the Checkboxes values in the calendar. Not only the ones that are checked.
function appendData(data){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Records");
Logger.log(data)
// Lägg till rad i spreadsheet
ws.appendRow([data.name, data.email, data.cuser, data.lastday, data.telenor, data.comment, data.company, data.costacc, data.laptop, data.ipad, data.printer, data.router]);
// Create data for event
var title = data.name + " börjar sin anställning på Roche"
var date = new Date(data.lastday)
var description = "<b>Mobil + Abonnemang:</b>\n" + data.telenor + "\n\n" +
"<b>Bolag:</b>\n" + data.company + "\n\n" +
"<b>Övrig utrustning:</b>\n" + data.laptop + ", " + data.ipad + ", " + data.printer + ", " + data.router
"<b>Kopiera rättigheter från:</b>\n" + data.cuser + "\n\n" +
"<b>Övriga kommentarer:</b>\n" +
data.comment

Square POS API adding Unique ID, is it possible?

I am working with Square POS API and have successfully sent a request to the android app via a mobile web app. The app opens, displays the correct price, accepts payment and returns to the callback URL.
I have read over the documentation a few times and may be missing it but is there a way I can add a Unique ID that is sent to the app and returned to the callback page so I can update the correct line item in the database?
possibly something like:
"l.com.squareup.pos.UNIQUE_ID=" + unique_id + ";" +
var posUrl =
"intent:#Intent;" +
"action=com.squareup.pos.action.CHARGE;" +
"package=com.squareup;" +
"S.com.squareup.pos.WEB_CALLBACK_URI=" + callbackUrl + ";" +
"S.com.squareup.pos.CLIENT_ID=" + applicationId + ";" +
"S.com.squareup.pos.API_VERSION=" + sdkVersion + ";" +
"i.com.squareup.pos.TOTAL_AMOUNT=" + transactionTotal + ";" +
"S.com.squareup.pos.CURRENCY_CODE=" + currencyCode + ";" +
"S.com.squareup.pos.TENDER_TYPES=" + tenderTypes + ";" +
"l.com.squareup.pos.AUTO_RETURN_TIMEOUT_MS=" + callbacktime + ";" +
"l.com.squareup.pos.UNIQUE_ID=" + unique_id + ";" +
"end";

firebase: update table data on client side every minute using javascript

Created a fake train schedule to try to learn firebase. communication between page and server is good however I want the times to update on the client side web page every minute but only the times. The times are displayed in a table.
//pull from database and prints to screen/html
trainDataBase.ref().on("child_added", function (childSnapshot) {
console.log("childSnapshot", childSnapshot.val());
// Store everything into a variable.
var trainName = childSnapshot.val().tname;
var destination = childSnapshot.val().dest;
var firstTrainTime = childSnapshot.val().firstTime;
var frequency = childSnapshot.val().freq;
// Minute Until Train
var tMinutesTillTrain = frequency - tRemainder;
console.log("MINUTES TILL TRAIN: " + tMinutesTillTrain);
// Next Train
var nextTrain = moment().add(tMinutesTillTrain, "minutes");
console.log("ARRIVAL TIME: " + moment(nextTrain).format("hh:mm"));
nextTrainConverted = moment(nextTrain).format("hh:mm A")
$("#train-table > tbody").append("<tr><td>" + trainName + "</td><td>" + destination + "</td><td>" + frequency + " Minutes" + "</td><td>" + tMinutesTillTrain + " Minutes" + "</td><td>" + nextTrainConverted + "</td><td>" + '<button class="update">Update</button>' + "</td></td>" + "</td><td>" + '<button class="remove">Remove</button>' + "</td></tr>");
});
Just want to update the train times and minutes till next train.

Categories

Resources