I have a form with id: formC, on submit i call ajax:
var datiForm = new FormData();
var pos = [];
var i = 0;
posizioni.each(function () {
if($(this).find("input[type=checkbox]").is(":checked")){
pos[i] = $(this).find("input[type=checkbox]").data("id");
i++;
}
});
datiForm.append("nome",nome.val());
datiForm.append("cognome",cognome.val());
datiForm.append("email",email.val());
datiForm.append("telefono",telefono.val());
datiForm.append("dataNascita",dataNascita.val());
datiForm.append("titolo",titolo.val());
datiForm.append("ruolo",ruolo.find(":selected").data("ruolo"));
datiForm.append("sede",sede.find(":selected").data("sede"));
datiForm.append("posizione",pos);
datiForm.append("cvFile",$("#cvFile")[0].files[0]);
$.ajax({
type: "POST",
data: {datiForm: datiForm},
url: "saveCandidate.php",
processData: false,
contentType: false,
success: function (data) {
console.log(data);
},
error: function (data) {
var position = data;
}
});
I have a problem, on server $datiForm = $_POST["datiForm"]; is null why?
Moreover i have input file where i can select file pdf. I put it in FormData:
datiForm.append("cvFile",$("#cvFile")[0].files[0]);
Now on server i want to take file from $datiForm and save it into mysql as Blob is possible?
You specified the data field incorrectly, it should be just the form data object
data: datiForm,
also the way you add posizione is not going to work, each entry in yrh array has to be added individually
posizioni.each(function () {
if($(this).find("input[type=checkbox]").is(":checked")){
datiForm.append("posizione["+i+"]", $(this).find("input[type=checkbox]").data("id"));
i++;
}
});
Now on server i want to take file from $datiForm and save it into mysql as Blob is possible?
Yes
You'll need to specify the 'contentType' attribute to 'multipart/form-data' in order to upload files.
Related
I know, similar questions had been asked before.
All questions I found concerns upload within a form and need a submit button. This I don't want. I want upload to start after file selection is made (I'm aware of security risks).
Why is the contend of the file dictionary not send?
The button itself is created by JS:
downLoadBtn = document.createElement('INPUT');
downLoadBtn.id = 'downloadBtn';
downLoadBtn.type = 'file';
downLoadBtn.onchange = function(){upload()}
function upload(){
file = document.getElementById('downloadBtn')
console.log(file['files']['0'])
$.ajax({
type: "POST",
url: '/upload',
dataType : 'json',
data: JSON.file,
success: function (response){
console.log(response);
}
});
}
python:
#app.route('/upload', methods = ['POST'])
def upload():
if request.method == 'POST':
data = request.files
print(data)
return jsonify(data)
What I'm doing wrong?
You pass JSON.file as the data parameter which is not defined in the code you posted, it should be the file tat was selected.
Since your server side code expects multipart from data, you'll have to use a FormData object.
function upload(){
file = document.getElementById('downloadBtn')
console.log(file['files']['0'])
var fd = new FormData();
fd.append('file', file['files']['0']);
$.ajax({
type: "POST",
url: '/upload',
dataType : 'json',
data: fd,
contentType: false,
processData: false,
success: function (response){
console.log(response);
}
});
}
I've a view that recives parameters from the frontend via AJAX.
I've passing AJAX parameters in a maner, but this time my way didn't work.
I've asked a friend for help, and he send me another way of sending AJAX data. To my untrained eyes they both work equal. So I don't know why mine does not work:
Why?
My friend's AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/?d_name=" + val_d + "&p_name=" + val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
</script>
My AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
d_name: val_d,
p_name: val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
});
</script>
View
def get_district(request):
d_name = request.GET.get("d_name")
p_name = request.GET.get("p_name")
data = Peru.objects.filter(departamento=d_name, provincia=p_name).values_list("distrito", flat=True)
# data = Peru.objects.filter(provincia=p_name).values_list("provincia", flat=True)
return render(request, "accounts/district_dropdown.html", {
"districts": set(list(data))
})
You need to pass the the d_name and p_name properties in a separate object specified by data. Currently you're passing them as top level properties of the ajax settings object, which won't have any effect.
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
data: { // Pass parameters in separate object
d_name: val_d,
p_name: val_p
},
}).done(function (result) {
$("#id_shipping_district").html(result);
});
The data object is converted into a query string and appended to the URL.
In your friend's case, they are building up the query string manually when they create the URL - hence their version works.
Hey guys I am using vuejs and ajax to send formData and return a json response. There's a json response comes though however I cant assign it to the vue data object. Any ideas as to why? Heres my method. I know the function is firing as it hits the other page and returns json data in the console. Message, nameExists, and error wont assign even though all our in the vue data property and is spelled correctly.
addTemplate: function() {
this.sub = true;
this.itemName = this.itemName.trim();
var addTemplateForm = document.getElementById("addTemplateForm");
var fd = new FormData(addTemplateForm);
if (this.validItemName == true /* etc...*/) {
$.ajax({
url:'addTemplateBackend.php',
type:'POST',
dataType: 'json',
data: fd,
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
error: function(data){
this.message = data.message;
alert('error');
},
success: function(data){
alert('success');
this.error = data.error;
this.message = data.message;
console.log(data);
this.nameExists = data.nameExists;
if(data.success == true){
$('#successModal').modal('show');
}
}
});
}
}
You need to either bind this:
success: function (data) {
this.message = data.message;
}.bind(this)
or use ES6 "fat arrow" syntax:
success: data => {
this.message = data.message;
}
See How does the "this" keyword work?.
I have this ajax code:
return $.ajax({
type: "POST",
url: "somefile.php",
cache:false,
data: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
dataType:"json",
success: function(data){
alert("success");
}
This works fine, but I need to pass the data parameter dynamically. For now I need the above data parameter content and a single string.
How do I pass this dynamically? / How do I store it in a variable and pass it to the "data:" field?
{ "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() }
I tried JSON.stringify I I couldn't get it to work probably due to the data being an array.
The year and genre arrays are coming directly from the jquery drop down menu. It is selected like by it's #id like so "$("#yearFilter")". This is the select form element.
<select multiple="multiple" name="yearFilter[]" class="filterChange" id="yearFilter">
What I need at the base level is:
var someData = "";
if(...){
someData = { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() };
}
else if(...){
someData = "sampleString";
}
And in ajax call:
...
data: someData,
...
I think I have an idea what you want but post has been overly complicated by extraneous issues like json stringify . Here's a function that could be used in several places eleswhere in your code to make one type of AJAX call or another.
You would then perhaps have several buttons and call the function within handlers for each type of button and change the argument passed to function
doAjax('someval');/* use in button 1*/
doAjax('someOtherval');/* use in button 2*/
function doAjax(arg) {
var someData = "";
if (arg == 'someval') {
someData = {
"yfilter": $("#yearFilter").val(),
"gfilter": $("#genreFilter").val()
};
} else {
someData = "sampleString";
}
$.ajax({
type: "POST",
url: "somefile.php",
cache: false,
data: someData,
dataType: "json",
success: function(data) {
if (arg == 'someval') {
alert("success 1");
} else {
alert("success 2");
}
}
})
}
Hope I've understood what you're asking for.
You could do something like this:
var parameters = {};
if (...) {
parameters = $("#yearFilter").serializeArray();
}
if () {
parameters = $("#genreFilter").serializeArray();
}
and then replace the line:
parameters: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
with:
data: parameters,
JSON type should be best option for dynamically data. push whatever data you wish to inside json like shown below, Hence create your json dynamically and send as ajax data.
var employees = {
accounting: [],
dept: "HR"
};
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
$.ajax({
url: POSTURL,
type: 'POST',
dataType: 'json',
data : employees,
contentType: 'application/json; charset=utf-8',
success: function (results)
{
},
error: function (results)
{
jQuery.error(String.format("Status Code: {0}, ", results.status, results.statusText));
}
});
Try it:
someData = JSON.stringify({ yfilter: $("#yearFilter").val(), gfilter: $("#genreFilter").val() });
It will work.
I'm trying to make my inline edit to be dynamic so it will just depend on some data- attributes from my markup so here's the code for now:
$(".inline-edit").editable(
function(value, settings) {
var editableField = $(this);
$.ajax({
type: 'PUT',
url: editableField.attr('data-href'),
dataType: 'html',
success: function(html) {
editableField.parents('.replaceable').replaceWith(html);
},
data: { 'regression_test_environment[name]' : value }
});
return(value);
},
{
event: 'click',
width: '80%',
height: '20',
submit : 'OK'
}
)
i want the name in regression_test_environment[name] to be editableField.attr('data-column-name') but it always fails in compiling because it keeps taking the key as a string. I tried making a variable after the editable field variable assignment and building the string as a different variable but it doesn't want to evaluate the key as a function.
Is there a way to do this? or am i stuck in creating a separate .editable call for each of my editable fields?
You may try like this:
var name = editableField.data('column-name');
var values = { };
values['regression_test_environment[' + name + ']'] = value;
$.ajax({
type: 'PUT',
url: editableField.data('href'),
dataType: 'html',
data: values,
success: function(html) {
editableField.parents('.replaceable').replaceWith(html);
}
});
Better, less confusing answer:
var data = {};
data[thisField] = $(this).text();
$.ajax({
data: data
});
Best is to pass dynamic values by serializing it :
var data = $('#formid').serialize(); // serialize all the data in the form
$.ajax({
url: 'test.php', // php script to retern json encoded string
data: data, // serialized data to send on server
...
});