$.post keeps redirecting me - javascript

I have problem with jquery $.post function. I use this function a lot and same function works fine except in one case and I don't understand why it keeps redirecting me after script was executed, here is js code:
var record;
$('.delbtt').on('click', function(e){
e.preventDefault();
var deleteid = $(this).parent().parent().find('#id').text();
record = $(this).parent().parent();
$('#delrecord').empty().val(deleteid);
});
$(document).on('submit', '#delteform', function() {
var formData = $(this).serialize();
$.post('includes/delete.php',formData,processData);
function processData(data){
record.remove();
};
});
HTML:
<!-- Modal -->
<div class="modal fade" id="deleteFormModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form id="deleteform" class="form-horizontal" role="form" action="includes/delete.php" method="POST"> <!-- -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete record</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this person?</p>
</div>
<input type="hidden" id="delrecord" name="delrecord" value="" />
<div class="modal-footer">
<button type="button" class="btn btn-default empty" data-dismiss="modal">Cancel</button>
<button id="delentry" type="submit" class="btn btn-danger">Delete Person</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
I know that function is executed successfully, because if I put alert("Why is this not working?"); after record.remove();, I can see alert and in background code executed, but instead of staying at the same page it redirects me to 'includes/delete.php'. I tried disabling all other $.post functions that I have in my JS, I tried using $('#deleteform').submit(), I tried putting it outside of my main $(document).ready(function() {}); same results... Always same result it redirects me after function completes instead of staying on a page. Does anybody have idea why am I getting this behavior?
php code:
<?php
include('budgetprop/Initialize.php');
Database::GetInstance()->ConnectToServer($errors);
$record = $_POST['delrecord'];
# CONNECT TO DB
if(Database::GetInstance()->ConnectToServer($errors)){
$insertSQL1 = "DELETE FROM salaries WHERE record_id = '".$record."' ";
$stmt1 = sqlsrv_query(Database::GetInstance()->databaseConnection, $insertSQL1);
# IF THERE IS AN ERROR
if(!$stmt1){
echo "Error, cannot delete record";
}else{
Database::GetInstance()->LastInsertId($stmt1);
}
# IF ALL QUERIES WERE SUCCSESSFUL, COMMIT THE TRANSACTION, OTHERWISE ROLLBACK
if($stmt1 && !$errors){
sqlsrv_commit(Database::GetInstance()->databaseConnection);
# FREE THE STATEMENT
Database::GetInstance()->FreeDBStatement($stmt1);
echo "success";
return true;
}else{
sqlsrv_rollback(Database::GetInstance()->databaseConnection);
# FREE THE STATEMENT
Database::GetInstance()->FreeDBStatement($stmt1);
return false;
}
# NO CONNECTION WAS MADE
}else{
return false;
};
?>
preventDefault() doesn't work either

It sounds like your form is still being submitted, hence the redirect. You can stop it with preventDefault()...
$(document).on('submit', '#deleteform', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.post('includes/delete.php',formData,processData);
function processData(data){
record.remove();
};
});

Assuming "deleteform" is the ID of a form element on your page, within which you have an input or button of type "submit", I would suggest changing the delentry button to have a type of "button".
Most browsers will perform a POST/GET on a form that has an input or button of type submit when that button is clicked.
I would then update your jQuery event handler to select the button and specify an onclick event:
$('#delentry').click(function() {
...
});
If you wish to maintain some form of graceful degradation, you could leave the markup as a submit type button and on $(document).ready(), update the type of the button to be "button".

Related

Close Bootstrap Modal from within injected HTML?

Script to Call Modal, and HTML Skeleton for Modal: (which is working)
<script>
$(document).on("click", ".addworker", function (e) {
e.preventDefault();
var $popup = $("#popup");
var popup_url = $(this).data("popup-url");
$(".modal-content", $popup).load(popup_url, function () {
$popup.modal("show");
});
});
</script>
<div id="popup" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
</div>
</div>
</div>
The HTML loaded into modal-content is returned by a django view which sits behind the url. (this part is working too)
Inside this HTML i have the Button, which i want to use to then close the modal again.
But when the Modal got injected with the HTML and is open, it seems like the modal is out of scope, so i tried to get it back with var $popup = $("#popup");.
And i indeed get back the Object, but the $popup.modal("hide"); Method doesnt work.
<script>
$(document).on("click", ".cancel", function (e) {
var $popup = $("#popup");
$popup.modal("hide");
});
</script>
<div class="modal-header">
<h1>{{ aoe }} Worker: {{ id }}</h1>
</div>
<form action="add/" method="post">
{% csrf_token %}
<div class="modal-body">
{{ form|crispy }}
</div>
<div class="modal-footer">
<input type="button" class="btn btn-secondary cancel" value="Cancel">
<input type="submit" class="btn btn-primary" value="Submit">
</div>
</form>
My first workaround: (inside the html file that gets injected to the modal)
<script>
$(document).on("click", ".cancel", function (e) {
var $popup = document.querySelector('#popup');
$popup.classList.remove('show');
$('#popup').css("display", "none");
var $back = document.querySelector('.modal-backdrop');
$back.parentNode.removeChild($back);
});
</script>
This works, but is not really that convenient.
Second Workaround:
Just call $("#popup").click() when pressing the Close Button,
to simulate a click into the free area next to the Modal.
Feels like cheating, but at least its less effort now.
Still, i would like to know the "proper" way to do this.
Problem Solved. I included JQuery in Both HTML Files, which seemed to cause the function not to work anymore. Now it works using $("#popup").modal('hide');

Modal won't close and prevent default on no click, and won't execute func on yes click

I have a modal with two buttons. One is a yes button and one is a no button. If yes button is pressed, I would like the remainder of the function to execute. If no btn clicked, I would like the page to prevent default and not execute. However, it seems that regardless of which button is clicked, nothing happens besides the modal closing. I am using a modal example I found elsewhere, so this may be the issue. After glancing at it for some time I cannot seem to find where the issue is. Am I missing something small? Or perhaps my Jquery is wrong? Below is my code:
Modal:
<!-- Modal for delete-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content border-primary mb-3 box-shadow-none img-responsive">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="card-body bg-light">
<div id="del" class="center">
<label>Are you sure you want to delete?</label>
</div>
</div>
<div class="modal-footer">
<div id="deleteYes">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteYes">Yes</button>
</div>
<div id="deleteNo">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteNo">No</button>
</div>
</div>
</div>
</div>
</div>
And here is my Jquery:
$(".btnDeleteTerminalCommand").click(function (e) {
$("#deleteModal").modal('toggle');
if ($("#deleteNo").click) {
return e.preventDefault();
}
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
var termId = row.find(".tdTermId").html().trim();
var cmdId = row.find(".tdCmdId").html().trim();
var cmdVal = row.find(".tdCmdVal").html().trim();
var cmdID = row.find(".cmdID").html().trim();
var data = {
TerminalID: termId,
CommandID: cmdId,
CommandValue: cmdVal,
ID: cmdID
};
$.ajax({
url: '#Url.Action("DeleteTerminalCommand", "TerminalCommand")',
type: "POST",
data: data,
success: function (response) {
console.log("Success");
window.location.href = response.Url;
}
});
});
Any advice helps! Thank you!
Your click handler will toggle the modal and immediately continue to execute the rest of the function before the user can click anything. If your modal has two buttons, create a click handler for each button. Perhaps the No button just closes the modal. The Yes button handler can execute the actions required to accomplish the task.
$(".btnDeleteTerminalCommand").click(function(e){
$("#deleteModal").modal('toggle');
}
$("#deleteNo").click(function(e){
$("#deleteModal").modal('hide');
}
$("#deleteYes").click(function(e){
// build data object
// ajax post
}

Bootstrap modal doesn't work on live server

Trigger Button:
while ($row = mysqli_fetch_array($result)) {
$name = $row['name'];
$id = $row['id'];
echo '<a data-target="#exampleModal" class="wpmui-field-input button wpmui-submit button-primary" data-toggle="modal" data-whatever="'.$name.'">Details</a>';
echo $id . "<br>";
}
Modal:
echo'
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">New message</h4>
</div>
<div class="modal-body">
<form>
<textarea class="form-control"></textarea>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Send message</button>
</div>
</div>
</div>
</div>';
JavaScript:
echo'
<script type="text/javascript">
window.onload = function () {
$("#exampleModal").on("show.bs.modal", function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data("whatever") // Extract info from data-* attributes
var modal = $(this)
modal.find(".modal-title").text("New message to " + recipient)
modal.find(".modal-body textarea").val(recipient)
})
}
</script>';
Now I have all these codes above that will generate a Modal Box when clicked on that Trigger Button. This code seems to work fine in my localhost but it doesn't act the same in my server, and the values returned are undefined. Now, I think it might have something to do with the PHP Version, because my localhost has PHP7 and my server has PHP5. Does this mean in PHP5 does not support value field (JavaScript is .val()) in the <textarea> tag as in <textarea value="something">?
Even if that's the case, what is the workaround for this problem? I tried using .html() and .text() but all it does is overwriting the value, and when you open up the modal box once again, the value will be the same for ALL modal boxes (whereas it should be different value for each recipient modal box).
It seems you have'nt included necessary jquery and style files.try including bootstrap.js, jQuery.min.js
This one might be helpful for you
www.bootply.com/mRbjbQ1JAB
Good Luck.
Use chrome developer tools or in firefox depending on your browser, click on the network tab and load the page the modal is supposed to appear, check all the files listed in the network tab of developer tools for anyone with 404 not found, that is possibly what is missing.

Creating and submitting form in new window - not working

What I want is to create new form in a new page and have it submitted. I've picked up this snippet from How to create HTML Form in a new window.
But it's only opening a new window with the URL in the action and not submitting the form automatically:
(function($) {
Drupal.behaviors.ajax_example2 = {
attach: function(context) {
jQuery("#btn1").click(
function () {
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", 'http://moodle.foresteee.com/login/index.php');
// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("username", "testaccount1#wo");
hiddenField.setAttribute("password", "forest3");
form.appendChild(hiddenField);
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
}
);
}
}
})(jQuery);
And I've created a small link:
Click here
This seems to be working:
$('a').click(function(){
window.open('', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
$('<form></form>').attr('method','post').attr('action','url_to_post').attr('target','formresult').append('<input type="text" name="test" value="test_value"/>').submit();
});
JSFiddle
So, the whole popup window thing is a little 90s, isn't it? Modals are definitely the way to go and via a simple framework such as bootstrap, you can ensure that it will be cross-browser compatible and even responsive. Plus your interface will look a lot better.
just remember to include the bootstrap cdn:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
html:
<a class="btn btn-primary">click me bro</a>
<div id="popup" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal's rock!!</h4>
</div>
<div class="modal-body">
<form method="post" action="url_to_post" target="formresult"></form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
jquery:
$('a').click(function(){
$('.modal-body form').empty().prepend('<input type="text" name="test" value="test_value"/>');
$('#popup').modal('show');
});
check it out Fiddle
Continuing what Flash Thunder has done (he probably deserves more credit)
This is the fix that I found to his work
http://jsfiddle.net/doiks14/a8HFa/11/
For some reason, IE won't respond to a submit event from a form unless its in the body.
I've only really added $('body').append($form) - this seems to fix it.

Why these confirmation modal is not showing up?

I use a template that uses bootstrap. I'm having trouble with showing a modal.
The form has a jquery validation, if everything is ok then when clicking on submit a confirmation modal should appear to ask user if he is sure he wants to store that information. If form doesn't pass validation then a simple message appears.
For the mentioned actions I build this:
<form action="#" id="form_sample_2" class="form-horizontal">
<div class="alert alert-error hide">
<button class="close" data-dismiss="alert"></button>Existen errores en el formulario. Por favor verifique.</div>
<!-- modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel3" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel3">Cargar Usuario</h3>
</div>
<div class="modal-body">
<p></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cerrar</button>
<button data-dismiss="modal" class="btn green" id="btnYes">Confirmar</button>
</div>
</div>
<!-- end modal -->
</form>
As you can see, modal and error message has the attribute "hide"...
the js file:
var handleValidation2 = function () {
// for more info visit the official plugin documentation:
// http://docs.jquery.com/Plugins/Validation
var form2 = $('#form_sample_2');
var error2 = $('.alert-error', form2);
var success2 = $('#myModal', form2);
//IMPORTANT: update CKEDITOR textarea with actual content before submit
form2.on('submit', function () {
for (var instanceName in CKEDITOR.instances) {
CKEDITOR.instances[instanceName].updateElement();
}
})
form2.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
//some code
},
submitHandler: function (form) {
success2.show();
error2.hide();
}
//some code
On this snippet, if form doesn't pass validation then error2.hide() function shows up the alert error message.
Problem comes when form passes validation when success2.show() function should show confirmation modal, but it's not doing that. Nothing appears when form is ok and I'm wondering what am I doing wrong.
Any help would be really much appreciated.
J.
Instead of success2.show(); use success2.modal('show')
This should fix your issue
submitHandler: function (form) {
success2.removeAttr('aria-hidden');
success2.show();
error2.hide();
}
do u try to remove att aria-hidded. hope that work for u

Categories