i have two forms on a page. 1st is shown and 2nd one is hidden.
1st form shows list of users and their emails in grid and pagination. when i select a multiple users from grid then a div shows up on the right side of the gird. which will be used to send email to selected user.
2nd form that shows up will input email subjects from users and then pass these whole data to django views.
i have user this ajax code to send whole data to the views function.
$("#_send").click(function(){
var frm = $('#messageform');
frm.submit(function () {
var selectedID = [];
$(':checkbox[name="selectedvalues[]"]:checked').each(function(){
selectedID.push($(this).data("email"));
});
$.ajax({
type: 'POST',
url: '/sendemail/',
processData: true,
data: {'frm':frm.serialize(),
'selectedID': selectedID},
success: function (data) {
alert(data);
},
error: function(data) {
alert("error");
}
});
return false;
});
});
and in django views i am catching like this;
def Send_Message(request):
checked_items = request.POST.getlist('selectedID[]')
Msg_Content = str(request.POST.get('content'))
frm = request.POST.get('frm')
print checked_items
print frm
print Msg_Content
it outputs like this;
abc#gmail.com,abc123#cogilent.comm
csrfmiddlewaretoken=dP7VkSQdWx0fXuX0kJC46arv6HFElvgz&subject=Hi+This+is+testing+message&content=ddddd
but i want these data seperately, message content and message subject.
When you serialize the data; you should be able to do request.POST.get('subject') etc
Related
Sorry I am a beginner with jQuery and Javascript. I want to be able to get the results into my modal from any form on the page that has class ajax. My code is below but not working correctly. Currently it opens the post result in a new page and not in the modal. Can anyone shed any light on my code?
Many thanks
$(document).ready(function() {
$('.ajax').click(function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('name').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(value);
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
This probably happens because your browser submits the form by default. It doesnt know youre doing AJAX stuff. To prevent this, use preventDefault().
In addition to that, jQuery has a built in function for serializing (1 and 2) form data.
$(document).ready(function() {
$('form.ajax').click(function(event) {
event.preventDefault(); // prevents opening the form action url
var $form = $(this),
url = $form.attr('action'),
type = $form.attr('method'),
data = $form.serialize();
// console.log(value); // value doesnt exist outside of your loop btw
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
Also, its not quite clear if you bind the click event handler to a form or a button, I guess the first one. You should change the handler to the following:
$(document).ready(function() {
$('form.ajax').on('submit', function(event) {
Trying to create a simple crud operation using edit and delete. Currently on edit functionality.
Functionality works like this:
1) user clicks on edit icon, bootstrap modal opens up with form information that is fetched from ajax request containing users id. Forms value fields are auto populated based on fetched ajax request.
2) User can edit the auto populating form fields editing the users information and a separate ajax request goes out that edits the users record.
Problem:
This all works how I wanted to but I noticed a small bug that I'm stuck on to where when I go edit a users information, hit send and then close out of the modal to open and edit another users information and hit send again, the previous forms data is added onto the data I'm currently editing and I don't want that. I just want to open up the modal and edit and send the current users data that I'm on.
In addition, I also noticed If I keep trying to edit multiple users information, multiple ajax requests are sent each time I try and edit another record. I tried looking up my problem and I think it's because of my events bubbling up in which I tried e.stopPropagation; and return false; and it did nothing to solve my problem. I feel like I'm close but there is something that I'm missing.
If you need my HTML code as well I'll be happy to show that.
Here is my code:
$(document).on('click', 'i.fas.fa-edit', function(userId){
emailField.value = 'Please wait...!';
fullnameField.value = 'Please wait...!';
areaField.value = 'Please wait...!';
personField.value = 'Please wait...!';
// By Default
adminAccess.checked = false;
personField.style.display = 'block';
adminAccess.addEventListener('click', function(){
if(adminAccess.checked == true) {
areaField.style.display = "none";
} else {
personField.style.display = "block";
}
});
var usersId = {
usersId: userId.target.id
}
// Select user data
$.ajax({
method: 'POST',
url: 'select-user-action.php',
data: usersId,
success: function(data){
var parseData = JSON.parse(data);
parseData.forEach(function(element){
emailField.value = element.email;
fullnameField.value = element.name;
areaField.value = element.areaField;
personField.value = element.personField;
});
}
});
});
$('#editModal').on('show.bs.modal', function () {
submitForm.addEventListener('submit', function(e){
// prevent form from submitting
e.preventDefault();
var editData = {
"email": emailField.value,
"fullName": fullnameField.value,
"areaField": areaField.value,
"personField": personField.value
};
// Previous data is being added onto current edited data.. This is what I'm stuck on.
console.log(editData);
// $.ajax({
// method: 'POST',
// url: 'edit-user-action.php',
// data: editData,
// success: function(data){
// console.log(data);
// }
// });
// this didnt work
return false;
});
});
I am trying to implement HTML5 history with an AJAX form.
The form contains some radio buttons and dropdowns. Upon changing any of these inputs, the form is automatically submitted and results are returned via AJAX.
Now having implemented history, the URL gets updated, so it looks like this for example:
/currencies?type=usd&year=2015
Here is how I perform the AJAX and update the URL:
$('#currency-form input, #currency-form select').change(function() {
var form = $('#currency-form');
var url = form.attr('action');
var data = form.serialize();
$.ajax({
url: url,
type: 'get',
dataType: 'json',
data: data,
success: function(response) {
// update the page content
processResponse(response.data);
// update the page url
window.history.pushState({}, response.meta_title, response.new_url);
}
});
});
To detect the back button, I have done the following:
$(window).on('popstate', function(event) {
var state = event.originalEvent.state;
if (state !== null) {
console.log(state);
}
});
There is one thing I am struggling with. Upon pressing the back button, it should pre-select the previous form values and submit the form again.
Does anybody know how I can achieve this?
1- HTML5 Tag Method:
Use Autocomplete tag for the form, HTML5, but can't be sure about all browsers' compatibility.
<form action="" method="post" autocomplete="on">
Check this post
2- jQuery Method:
See this example:
Using jQuery plugin for cookies.
To set a cookie; use something like this example:
(function(){
// get elements values
var checkbox1 = $('#checkbox1').val();
var radio1 = $('input[id="radio1"]:checked').val();
var textbox1 = $("#textbox1").val()
//save elements values into cookies
$.cookie("radio1", checkbox1);
$.cookie("checkbox1", radio1);
$.cookie("textbox1", textbox1);
});
Then to load the values upon your desired event:
(function (){
//read value from cookie.
var radio1= $.cookie("radio1");
var checkbox1= $.cookie("checkbox1");
var textbox1= $.cookie("textbox1");
$('#radio1').prop('checked', radio1);
$('#checkbox1').prop('checked', checkbox1);
$('#textbox1').val(textbox1);
// Etc...
});
When submission or on live editing; try to save the entry in cookies and when you back to the form...load that values into fields.
3- Populate from JSON Data:
Reference:
// reset form values from json object
$.each(data, function(name, val){
var $el = $('[name="'+name+'"]'),
type = $el.attr('type');
switch(type){
case 'checkbox':
$el.attr('checked', 'checked');
break;
case 'radio':
$el.filter('[value="'+val+'"]').attr('checked', 'checked');
break;
default:
$el.val(val);
}
});
The way to accomplish this is to push the new input field values in to state as follows:
var state = {
field1: $('#input1').val(),
field2: $('#input2').val()
};
window.history.pushState(state, response.meta_title, response.new_url);
Then when you detect back button event, do the following to repopulate the input fields:
$('#input1').val(state.field1);
$('#input2').val(state.field2);
So, I have a view with a chosen search box, a button "Add" (btn-default) and a button "Edit" (breadcrumb) . When I click the Add button, the ajax sent me a table with the values (in this case, funcionaries) selected in the chosen text box.
I want that, when I click on the Edit button, send the chosen values (can be one, or hundreds of values) to another controller to return another view.
Don't want to use ajax because I want to use a new view on totally.
On the controller side, when I send the data with javascript, I always get null. Why?
View
<script>
$(document).ready(function () {
$(".btn-default").on("click", function (event, params) {
$.ajax({
url: '#Url.Action("EditarPonderacoesEspecial", "Sorteios")',
type: 'POST',
dataType: 'html',
cache: false,
traditional: true,
data: { bdoIds: $(".chosen-select").val() },
success: function (responseText, textStatus, XMLHttpRequest) {
$("#MyDiv").empty();
$("#MyDiv").html(responseText);
},
error: function () { }
})
});
$(".breadcrumb").on("click",function (event, params) {
bdoIds = $(".chosen-select").val();
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", bdoIds);
});
});
Controller
public ActionResult EditarPonderacoesEspecialSecond(string[] bdoIds)
{
//do whatever I want with the bdoIds
return View();
}
I had tried many different ways, but the controller always receive the parameter as null. What I am doing wrong? Thanks!
Your controller action is expecting an array of strings.
Assuming .chosen-select is a select list as that part is missing from the question.
First read the selected values into an object as follows:
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
Then send them as follows:
$(".breadcrumb").on("click",function (event, params) {
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", { bdoIds: selectedValues });
});
Declare Global array like
var SelectedArray = new Array();
When you select multiple selectlist item each time push value in SelectedArray
$('#ChosenId').chosen().change(function () {
SelectedArray = $('#ChosenId').chosen().val();
});
Then your ajax data is like
data: { bdoIds: SelectedArray },
i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.