I send data from JS via JSON
var pricesum = sumprice;
var date = expirationdates;
var price = prices;
$.ajax({
type: "POST",
url: "print",
data: {
'pricesum': pricesum, 'date': date,'price': price,
},
They have the following form
expirationdate = request.POST.get('date', False);
price =request.POST.get('price', False);
print(expirationdate)
print(price)
Next, I get them in the django function, but I always get false. How do I get them correctly so that they are all in the array?
I'm trying
expirationdate = request.POST.get('date[]', False);
price =request.POST.get('price[]', False);
But I get only the last element of the array date and price
[('pricesum', '3600'), ('date[]', '2021-05-06'), ('price[]', '900')]
After some discussions, it seems that you should stringify your data in your ajax post request.
$.ajax({
type: "POST",
url: "print",
data: JSON.stringify({
'pricesum': pricesum, 'date': date,'price': price,
})
})
Then you can access the data posted by loading the stringified JON into your Python code :
import json
post_data = json.loads(request.body)
pricesum = post_data.get("pricesum", False)
date = post_data.get("date", False)
price = post_data.get("price", False)
Related
I have a form and i wanted specific elements of the form which I got and stored the values in an array.
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
var item_name = miniform.elements['itemId'].value;
var quantity = miniform.elements['quantityId'].value;
var amount = miniform.elements['amountId'].value;
var total = amount * quantity;
var cart = ["Item: ",item_name,"Quantity: ",quantity,"Amount: ",amount,"Total: ",total];
I would then like to convert this array into a JSON object and send it to a php file through ajax but its not working. Here is my ajax code:
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.stringify(cart),
success: function(){
console.log('Message Sent');
}
});
What could be the problem??
look the comma, it should be {"key":value, "key":value..} not {"key":,value, "key":,value..}
var cart = {"Item" : item_name, "Quantity" : quantity, "Amount" : amount, "Total" : total};
you are doing wrong .
please use this way
var cart = {"Item ":item_name,"Quantity ":quantity,"Amount ":amount,"Total ":total};
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.parse(cart),
success: function(){
console.log('Message Sent');
}
});
If you want to post the array Then you can use this way.
cart = [];
cart[0] = item_name;
cart[1] = quantity;
cart[2] = amount;
cart[3] = total;
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data:{cart:cart},
success: function(){
console.log('Message Sent');
}
});
Don't build it manually
Instead of building your Object or Array manually, which is prone to errors, do it like this:
Object
// Define your empty Object
var cart = {};
// Assign its properties
cart.item_name = miniform.elements['itemId'].value;
cart.quantity = miniform.elements['quantityId'].value;
cart.amount = miniform.elements['amountId'].value;
cart.total = amount * quantity;
Array
Or if you prefer to have an array:
// Define your empty array
var cart = [];
// Assign its properties
cart['item_name'] = miniform.elements['itemId'].value;
cart['quantity'] = miniform.elements['quantityId'].value;
cart['amount'] = miniform.elements['amountId'].value;
cart['total'] = amount * quantity;
Now you have your cart Object or Array ready and you can call JSON.stringify on it:
JSON.stringify(cart);
You could just send the entire form using formdata(). Is there a reason you don't?
Anyway, it doesn't work because you are not creating a json object, but a normal array. There's a difference. You can actually just put the json directly into the ajax call and you don't have to stringify it.
var cart = {};
cart['Item'] = item_name;
cart['Quantity'] = quantity;
cart['Amount'] = amount;
cart['Total'] = total;
$.ajax({
url: 'https://www.google.com',
type: "POST",
//Datatype causes it to automatically become json and will expect json back
//return json back from php through json_encode($myArray);
dataType: "json",
data: cart,
success: function() {
alert('Message Sent');
}
});
in short: You used the wrong braces :)
I just changed it to an easier way of managing objects. The problem with your previous object was that it was built wrong. Should be something like:
var cart = {"Item":item_name,"Quantity": quantity,"Amount":amount,"Total":total};
I found a solution to my problem and I combined some your responses to find the answer.
$('#miniform').on('submit',function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
var cart = {};
cart.item_name = miniform.elements['itemId'].value;
cart.quantity = miniform.elements['quantityId'].value;
cart.amount = miniform.elements['amountId'].value;
cart.total = cart.amount * cart.quantity;
var jsonString = JSON.stringify(cart);
$.ajax({
url: url,
type: type,
data:{data:jsonString},
success: function(){
console.log('Email Sent');
},
error: function(error){
throw new Error('Did not work');
}
});
return false;
});
I try to pass many values to Action in MVC but, user is always null.
var form = $('form');
$.ajax({
type: "POST",
url: '#Url.Content("~/User/UpdateUser")',
data: { user: form.serialize(), NameOfCare: care },
success: function (result) {
if (result == "Ok") {
document.location.href = '#Url.Content("~/User/Index")';
}
}
});
how to pass form with many values in Ajax ?
First of all, you have to use #Url.Action instead #Url.Content because you have to send your form data to a controller in order to process data.
.serialize method encode a set of form elements as a string for submission.
You should use this: data:form.serialize() + "&NameOfCare="+care.
On server-side your method should looks like this:
public ActionResult(UserViewModel user,string NameOfCare){
}
user object will be filled with your data , using Model Binding
you are sending a serialized object while it's actually a string. try below example. The action will de-serialize the string automatically.
function load() {
var dataT = $("#searchform").serialize();
var urlx = "#Url.Action("SR15Fetch", "SR15", new { area = "SALES" })";
debugger;
$.ajax({
type: "GET",
url: urlx,
data: dataT,
cache: false,
success: HandellerOnSuccess,
error: HandellerOnFailer,
beforeSend: Ajax_beforeSend(),
complete: Ajax_Complete(),
});
}
i am using jquery to send json data that contains array of elements like this
$('#brand_category').click(function(event){
category = $("input:checkbox[name=category]:checked").map(function() {
return this.value;
}).get();
brand = $("input[type='radio']:checked").map(function() {
return this.value;
}).get();
parameter.push({
brand : brand,
category: category
});
var json = JSON.stringify(parameter)
$.ajax({
type: 'post',
url: "{% url 'seller_details' %}",
data: {'parameter[]' : json , csrfmiddlewaretoken:'{{csrf_token}}'},
success: function(data){
},
error:function (response, error){
}
});
and in the view i am collecting the data like this
brand_category = self.request.POST.get('parameter[]')
print brand_category
this prints the data as this
[{"brand":["spykar"],"category":["Women Clothing","Dresses"]},{"brand":["Madame"],"category":["Women Clothing","Dresses"]}]
then i tried to loop through the json like this
for list in list_data:
brand = list_data['brand']
print brand
categories = list_data['category']
print categories
but i am getting the error as this
list indices must be integers, not str
how can i loop through the json data to get the list of brands and categories?
Your outer loop is a list, and then you loop through each dictionary in the list. Also, you have to convert the string to a python object.
import json
brand_category = self.request.POST.get('parameter[]')
Lbrand_category = json.loads(brand_category)
for D in Lbrand_category:
brand,categories = D['brand'],D['category']
Note: if you want only the brand string, without the list, use:
brand,categories = D['brand'][0],D['category']
I recommend you this AJAX Request (Its more clear):
$('#brand_category').click( sendAjax );
function sendAjax()
{
var category = $("input:checkbox[name='category']:checked").val();
var brand = $("input[type='radio']:checked").val();
var data = { "category" : category, "brand" : brand, "csrfmiddlewaretoken" : '{{csrf_token}}' }
$.ajax({
type: 'post',
url: "{% url 'seller_details' %}",
data: data,
success: function(data)
{
//console.log(data) // Print the response of Django or see this in "Network" request, F12 Chrome
},
error:function (response, error)
{
}
});
}
View:
category = request.POST['category']
print category
brand = request.POST['brand']
print brand
List data of brands in JavaScript:
var data = {} //This is a empty object named data
data.brans = [];
and then you need create a for select all brands
for ("list of brands"){
brand_name = logic
data.brands.push(brand_name)
} //This is only a idea
I am currently trying to solve a problem.
I have several forms on a single page which get sent to the backend asynchronously via ajax.
Now some of them need to have a fileupload which doesnt break the process, so it alsoneeds to be handled asynchronously.
I am trying to figure it out like that :
// Allgemein Submit
$allgSubmit.click(function(){
event.preventDefault();
var gehrKundennummer = $('#gehrKundennummer').val();
var kundenklasse = $("input[type='radio'][name='kundenklasse']:checked").val();
var lkw12t = $('#lkw12t').val();
var lkw3t = $('#lkw3t').val();
var autobus = $('#autobus').val();
var firmenname1 = $('#firmenname1').val();
var firmenname2 = $('#firmenname2').val();
var uidnummer = $('#uidnummer').val();
var peselregon = $('#peselregon').val();
var firmenart = $('#firmenart option:selected').val();
var strasse = $('#strasse').val();
var ort = $('#ort').val();
var plz = $('#plz').val();
var land = $('#land').val();
var fd = new FormData();
var file = fd.append('file', $('#allg_firmen_dok').get(0).files[0]);
var allgArray = {
'gehrKundennummer':gehrKundennummer,
'kundenklasse':kundenklasse,
'lkw12t':lkw12t,
'lkw3t':lkw3t,
'autobus':autobus,
'firmenname1':firmenname1,
'firmenname2':firmenname2,
'uidnummer':uidnummer,
'peselregon':peselregon,
'firmenart':firmenart,
'strasse':strasse,
'ort':ort,
'plz':plz,
'land':land,
'file':file
};
//var data = new FormData();
//jQuery.each(jQuery('#allg_firmen_dok')[0].files, function(i, file) {
// data.append('file-'+i, file);
//});
console.log(allgArray);
$.ajax({
url: "PATHTOFILE/logic/logic_update_client_allg.php",
type: "POST",
data: allgArray,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function(allgArray){
alert(allgArray);
var allgSave = $('#allgSave');
allgSave.text('Aktualisieren erfolgreich!');
allgSave.toggle();
},
error: function(){
var allgSave = $('#allgSave');
allgSave.text('Aktualisieren fehlgeschlagen!');
allgSave.toggle();
}
});
});
The console log of the array returns all values correctly except the one for "file"
it says undefined.
I don't know how to deal with it, are there any requirements that im missing?
Thanks for any kind of help
EDIT
var file = fd.append('file', $('#allg_firmen_dok').get(0).files[0]);
returns undefined
I think the variable fd = new FormData() is an Object and it has attribute "file". So it cannot pass the attribute "file" to another Object "allgArray"
You need to check about it before you call function
$.ajax({
url: "PATHTOFILE/logic/logic_update_client_allg.php",
type: "POST",
data: allgArray,
Think about the data you send! It maybe another instance to get data from "file" of "fd". Hope it help you! ^^
Btw, I used AJAX to send file last time
$(document).ready(function (e) {
$("#Form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "uploader.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
console.log(data);
}
});
}));
});
add headers: { "Content-Type": "multipart/form-data" } in ajax option
I have a javascript function
function TxEncrypt(event)
{ //perform encryption of token data, then submit the form like normal
//obtain public key and initial JSEncrypt object
var txPubKey = txJ$(".zwitch_encryptionkey").val();
var txEncrypter = new JSEncrypt();
txEncrypter.setPublicKey(txPubKey);
//get Data and encrypt it
var txData = '{}';
var txCryptData = '';
if(txJ$(".zwitch_data").length > 1)
{ //if there are more than one element with this class, convert it to json string
txData = txJ$(".zwitch_data").serializeObject();
txCryptData = txEncrypter.encrypt(JSON.stringify(txData));
}
else
{ //else, just encrypt the value
txData = txJ$(".zwitch_data").val();
txCryptData = txEncrypter.encrypt(txData);
}
dataString = txCryptData; // array?
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
});
alert(dataString);
}
I could get the value of dataString.But the ajax parrt is not working.I have added the jquery library.But doesnt seem to work
What's the error you are getting?
I think this should be:
$.ajax({
type: "POST",
url: "tokenize.php", //removed the dot
.....