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;
});
});
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) {
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);
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
I have been trying to solve a simple but, for me, really hard problem.
I have a form and I need to add data from the form to a database, but with form validation. For validation I use the parsley plugin and for some input fields I use select2 plugin.
I try to add form in this way (Comments is in code):
//try to see is zemljiste or vrsta_rada = null to do not add data to database
var zemljiste = $("#parcele").select2("data");
var vrsta_rada = $("#vrsta_rada").select2("data");
//Now when I click on #dodaj I need to chech is zemljiste or vrsta_rada == null to do not start function for adding data but DONT work
$("#dodaj").click(function () {
if (zemljiste == null || vrsta_rada == null) {
alert('PLEASE fill the fields');
} else {
//HERE if zemljiste and vrsta_rada != null start validation and this also dont work
$('#myForm').parsley().subscribe('parsley:form:validate', function (formInstance) {
formInstance.submitEvent.preventDefault(); //stops normal form submit
if (formInstance.isValid() == true) { // check if form valid or not
zemljiste = $("#parcele").select2("data").naziv;
id_parcele = $("#parcele").select2("data").id;
vrsta_rada = $("#vrsta_rada").select2("data").text;
//code for ajax event here
//Here is ajax and when I fill all fields I add data to database but here success and error into ajax dont work???
$.ajax({
url: "insertAkt.php",
type: "POST",
async: true,
data: {
naziv: $("#naziv").val(),
parcele: zemljiste,
vrsta_rada: vrsta_rada,
opis: $("#opis").val(),
pocetak: $("#pocetak").val(),
zavrsetak: $("#zavrsetak").val(),
status: $("#status").val(),
id_parcele: id_parcele,
}, //your form data to post goes here as a json object
dataType: "json",
success: function (data) {
//SO if success I add data but this code below dont work also in error dont work
$('#myModal').modal('hide');
drawVisualization();
console.log('YESSSSSSS');
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
});
}
});
With this, I have a few problems...
1. When submit code, the page refreshes and I don't want to do that.
2.When I fill in all the fields, I add data to the database but also add all the previous attempts with incorrect information. Why?
3. Why can I not see what return my success and error into .ajax in console.log ???
Look the pictures:
I am trying to get everyone's total clicks on a button. I was thinking about POST function with ajax but it would make lots of PHP request on the server. I want to do something like that:
<script>
document.getElementById('buttonToClick').onclick = function() {
var totalClicks = ???; // get total clicks number from the server somehow and
// assign it to var totalClicks;
document.getElementById("totalClicks").innerHTML = totalClicks;
??? = ??? + 1; // add 1 to total clicks number and save it to server.
};
</script>
<input id="buttonToClick" type="submit" name="button" value="enter"/>
<a>The button is clicked <a id="totalClicks"></a> times!</a>
Is it possible to make this with Javascript?
You would have to use AJAX to POST the data to the server, since you are using jQuery you can use the $.ajax function.
As an example:
$(document).on("click", "#buttonToClick", function() {
uploadClickCount();
});
function uploadClickCount()
{
var userId = $("#UserId").val(); // Get the user id first
var totalClicks = $("#totalClicks").val();
$.ajax({
url: 'YourWebsite/ClickCounter',
type: "POST",
data: { user: userId, clickCount: totalClicks },
success: function() { }
error: function() { alert('Unable to connect to the server'); }
});
}
An alternative to save on calls to the server would be to attempt to send the total clicks when the user leaves the page or closes the page using the window.unload method, however this may be unreliable.
You could also look at storing the click count in HTML 5 local storage and then upload it when the user returns/once the DOM is ready, i.e.. $(document).ready(function() { });
It would also be best practice to store when the user last attempted to contact the server, you can then use this to invoke the AJAX call after a 10 second delay which would prevent mass requests server side.