My web app works fine until i press the <button id="button" class="btn btn-primary btn-lg" onclick="sendForm()" value="GENERA XML">GENERA XML</button>
when i press it, the web app crash, i've check the debugger it seems like the function post is called two times, the first time the function works perfectly, the second time it runs it make my application crash.
this is the form:
<form class="container broadcast-form" action="/form" enctype="multipart/form-data" method="post">
this is my client side js:
function sendForm() {
const Form = document.querySelector('.broadcast-form')
let formSend = new FormData();
const cliente = Form.querySelector('#clienti').options[clienti.selectedIndex].text
formSend.append('cliente', cliente);
$.ajax({
url: '/form',
method: "POST",
dataType: 'json',
data: formSend,
processData: false,
contentType: false,
success: function(result){
console.log(result);
},
error: function(er){
console.log(er);
}
});
}
and this is my server side:
app.post('/form', (req, res) => {
con.query(('SELECT * FROM Tab_Clienti WHERE Cliente = "' + cliente +'"'), (err, QCliente, fields) =>{
if (err) console.log(err)
else{...}
})
})
For obvious reasons i've reduced the code with only the essential.
How do I let the application send the form just one time?
This is the missing part:
const cliente = Form.querySelector('#clienti').options[clienti.selectedIndex].text
const emittente = Form.querySelector('#emittenti').options[emittenti.selectedIndex].text
const inputFile = Form.querySelector('#path').value.replace(/.*[\/\\]/, '')
const dataT = Form.querySelector('#date').value
const oraTrasmissione = Form.querySelector('#timeTransmission').value
const sottotitolo = Form.querySelector('#sottotitolo').value
const titoloTrasmissione = Form.querySelector('#titoloTrasmissione').value
const presentatore = Form.querySelector('#presentatore').value
const sommario = Form.querySelector('#sommario').value
const keyword = Form.querySelector('#keyword').value
const currentDate = new Date().toLocaleDateString()
const currentTime = new Date().toLocaleTimeString();
const durataTrasmissione = Math.floor(Form.querySelector('#preview').duration);
const fileVideo = Form.querySelector('#preview').src
formSend.append('cliente', cliente);
formSend.append("inputFile",Form.querySelector('#path').value.replace(/.*[\/\\]/, ''));
formSend.append('emittente', emittente);
formSend.append('sottotitolo',sottotitolo);
formSend.append('dataT', dataT);
formSend.append('currentDate', currentDate);
formSend.append('currentTime', currentTime);
formSend.append('oraTrasmissione', oraTrasmissione);
formSend.append('durataTrasmissione', durataTrasmissione);
formSend.append('titoloTrasmissione', titoloTrasmissione);
formSend.append('presentatore', presentatore);
formSend.append('sommario', sommario);
formSend.append('keyword', keyword);
formSend.append('fileVideo', Form.querySelector('#preview').src);
and server side:
app.post('/form', upload.single('fileVideo'),(req, res) => {
var date = new Date(),
blockid = (date.toJSON().replace(/[\-T:.Z]/g, ''));
cliente = req.body.cliente
inputFile = req.body.inputFile
dataT = req.body.dataT
currentDate = req.body.currentDate
currentTime = req.body.currentTime
oraTrasmissione = req.body.oraTrasmissione
durataTrasmissione = req.body.durataTrasmissione
emittente = req.body.emittente
sottotitolo = req.body.sottotitolo
titoloTrasmissione = req.body.titoloTrasmissione
presentatore = req.body.presentatore
sommario = req.body.sommario
keyword = req.body.keyword
fileVideo = req.body.fileVideo
blockdate = JSON.stringify(date.getFullYear()) + "-" + JSON.stringify(date.getMonth()+1) + "-" + JSON.stringify(date.getDate()) + " " + JSON.stringify(date.getHours()) + ":" + JSON.stringify(date.getMinutes()) + ":" + JSON.stringify(date.getSeconds())
con.query(('INSERT INTO movedb.Tab_Invii (Data_Invio, Orario_Invio, Nome_File_Inviato, Cliente, Emittente, Orario_trasmissione, Durata_trasmissione, Nome_trasmissione, Titolo_Trasmissione, Presentatore, Keyword) VALUES ("' + currentDate + '","' + currentTime + '","' + inputFile + '","' + cliente + '","' + emittente + '","' + oraTrasmissione + '","' + durataTrasmissione + '","'+ sottotitolo + '","' + titoloTrasmissione + '","' + presentatore + '","' + keyword +'");'), (err, req, res)=>{
if (err) console.log(err)
else{
con.query(('SELECT * FROM Tab_Clienti WHERE Cliente = "' + cliente +'"'), (err, QCliente, fields) =>{
if (err) console.log(err)
else{
con.query(('SELECT * FROM Tab_Emittenti WHERE Emittente = "' + emittente +'"'), (err, QEmittente, fields) =>{
if (QEmittente[0].Media == 'TV') var mediaEmittente = 'T';
if (QEmittente[0].Media == 'Radio') var mediaEmittente = 'R';
if (QEmittente[0].Media == 'W') var mediaEmittente = 'W';
Try like below
$('.broadcast-form').unbind('submit').submit();
or
('.broadcast-form').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function( response ) {
}
});
return false;
});
The problem is that both:
<form class="container broadcast-form" action="/form" enctype="multipart/form-data" method="post">
AND
$.ajax({
url: '/form',
method: "POST",
dataType: 'json',
data: formSend,
processData: false,
contentType: false,
success: function(result){
console.log(result);
},
error: function(er){
console.log(er);
}
});
They Were sending the same form to the same "post" call, so one of them get the data and the other one not so the other one return an error. The solution is to let one of them address the call to another "post".
You should try to remove action in your code to have something like this:
<form class="container broadcast-form"
enctype="multipart/form-data" method="post">
Then in the sendForm() function pass e and add e.preventdefault() in your function.
Related
I have these columns on my table:
CardNumber
DateRegister
TimeRegister
DateExit
TimeExit
I read a value that is in a box, and when I press enter, the
Cardnumber, DateRegister,TimeRegister is add to the SQL Database
So I'll have like
CardNumber|DateRegister|TimeRegister|DateExit|TimeExit
124455|23-10-2022|11:00|null|null|
My Issue is, If I read the same card again, before I need to see if there is already one entrance on database with that card number, that don't have still DateExit and TimeExit.
If dont, I need to update that line, with that information, of if is a new one, will add a new entrance on the database
This is my code:
#section readcard{
<script>
$(function () {
$("#readONchange").change(function () {
var param1 = new Date();
var param2 = param1.getDate() + '/' + (param1.getMonth() + 1) + '/' + param1.getFullYear();
var param3 = param1.getHours() + ':' + param1.getMinutes() + ':' + param1.getSeconds();
var es = {};
/*es.IdCartao = $("#readONchange").val();*/
/*es.DateRegister = param2;*/
//Le cartao / Le data / Le Hora
es.IdCartao = $("#readONchange").val();
es.DateRegister = param2;
es.TimeRegister = param3;
if (es.IdCartao != null)
{
} else if (es.IdCartao == null) {
empregados.IdCartao = es.IdCartao(id);
(es.IdCartao == $("#readONchange").val && es.DateRegister != null && es.TimeRegister != null)
es.TimeExit = param3;
alert(es.IdCartao == $("#readONchange").val);
} else {
alert("erro")
}
alert("Register ADD!")
$.ajax({
type: "POST",
url: '#Url.Action("AddReport")',
data: '{es: ' + JSON.stringify(es) + '}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
sucess: function () {
alert("Data Insert with Sucess");
},
error: function () {
alert("ERROR! on the regist");
}
});
});
});
</script>
this is my c# code
public static void updateSubmit(string id,string fname,string lname,string email,string password,string address)
{
string connectionString = "mongodb://10.10.32.125:27017";
MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
MongoClient mongoClient = new MongoClient(settings);
var Server = mongoClient.GetDatabase("mongovaibhav");
var collection = Server.GetCollection<employee>("mongov");
ObjectId objectId = ObjectId.Parse(id);
var filter = Builders<employee>.Filter.Eq(s => s._id, objectId);
employee emp = new employee();
emp.fname = fname;
emp.lname = lname;
emp.email = email;
emp.pass = password;
emp.address = address;
collection.ReplaceOneAsync(filter, emp);
}
This is my ajax code with whom i send update request and data also
function updateSubmit()
{
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home.aspx/updateSubmit',
data: "{'id':'" + $("#hidden").val()+ "','fname':'" + $("#fname").val() + "','lname':'" + $("#lname").val() + "','email':'" + $("#email").val() + "','password':'" + $("#password").val() + "','address':'" + $("address").val() + "'}",
async: false,
success: function (response) {
alert("You Have SuccessFully Update Data");
},
error: function () {
console.log('there is some error');
}
});
}
Now My Problem is that i get the alert message that you have successfully update record but the record cant change effect in database
i Got the Solution i have Mistake In My "Param" Variable Where I Write Password Insted of "pass" because my employee class contain "pass" property
Thank you every one #souvik #felix
string connectionString = "mongodb://10.10.32.125:27017";
MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
MongoClient mongoClient = new MongoClient(settings);
var Server = mongoClient.GetDatabase("mongovaibhav");
var collection = Server.GetCollection<employee>("mongov");
ObjectId objectId = ObjectId.Parse(id);
var filter = Builders<employee>.Filter.Eq(s => s._id, objectId);
string param = "{$set: { fname:'" + fname + "',lname:'" + lname + "',email:'" + email + "',pass:'" + password + "',address :'" + address + "' } }";
BsonDocument document = BsonDocument.Parse(param);
collection.UpdateMany(filter, document);
I POST my table data using ajax in database. Now I want to get back when I give click the open button.
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
debugger;
//var p = JSON.stringify('[' + data + ']');
// alert(p.GetPageInfoResult[0])
//var k = data.main[0];
//alert(data.length);
//var jsonObj = $.parseJSON('[' + data + ']');
//alert(JSON.parse(data));
var jsonPretty = JSON.stringify(JSON.parse(data), null, 2);
},
error: function () {
alert('Error');
When I give my file name I want to display my pageinfo. I get data like
[{"main":{"sub":[],"tittle":"oops","startvalue":"21","stopvalue":"45","status":"","accumalated":"","comment":""}}]
You have not cleared where you want place your resultant Json. Below is that Success result placed in div having table . It is just a sample you may change as per your requirement:
function OnSuccess(response) {
debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var page = xml.find("Table");
var row = "";
$('#popupdiv tbody').html('');
page.each(function () {
var page = $(this);
row = " " + page.find("tittle").text() + " " + page.find("startvalue").text() +
" " + page.find("stopvalue").text() + " " + page.find("status").text() +
" " + page.find("accumalated").text() + " " + page.find("comment").text() + "";
$('#popupdiv tbody').append(row);
});
}
hey i am making a simple web form its a product detail insertion web page. I am trying to insert using ajax call. without ajax it works .. but $.ajax is not invoking my code behind static method, no idea wat's the issue. here's the code:
$(document).ready(function () {
$("#submit").click(function () {
var cat = document.getElementById('DropDownList1').value;
var nm = document.getElementById('name').value;
var cde = document.getElementById('code').value;
var dt = document.getElementById('dt').value;
var price = document.getElementById('price').value;
var f3 = document.getElementById('ty').innerHTML;
alert("you clicked " + cat + " - " + nm + "-" + cde + "-" + dt +
"-" + price + "-" + f3 + "-");
//////////////uptil here alert gives the right value.
$.ajax({
method: "POST",
contentType: "application/json",
url: "home.aspx/ins",
dataType: "json",
data: "{'Name :' + nm + 'code :' + cde +'category :'+ cat +
'date :'+ dt +'price :'+ pr +'img_name :' + f3}",
//data:"{}",
//async: false,
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
})
});
//////////////////////////////// here is the code behind method:
[System.Web.Services.WebMethod]
public static void ins(string Name,string code,string category, DateTime date,
int price,string img_name)
{
productclass pc = new productclass();
pc.Pr_name = Name;
pc.Code = code;
pc.Category = category;
pc.Expiry = date;
pc.Price = price;
pc.Pr_image = img_name;
dalinsert di = new dalinsert();
bool flag = di.insert(pc);
}
Correct way to pass data to ajax post via webmethod is like this.
var params = "{'Name' :'" + nm + "', 'code' :'" + cde + "', 'category' :'" + cat + "', 'date' : '" + dt + ", 'price' :'" + pr + "' , 'img_name' :'" + f3 + "' }" // Declare this above $.ajax...
data: params, //Use above in $.ajax... .
I believe the issue is in your data being passed in:
data: "{'Name :' + nm + 'code :' + cde +'category :'+ cat +'date :'+ dt +'price :'+ pr +'img_name :' + f3}"
I see two possible issues there. First, your '+' are being treated as literals there as they are surrounded by double quotes that are never escaped. What you are trying to achieve, I believe, is:
data: "{'Name :'"+ nm +"'code :'"+ cde +"'category :'"+ cat +"'date :'"+ dt +"'price :'"+ pr +"'img_name :'"+ f3 +"}"
However that still has a potential problem as I believe that json will be malformed. The expected syntax of a json string, with string variables at least, is '{"key1":"value1","key2":"value2"}'.
A better way to make sure your right and to save yourself work is to use JSON.stringify to do the work for you.
var temp = {};
temp.Name = nm;
temp.code = cde;
temp.category = cat;
temp.date = dt;
temp.price = pr;
temp.img_name = f3;
var data = JSON.stringify(temp);
I have web methods that are called via AJAX in a .Net 4.0 web app. In many cases, the AJAX calls are made repeatedly in a for loop. My problem is, the information the web method is syncing to my server is time stamped and therefore must be synced in the order in which I am sending it to AJAX. Unfortunately, it seems whatever finishes first, simply finishes first and the time stamps are all out of order. I need to basically queue up my AJAX requests so that they execute in order rather than Asynchronously, which I know is the A in AJAX so this might be a totally dumb question.
How do I force the order of execution for AJAX calls done in a for loop?
Edit: Some code
for (var i = 0; i < itemCnt - 1; i++) {
try {
key = items[i];
item = localStorage.getItem(key);
vals = item.split(",");
type = getType(key);
if (type == "Status") {
var Call = key.substring(7, 17);
var OldStat = vals[0];
var NewStat = vals[1];
var Date1 = vals[2];
var Time1 = vals[3];
var miles = vals[4];
try {
stat(Call, OldStat, NewStat, Date1, Time1, miles, key);
}
catch (e) {
alert("Status " + e);
return;
}
}
else if (type == "Notes") {
var Call = key.substring(6, 16);
var Notes = item;
try {
addNotes(Call, Notes);
}
catch (e) {
alert("Notes " + e);
return;
}
}
else if (key == "StartNCTime" || key == "EndNCTime") {
var TechID = vals[0];
var Date = vals[1];
var Time = vals[2];
var Activity = vals[3];
var Location = vals[4];
var Type = vals[5];
try {
logTime(TechID, Date, Time, Activity, Location, Type,
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
function stat(Call, OldStat, NewStat, Date1, Time1, miles, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/update_Stat",
data: '{ CallNumber:"' + Call + '", OldStat:"' + OldStat + '", NewStat:"' + NewStat + '", Date1:"' + Date1 + '", Time1:"' + Time1 + '", Miles: "' + miles + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Update Stat: " + err.Message);
location = location;
}
});
}
function logTime(TechID, Date, Time, Activity, Location, Type, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/nonCallTime",
data: '{ TechID:"' + TechID + '", Date1:"' + Date + '", Time1:"' + Time + '", Activity:"' + Activity + '", Location:"' + Location + '", Type: "' + Type + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Non Call Time: " + err.Message);
location = location;
}
});
}
function addNotes(Call, Notes) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/addNote",
data: '{ Call:"' + Call + '", Notes:"' + Notes + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Notes: " + err.Message);
location = location;
}
});
}
You have to use callbacks.
function ajax1(){
//..some code
//on ajax success:
ajax2();
}
//etcetera...
Or might I suggest using a javascript library like jQuery to synchronize your ajax requests for you.
set the third parameter in xmlhttp object's open method to false to make it synchronous.
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
A general pattern for making actions serial would be such:
function doAjax(data, cb) {
...
// when ready call cb
}
(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
doAjax(data);
});
Doing so in a for loop would require recursion.
(function next() {
if ( i < n ) {
doAjax(data[i++], next);
}
})();