Transfer form together with other data using one AJAX post. Django - javascript

Very simple task. It is necessary to transfer data from the form together with other data using AJAX POST. The problem is how to extract this data later from the form, because they represent a whole line.
$(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var form=$('#myform').serialize();
var data={};
data['form']=form;
data['csrfmiddlewaretoken']='{{ csrf_token }}';
data['other_data']='other_data';
$.ajax({
type: 'POST',
url: '/myajaxformview',
dataType: 'json',
data: data,
success: function (data, textStatus) {
$('#output2').html(JSON.stringify(data));
},
error: function(xhr, status, e) {
alert(status, e);
}
});
});
});
def myajaxformview(request):
if request.method == 'POST':
if request.is_ajax():
data = request.POST
print(data)
#<QueryDict: {'form': ['csrfmiddlewaretoken=VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9&field1=1&field2=2'], 'csrfmiddlewaretoken': ['VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9'], 'other_data': ['other_data']}>
form=data.get('form')
#csrfmiddlewaretoken=VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9&field1=1&field2=2
print(form)
return HttpResponse(json.dumps(data))
return render(request, 'foo.html')

Consider using of FormData:
$(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var data = new FormData(event.target);
data.append('form', event.target);
data.append('csrfmiddlewaretoken', '{{ csrf_token }}');
data.append('other_data', 'other_data');
$.ajax({
type: 'POST',
url: '/myajaxformview',
dataType: 'json',
data: data,
processData: false,
contentType: false,
success: function (data, textStatus) {
$('#output2').html(JSON.stringify(data));
},
error: function(xhr, status, e) {
alert(status, e);
}
});
});
});

Related

Trying to Request Data (POST) from FLASK API with Java Script

I am currently trying to request Data with Java Script from my API but it doesn`t work.
Everytime i POST i get the error, that "TypeError: 'NoneType' object is not subscriptable" in FLASK.
Code of my API:
#http://127.0.0.1:5000/fnd
#app.route('/fnd', methods=['POST'])
def fnd():
content = request.json
return jsonify(content['Text'])
For the Post I am using JQuery AJAX Requests
$(function ()
{
var output = $('#output');
$('#checkonfake').on('click',function(){
var texttocheck = $('#texttocheck').val();
var datad = {"Text": texttocheck}
console.log(datad);
if(texttocheck != ""){
$.ajax(
{
dataType: "json",
type: 'POST',
data:
{
datad
},
url: 'http://127.0.0.1:5000/fnd',
success: function (result)
{
console.log(result);
},
error: function ()
{
console.log("error");
}
});
}
})
});
I have like a Input Box and a button and as soon as i press the button the request should be sent off.
you can change code to this by string:
#http://127.0.0.1:5000/fnd
#app.route('/fnd', methods=['POST'])
def fnd():
s_json = request.get_data(as_text=True)
obj = json.loads(s_json)
return jsonify(obj['Text'])
and change html code to this:
datad = {"aaa":"aaaa", "bbb":"bbb","Text":"Text"}
$.ajax(
{
dataType: "json",
type: 'POST',
data: JSON.stringify(datad),
url: 'http://127.0.0.1:5000/fnd',
success: function (result)
{
console.log(result);
},
error: function ()
{
console.log("error");
}
});
or if you wana uses json
#app.route('/fnd', methods=['POST'])
def fnd():
return jsonify(request.form["Text"])
datad = {"aaa":"aaaa", "bbb":"bbb","Text":"Text"}
$.ajax(
{
dataType: "json",
type: 'POST',
data: datad,
url: 'http://127.0.0.1:5000/fnd',
success: function (result)
{
console.log(result);
},
error: function ()
{
console.log("error");
}
});
by the way:
i can't find the info for request.json in flask.palletsprojects.com
so.. i don;t know this param means and why it is none

How prevent that an user change the input value?

I've a website with the post, and when an user comment its I send an Ajax request.
$(document).on('submit', '.theFormComment', function(e){
var data_to_send = $(this).serializeArray(); // convert form to array
data_to_send.push({name: "cs_spotale", value: $.cookie("c_spotale") });
$.ajax({
type: "POST",
url: '/post/addComment',
data: $.param(data_to_send),
dataType: 'json',
success: function(data){
console.log(data);
if(data.user_id !== data.user_to_id) {
$.ajax({
type: "POST",
url: "/notification/addNotification",
data: {
post_id: data.the_post,
user_from_id: data.user_id,
user_to_id: data.user_to_id,
action: data.action,
cs_spotale: $.cookie("c_spotale")
},
dataType: 'json',
success: function(x){
socket.emit('sendNotification', {data: data, type: x.type, image: x.image});
},
error: function(){}
});
}
$('#comment-box-'+ data.the_post).val('');
$("input[id='csrf_prot']").val(data.c);
$(data.html).prependTo("#comment-" + data.the_post);
if(data.own !== data.username){
socket.emit('notify', data.own, data.username);
}
socket.emit('updateComment', {permaRoom: data.the_post, html: data.html});
},
error: function(data){
console.log(data);
}
});
e.preventDefault();
return false;
});
I saw that if I change the input value of my hidden field "post_id", the comment goes to another "post_id". There is a way to prevent this problem? Or any other idea?

How to return the 2nd data variable of an $.ajax() function?

Here's my ajax function. How do I console.log the first data variable? The below code doesn't work:
$('.comment_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: {
'text': $('.comment_text').serialize(),
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function() {
console.log(text)
}
})
})
However when I do this:
$('.comment_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data:
$('.comment_text').serialize(),
success: function(data) {
console.log(data)
}
})
})
it works fine. Any idea why?
Because
success: function() {
console.log(text)
}
text doesn't exist in this context.
this.data.text would work because you're inside a method of your object:
$.ajax({
type: 'POST',
data: {
'text': $('.comment_text').serialize(),
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function() {
console.log(this.data.text);
// everything from the object is accessible with this here (i.e. type and data fields)
}
})
try to get the data you want to send to an external variable so you will have access to its properties inside the ajax success callback function.
$('.comment_form').on('submit', function(e) {
var _data = {
'text': $('.comment_text').serialize(),
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
e.preventDefault();
$.ajax({
type: 'POST',
data: _data,
success: function() {
console.log(_data.text)
}
})
})
console.log($('.comment_text').val())
Your second example is working because it's logging the parameter dataof the success callback function, aka the response from the server.
$('.comment_form').on('submit', function(e) {
e.preventDefault();
var dataToSend = {
text: $('.comment_text').serialize(),
csrfmiddlewaretoken: '{{ csrf_token }}',
};
$.ajax({
type: 'POST',
data: dataToSend,
success: function() {
console.log(dataToSend.text)
}
})
})
Case 1:
If you just want to access the same text what you are sending in ajax data hit then you have to initialize it first. Because text is not any variable here so far so it will give undefined. You can do it like:
$('.comment_form').on('submit', function(e) {
var requestData = {
'text': $('.comment_text').serialize(),
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
e.preventDefault();
$.ajax({
type: 'POST',
data: requestData ,
success: function() {
console.log(requestData.text)
}
})
})
Case 2: If you are trying to access the text from ajax response then you have to pass the same parameter in success function.
$('.comment_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: {
'text': $('.comment_text').serialize(),
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function(text) {
console.log(text)
}
})
})
Well if you want to serialize and want some data to be sent along the way.
Here is what I do:
var myForm = document.getElementById('myForm');
formData = new FormData(myForm);
formData.append('custom_key', 'CUSTOM VALUE');
...
Then in AJAX data:
$.ajax({
...
data : formData,
...
});
Now in the backend code you can find your form fields as well as your custom key value.
Hope this helps.

Is it possible to send entire form including the files to server using jquery/ajax?

Is it possible to submit entire form (all the fields including fileupload) to server (webmethod or handler etc) using Jquery/Ajax? If yes, how?
ASPX:
$.ajax({
type: "POST",
url: "SupplierBidding.aspx/SubmitBid",
data: JSON.stringify({ id: $('#txtbidderid').val(), bidamt: $('#txtbidamt').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
span.fadeIn("slow", function () {
span.text(data.d).fadeOut('slow');
});
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
setTimeout(function () {
btn.prop('disabled', false);
}, 3000);
}
});
}
WebMethod:
[WebMethod]
public static string SubmitBid(string id, string bidamt)
{
//code
return "";
}
I would like to replace data: JSON.stringify({ id: $('#txtbidderid').val(), bidamt: $('#txtbidamt').val() }) with entire form including files also.
You can use Formdata.
FormData Docs
Code example.
var fdata = new FormData();
fdata.append( 'file', input.files[0] );
$.ajax({
url: 'http://yourserver.com/upload.php',
data: fdata,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log('siceess')
}
});
Did you try jQuery Form plugin?
It handles file uploads.
Worked for me before.

Send form email to a REST service using JSON

How to Send form email to a REST service using JSON
I´m trying so:
// Send Mail
$('#btn_send').click(function() {
// Data object contact
this.name = $('#inputnome').val();
this.email = $('#inputemail').val();
this.subject = $('#inputassunto').val();
this.message = $('#textareamsg').val();
this.toJsonString = function() {
return JSON.stringify(this);
};
$.ajax({
type: "POST",
url: "http://localhost:8080/MailWS",
data: contact.toJsonString(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status, jqXHR) {
alert(status.toString());
},
error: function(jqXHR, status) {
alert(status.toString());
}
});
});
I think the problem is that you're not binding onclick action to your button. Try enclosing your whole javascript in $( document ).ready(function() {}); or do something like this which is cleaner.
$( document ).ready(function() {
$('#btn_send').click(function() {
sendEmail();//
});
});
function sendEmail(){
var valuesArr = new Array();
valuesArr.push($('#inputnome').val());
valuesArr.push($('#inputemail').val());
valuesArr.push($('#inputassunto').val());
valuesArr.push($('#textareamsg').val());
var jsonText = JSON.stringify(valuesArr);
$.ajax({
type: "POST",
url: "http://localhost:8080/MailWS",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status, jqXHR) {
alert(status.toString());
},
error: function(jqXHR, status) {
alert(status.toString());
}
});
}

Categories

Resources