Как я могу отправить свою форму с помощью ajax с несколькими кнопками отправки, каждый со своим уникальным значением? Все, что я пытаюсь, просто заканчивается тем, что значение отправки не определено. И я также хочу загрузить файл с использованием той же формы, но я получаю ошибку 403 (FORBIDDEN), и всякий раз, когда я пытаюсь распечатать файл с помощью консоли, он печатает ---> FormData {} <---- Что это значит. Является ли моя переменная FormData() хранит NULL. Любая помощь будет замечательной!
<script>
$(document).ready(function(){
$("#compile").click(function(){
$("#formid").submit('function(event){
event.stopPropagation(); //stop stuff happening
event.preventDefault(); //Stop from submitting the form normally
console.log($(this).serialize());
var doc = new FormData($(this)[0]);
console.log(doc);
var $form = $( this ),
code = $form.find("input[name='user_code']").val(),
lang = $form.find("input[name='language']").val(),
csrf = $form.find("input[name='csrfmiddlewaretoken']").val();
var request = $.ajax({ //create an ajax call
//var $form =$(this),
type : $(this).attr('method'),
url : $(this).attr('action'),
data : {user_code : code,language : lang,flag : "compile",doc : doc,csrfmiddlewaretoken : csrf}, //get the form data
processData : false,
enctype : 'multipart/folr-data',
dataType : "text"
// success : function(data){alert(data);}
});
request.done(function(msg){ document.getElementById("demo").innerHTML=msg;
});
request.fail(function() { alert("fail")});
});
});
$("#save").click(function(){
$("#formid").submit('function(event){
event.stopPropagation(); //stop stuff happening
event.preventDefault(); //Stop from submitting the form normally
console.log($(this).serialize());
var doc = new FormData($(this)[0]);
console.log(doc);
var $form = $( this ),
code = $form.find("input[name='user_code']").val(),
lang = $form.find("input[name='language']").val(),
csrf = $form.find("input[name='csrfmiddlewaretoken']").val();
var request = $.ajax({ //create an ajax call
//var $form =$(this),
type : $(this).attr('method'),
url : $(this).attr('action'),
data : {user_code : code,language : lang,flag : "save",doc : doc,csrfmiddlewaretoken : csrf}, //get the form data
processData : false,
enctype : 'multipart/folr-data',
dataType : "text"
// success : function(data){alert(data);}
});
request.done(function(msg){ document.getElementById("demo").innerHTML=msg;
});
request.fail(function() { alert("fail")});
});
});
$("#submit").click(function(){
$("#formid").submit('function(event){
event.stopPropagation(); //stop stuff happening
event.preventDefault(); //Stop from submitting the form normally
console.log($(this).serialize());
var doc = new FormData($(this)[0]);
console.log(doc);
var $form = $( this ),
code = $form.find("input[name='user_code']").val(),
lang = $form.find("input[name='language']").val(),
csrf = $form.find("input[name='csrfmiddlewaretoken']").val();
var request = $.ajax({ //create an ajax call
//var $form =$(this),
type : $(this).attr('method'),
url : $(this).attr('action'),
data : {user_code : code,language : lang,flag : "submit",doc : doc,csrfmiddlewaretoken : csrf}, //get the form data
processData : false,
enctype : 'multipart/folr-data',
dataType : "text"
// success : function(data){alert(data);}
});
request.done(function(msg){ document.getElementById("demo").innerHTML=msg;
});
request.fail(function() { alert("fail")});
});
});
});
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js">
</script>
</head>
<body>
{{question.id}}. {{question.question_name}}
<br>
{{question.question_text}}
<form action="result" id="formid" method="POST" enctype="multipart/form-data">{% csrf_token %}
<input type="textarea" name="user_code"><br>
<input type="radio" name="language" value="c" checked="yes">c
<input type="radio" name="language" value="c++">c++<br>
<input type="file" name="doc" id="doc">
<input id = "save" type="submit" name="flag" value="save">
<input id ="compile" type="submit" name="flag" value="compile">
<input id = "submit" type="submit" name="flag" value="submit">
</form>
<a href="/leaderboard">Leaderboard</a>
<a href="/questionlist">Back To questions</a>
<br><br><br><br>
<p id = "demo"></p>
</body>
</html>
Прежде всего, вы не можете иметь несколько кнопок отправки на одной странице, у вас будет плохое время, делая это именно так. Просто превратите их в кнопки, так как вы на самом деле не представляете форму обычным способом.
<body>
<form action="result" id="formid" method="POST" enctype="multipart/form-data">
<input type="input" name="user_name"><br>
<input type="textarea" name="user_code"><br>
<input type="radio" name="language" value="c" checked="yes">c
<input type="radio" name="language" value="c++">c++<br>
<input type="file" name="doc" id="doc">
<div>
<input id ="save" type="button" name="flag" value="save">
<input id ="compile" type="button" name="flag" value="compile">
<input id ="submit" type="button" name="flag" value="submit">
</div>
</form>
</body>
Затем для вашего javascript вам действительно нужно отделить вызов ajax от всех этих событий щелчка и просто ссылаться на него как на функцию. Будет легче поддерживать линию. Вот краткий пример, чтобы вы шли в правильном направлении. Я не уверен точно, что вы хотите, так как все ваши 3 кнопки, похоже, делают то же самое в этот момент. Кроме того, этот ajax submit будет обрабатывать файлы, а также обычные входы, поэтому вам не нужно беспокоиться о том, чтобы отделить эту логику, если это то, о чем вы беспокоились.
$(document).ready(function(){
var function = ajaxSubmitForm(button,form,type){
var code = form.find("input[name='user_code']").val(),
lang = form.find("input[name='language']").val(),
csrf = form.find("input[name='csrfmiddlewaretoken']").val(),
formAction = form.attr('action'),
formData = new FormData(form[0]);
//I have no idea why you have three buttons executing the same submit
//But my guess is you want to submit different items with different buttons
//You can build that logic here if youw ant
if(type === 'secret') {
formData.append('username', 'JamesBond');
} else if (type === 'buttonData') {
formData.append('data', button.data('some-data-attribute'));
}
return $.ajax({
type: "POST",
url: formAction,
data: formData,
cache: false,
contentType: false,
processData: false,
timeout: 20000
});
}
$("#compile").on('click', function(){
var button = $(this),
type = $(button).data('type'),
form = $(button).closest('form'),
submitRequest = ajaxSubmitForm(button,form,type);
submitRequest.done(function(){
console.log("all done...");
}).fail(function(){
console.log("Something went wrong...");
});
});
$("#save").on('click', function(){
var button = $(this),
type = $(button).data('type'),
form = $(button).closest('form'),
submitRequest = ajaxSubmitForm(button,form,type);
submitRequest.done(function(){
console.log("all done...");
}).fail(function(){
console.log("Something went wrong...");
});
});
$("#submit").on('click', function(){
var button = $(this),
type = $(button).data('type'),
form = $(button).closest('form'),
submitRequest = ajaxSubmitForm(button,form,type);
submitRequest.done(function(){
console.log("all done...");
}).fail(function(){
console.log("Something went wrong...");
});
});
});