So, I'm trying to make a row containing a delete button to .hide after pressing delete.
The problem is.. The delete button submits a form, I can't pre-define my button class/ID because it's beeing echo'd multiple times (php script reads a dir, then puts all files in a table)
this is the current script, It does post the form in the background, But it doesn't hide the element, I tried some stuff myself but the script then ended up hiding all the buttons on the page or it won't work at all..
The button beeing echo'd:
echo "<input type='submit' value='delete' name='submit'>";
The Script behind it:
$("#delform").submit(function() {
var url = "../../setdel.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#delform").serialize(), // serializes the form's elements.
success: function(data)
{
// location.reload(); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Catch the button's onclick instead of catching the submission. Example:
echo "<input type='submit' value='delete' name='delete' class='trigger_delete'>";
// ^^ don't name your buttons as submit
// it will conflict to .submit() method
The on JS:
$('.trigger_delete').on('click', function(e){
e.preventDefault(); // prevent triggering submit
var url = "../../setdel.php";
$.ajax({
type: 'POST',
url: url,
data: $("#delform").serialize(),
success: function(response) {
console.log(response);
$(e.target).closest('tr').hide(); // or .fadeOut();
}(e) // <--- this one
});
});
Related
I am building an application in Django that creates rubrics to grades assignments. Each rubric item is editable and on submission of the form, the page is checking if a rubric item has been edited and if it has editing it in the database. Then once all those have been updated, it will submit the checked checkboxes as the grade. So the form action is to submit the grade, and in the jquery I have an event listener checking for when the submit button is clicked that will make an ajax call to update the rubric entries. The rubric entries arent being edited before the form goes to its action. Like its going to the form action too quickly the jquery doesnt have time to finish.
I've tried doing event.preventDefault to prefent the form from going to the action and then submiting the form after the loop that edits all the rubric entries which should give it time to finish. I've also tried calling this function in an onsubmit instead of an onclick because I heard that the onsubmit executes before the form action does. But here's the thing. The code works perfectly on my mac, but does not work on 2 other PCs. Every fix I've tried still works on my mac but still doesn't work on the PCs.
When I change the form submit button to type 'button' which means the form never goes to its action, or after doing event.preventDefault never submit the form, the edit function works properly so I've concluded that the problem is that the form action is disrupting the other function but I just cant figure out why when I've taken measures to try to stop it, and why only on PC?
<form action="{% view to upload grade %}" method="post" id="upload_form">
<ol id="form_list">...</ol>
<button type="submit" id="submit_grade">Submit Grade</button>
</form>
$(document).on('click', "#submit_grade", function(event){
event.preventDefault();
$(".rubricEntry").each(function(){
var crit_pk = $(this).attr('id');
var description = $(this).find(".rubricField-description").text();
var points = parseInt($(this).find(".rubricField-points").text());
console.log("points:" + points +" description: " + description);
if(description === textPlaceholder || isEmptyorSpaces(description) ){
console.log("empty or description");
$.ajax({
type: "POST",
url: '/upload/delete/'+ a_canvasId+'/' + crit_pk +'/',
data:{ csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
},
dataType: 'html',
success: function() {
}
});
}
else{
console.log("tried to edit");
$.ajax({
type: "POST",
url: '/upload/edit/'+ a_canvasId+'/' + crit_pk + '/',
data:{ csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
point_value: points,
description: description
},
dataType: 'html',
success: function() {
console.log("success");
}
});
}
});
document.getElementById("upload_form").submit();
});
Fixed by adding async: false, to the ajax call.
I am adding a text area on click of a particular div. It has <form> with textarea. I want to send the jquery variable to my php page when this submit button is pressed. How can this be achievable. I am confused alot with this . Being new to jquery dizzes me for now. Here is my code,
`
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'><textarea cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' name= 'submit_notes' type='submit' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>`
Your code works fine in the fiddle I created here -> https://jsfiddle.net/xe2Lhkpc/
use the name of the inputs as key of $_POST array to get their values.
if(isset($_POST['submitValue'])) { $qid = $_POST['submitValue']; }
if(isset($_POST['notes'])) { $notes = $_POST['notes']; }
You should send your data after form submitted, something like this
:
$(".comment_form form").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
you can assign event after insert your form.
// handling with the promise
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'></form><br></div>").promise().done(function () {
// your ajax call
});;
This is my Fiddle code:
$("form.signupform").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
$(form).children(".signupresult").html(data.signupresult);
$(form).children(".signupresult").css("opacity", "1");
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form class="signupform" method="post" action="admin/signupinsert.php">
<p class="signupresult"></p>
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
Signupinsert.php page code:
// Code to insert data into Database
$signupresult = "Some value here";
$response = new \stdClass();
$response->signupresult = $signupresult;
header('Content-Type: application/json');
print json_encode($response);
Expected Result:
When user clicks on submit form button, the code runs in background. And submits the form without reloading the page.
And the signupinsert.php page return some text, and its text display on a paragraph with class signupresult.
And the form can be submitted unlimited times, without reloading the page.
Problem:
The form only gets submitted once. If I try to submit it twice, "Nothing Happens" (No values inserted into database, no value returned in paragraph with class signupresult.
Where is the problem?
You have to tell your request that you expect JSON as return. Else data.signupresult doesn't make sense; data is seen as a string.
I always use $.ajax, never $.post; I find it easier to add options.
$.ajax({
url: $(this).attr("action"),
dataType: 'JSON',
type: 'post',
data: $(this).serialize(),
success: function(data) {
...
}
})
I have a script that sends my form via php-ajax. It does return success but what I need it to do when it has been successful is clear all the form data and close the div and load another one. I have tried many different ways to clear form and close div but they just seem to stop it working totally. The id of the div to close is '5box' The working script that i need to add these to is :
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevent default submission of the form after clicking on the submit button.
return false;
});
});
Any ideas would be appreciated
To clear the form you can call the reset() method of the underlying Element. I'm not sure what you mean by 'close the div', but you can call hide() to make it disappear. Try this:
success: function(result) {
if (result == 'success') {
$('.output_message').text('Message Sent!');
form[0].reset();
$('#5box').hide();
} else {
$('.output_message').text('Error Sending email!');
}
}
Also note that it would be much better practice to return JSON from the AJAX call. You can then have a boolean flag to show the state of the request.
Update
<button name ='send' value="Send" type='submit' class='btn btn-primary'>Finish</button>
Given that is the code of your button there is another issue - you're not preventing the form from being submit, hence the AJAX request is cancelled. To do this, hook to the submit event of the form instead of the click of the button. From there you can call e.preventDefault() to stop form submission. Try this:
<script>
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result) {
if (result == 'success') {
$('.output_message').text('Message Sent!');
form[0].reset();
$('#5box').hide();
} else {
$('.output_message').text('Error Sending email!');
}
}
});
});
});
</script>
Note I used a generic 'form' selector above. You can change that to a class or id selector on the form as required.
For clearing form fields
$("input[type=text], textarea").val("");
cheers
you can also use Triggers as well
$('#form_id').trigger("reset");
I have a php function that loops thru matches in a database, inside the loop, there is a form that gets returned to the page where the function is called:
while($row=mysql_fetch_array($get_unconfirmed))
{
echo "<form name='confirm_appointment' method='post' class='confirm_appointment'>";
echo "<input type='hidden' name='app_id' value='$appointment_id'>";
echo "<input type='hidden' name='clinic_id' value='$clinic_id'>";
echo "<td><input type='submit' class='update_appointment_button' value='$appointment_id'></td>";
echo "</form>";
}
Then I have jQuery to submit the form:
$( document ).ready(function() {
$(".update_appointment_button").click(function(){
var url = "ajax/update_appointment_status.php";
$.ajax({
type: "POST",
url: url,
data: $(".confirm_appointment").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
But the issue is, the way its set up, no matter what row I push "submit" for - I always get the values from the last row (form).
So I know the issue, I am not telling jQuery to get the values from the form with the button thats pushed. I need to somehow use .this maybe, but just cant seem to figure out the correct syntax.
Any help would be appricated!
You can access its parent form like this
data: $(this).closest(".confirm_appointment").serialize(),
or something like this
data: $this.parent().parent().serialize(),
Another way: replace the button click event by the form submit event.
$(document).ready(function () {
$('.confirm_appointment').submit(function (e) {
e.preventDefault();
var url = "ajax/update_appointment_status.php";
var serialized = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: serialized,
success: function (data) {
alert(data); // show response from the php script.
}
});
});
});
JSFiddle demo