Reputation: 818
I have below ajax function, which is working fine when I input values for all the fields, but it doesn't work when I do not supply value to any of the three fields (pname,psection, and rinput-json)
<script type="text/javascript">
function saveprof() {
$('.spinner').show();
$.ajax({
type: "POST",
url: "saveprof",
enctype: 'multipart/form-data',
async: true,
data: {
'pname_Aj': $('#pname').val(),
'psection_Aj': $('#psection').val(),
'rinput_Aj' : JSON.stringify(fun()),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: function (data, textStatus, jqXHR) {
$('#message').html(data);
window.location.href = 'myprofile';
window.location('myprofile');
$('.spinner').fadeOut();
}
});
}
</script>
How can I make it work even if the values for any of the fields are not supplied ?
For your information, this call is made to the Django view which does save the fields in the database.
Upvotes: 0
Views: 40
Reputation: 1
If the parameters need to be absent when no value
function saveprof() {
$('.spinner').show();
$.ajax({
type: "POST",
url: "saveprof",
enctype: 'multipart/form-data',
async: true,
data : function() {
var data = {};
var addToData = function(name, val) {
if(val) {
data[name] = val;
}
}
addToData('pname_Aj', $('#pname').val());
addToData('psection_Aj', $('#psection').val());
addToData('rinput_Aj', JSON.stringify(fun()));
addToData('csrfmiddlewaretoken', $("input[name=csrfmiddlewaretoken]").val());
return data;
}(),
success: function (data, textStatus, jqXHR) {
$('#message').html(data);
window.location.href = 'myprofile';
window.location('myprofile');
$('.spinner').fadeOut();
}
});
}
Upvotes: 0
Reputation: 105
It sounds like those values are optional?
If so, perhaps you can check to see if those values exist, and if not, just submit an empty string:
data: {
'pname_Aj': ( $('#pname').val() || ""),
'psection_Aj': ( $('#psection').val() || ""),
'rinput_Aj' : (JSON.stringify(fun()) || ""),
'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val()
},
So if the user has entered values in those sections (and fun()
returns something that can be stringified, those variables get submitted. Otherwise, an empty string gets submitted.
Upvotes: 1