I am trying to create generalised method for ajax in my javascript and bootstrap modal is not working as expected.
HTML :
<div class="modal fade" id="consult_modal_v2" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div style="background-color: #dc3d3e;color: #fff;height:85px !important;;" class="modal-header">
<div>
<div class="row">
<div class="col-md-11">
<h4 id="message_v2" style="text-align:center;margin-top: 10px;"></h4>
</div>
</div>
</div>
<button id="con_close1_v2" type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="container"></div>
<div class="modal-body">
<div class="col-md-12" style="margin-top:3%;margin-bottom:2%;">
<div class="col-md-3" id="con_uname_v2" style="margin-top:11px">Admin Username</div>
<div class="col-md-9"><input type="text" id="con_sect_name_v2" class="form-control"></div>
<div class="col-md-3" id="con_pass_v2" style="margin-top:11px">Admin Password</div>
<div class="col-md-9"><input type="password" id="con_sect_pass_v2" class="form-control"></div>
</div>
</div>
<div style="border:none;" class="modal-footer" >
<button class="btn btn-default" id="con_close_v2" style="margin-top:3%;">Cancel</button>
<button class="btn btn-default" id="con_sect_ok_v2" style="margin-right:2%;margin-top:3%;">Override</button>
<button class="btn btn-default" id="con_upd_sect_ok_v2" style="display:none;margin-right:2%;margin-top:3%;">Override</button>
</div>
</div>
</div>
</div>
JavaScript:
Executed as
generalised_ajax('post_url',
{
'sub_id': sub_id,
'status': status,
'_token': csrf_token
}, "POST", function () {
console.log('success placing apt');
}, {},
function () {
console.log('apt cancelled');
}, {});
function generalised_ajax(url, data, type, post_success, post_success_params, post_cancel, post_cancel_params) {
$.ajax({
url: url,
data: data,
type: type,
headers: {Accept: "application/json"},
dataType: 'json',
success: function (result, status, xhr) {
post_success(post_success_params);
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.responseJSON.type === "confirmation") {
responseProcess = xhr.responseJSON;
generalised_confirm(responseProcess.message, {
url: url,
data: data,
type: type,
post_success: post_success,
post_success_params: post_success_params,
post_cancel: post_cancel,
post_cancel_params: post_cancel_params
}, responseProcess.config_name);
} else if(xhr.responseJSON.type === "admin_auth"){
generalised_authentication(responseProcess.message, {
url: url,
data: data,
type: type,
post_success: post_success,
post_success_params: post_success_params,
post_cancel: post_cancel,
post_cancel_params: post_cancel_params
});
}
}
});
}
function generalised_confirm(message, data, config_name) {
var r = confirm(message);
if (r === true) {
data.data[config_name] = true;
generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
} else {
data.post_cancel(data.post_cancel_params);
}
}
var modelX = $("#consult_modal_v2");
function generalised_authentication(message, data){
var uname = $("#con_sect_name_v2");
var pass = $("#con_sect_pass_v2");
$("#message_v2").val(message);
modelX.modal('toggle');
$("#con_sect_ok_v2").click(function(event){
modelX.modal('toggle');
data.data['a_uname'] = uname.val();
data.data['a_pswd'] = pass.val();
uname.val('');
pass.val('');
generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
});
$("#con_close_v2").click(function(event){
modelX.modal('toggle');
data.post_cancel(data.post_cancel_params);
});
}
Expected scenarios:
Sent ajax
Server responded with admin_auth error
Open modal
Input admin creds (wrong ones)
Close modal
Sent ajax
Server responded with admin_auth error
Repeat from stage 3
How it's working right now
Sent ajax
Server responded with admin_auth error
Open modal
Input admin creds (wrong ones)
Close modal
Sent ajax
Now server responded with same ajax as Point 2. But modal won't open again.
It is working fine with javascripts confirmation popup.
Update:
After I removed fade class from modal, it started appearing everytime. But now it sends double of ajax of previous attempt.
Like for first time once, second time twice, third time 4 times, 4th time 8 times and so on.
I don't know what is the reason of this behaviour but
changing
$("#con_sect_ok_v2").click(function(event){
modelX.modal('toggle');
data.data['a_uname'] = uname.val();
data.data['a_pswd'] = pass.val();
uname.val('');
pass.val('');
generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
});
to
$("#con_sect_ok_v2").one('click',function(event){
modelX.modal('toggle');
data.data['a_uname'] = uname.val();
data.data['a_pswd'] = pass.val();
uname.val('');
pass.val('');
generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
});
solved it.
Credits https://stackoverflow.com/a/3393694/2598994
Related
I have a dialog box which displays an OK button once the process completes.
I would like to refresh the page once user clicks OK.
However, in my existing code, there isn't a code to handle the behaviour after clicking OK.
Below is my current code
$.ajax({
type: "POST",
url: wsurl + "BackendRequest",
data: '{ sDomain : "' + domain + '", sUserName : "' + username '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
document.getElementById('btnGenerate').disabled = true;
showDialogPopup('Generate Request', data.d);
//window.location.reload();
},
error: function (objXMLHttpRequest, textStatus, errorThrown) {
showDialogPopup('Generate Request', data.d);
//window.location.reload();
}
});
The current window.location.reload(); refreshes the page immediately.
Is there a way to refresh the page only after user clicks OK in the showDialogPopup method?
You should write an onclick event for your "Ok" button.
try the code below:
<a onclick="OpenModal()">Open Modal</a>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<button onclick="ReloadPage()">Ok</button>
</div>
</div>
</div>
<script>
//Opens the popup
function OpenModal() {
$("#myModal").modal('show');
}
//Reloads the page
function ReloadPage() {
window.location.reload();
}
You can use confirm popup modal with return type boolean
success: function (data) {
const isConfirmed = confirm('Generate Request');
if(isConfirmed) {
console.log('Ok button clicked', data.d)
window.location.reload();
}
}
I've some problem with AJAX request. As the title said, I want to execute an AJAX request after succeeding previous AJAX, for printing via thermal printer.
So far, I have some buttons with 3 different IDs. Every IDs will execute an AJAX request to query an update into database, and it's succeeded. But then I want to execute another AJAX request for printing via thermal printer (QPOS Q58M) via escpos-php. The result think it's success but no printing done. Then I tried to execute the printing script without AJAX and it's succeeded.
Here's the HTML view
<div class="row">
<div class="col-lg-4 col-md-4 col-xs-12">
<button class="btn btn-app btn-purple">
<div >Certificate</div>
</button>
<button id="simpan_antrian1" class="btn btn-app btn-purple print">
<i style="padding:55px 0;font-size:100px" class="ace-icon fa fa-user-plus"></i>
</button>
<button class="btn btn-app btn-purple">
<div id="load_antrian1"></div>
</button>
</div>
<div class="col-lg-4 col-md-4 col-xs-12">
<button class="btn btn-app btn-purple">
<div >Test</div>
</button>
<button id="simpan_antrian2" class="btn btn-app btn-purple print">
<i style="padding:55px 0;font-size:100px" class="ace-icon fa fa-user-plus"></i>
</button>
<button class="btn btn-app btn-purple">
<div id="load_antrian2"></div>
</button>
</div>
<div class="col-lg-4 col-md-4 col-xs-12">
<button class="btn btn-app btn-purple">
<div >Course</div>
</button>
<button id="simpan_antrian3" class="btn btn-app btn-purple print">
<i style="padding:55px 0;font-size:100px" class="ace-icon fa fa-user-plus"></i>
</button>
<button class="btn btn-app btn-purple">
<div id="load_antrian3"></div>
</button>
</div>
</div>
And here is the script for calling the request
<script type="text/javascript">
$(document).ready(function(){
$('#load_antrian1').load('pages/beranda/getAntrian1.php');
$('#load_antrian2').load('pages/beranda/getAntrian2.php');
$('#load_antrian3').load('pages/beranda/getAntrian3.php');
// antrian sertifikat
$("#simpan_antrian1").on('click',function(){
$.ajax({
url : "pages/beranda/proses1.php",
type : "POST",
cache : false,
success: function(
if(msg=="Sukses"){
$('#load_antrian1').load('pages/beranda/getAntrian1.php').fadeIn("slow");
$('#load_antrian2').load('pages/beranda/getAntrian2.php').fadeIn("slow");
$('#load_antrian3').load('pages/beranda/getAntrian3.php').fadeIn("slow");
$.ajax({
url : "pages/beranda/print.php",
type: "POST",
cache: false,
//success: function(data, textStatus, jqXHR)
success: function()
{
alert('Please take your ticket');
}
error:function (){
alert("There is an error when printing")
}
});
}
}
});
});
// antrian Test
$("#simpan_antrian2").on('click',function(){
$.ajax({
url : "pages/beranda/proses2.php",
type : "POST",
cache : false,
success: function(
if(msg=="Sukses"){
$('#load_antrian1').load('pages/beranda/getAntrian1.php').fadeIn("slow");
$('#load_antrian2').load('pages/beranda/getAntrian2.php').fadeIn("slow");
$('#load_antrian3').load('pages/beranda/getAntrian3.php').fadeIn("slow");
$.ajax({
url : "pages/beranda/print.php",
type: "POST",
cache: false,
//success: function(data, textStatus, jqXHR)
success: function()
{
alert('Please take your ticket');
}
error:function (){
alert("There is an error when printing")
}
});
}
}
});
});
// antrian Test
$("#simpan_antrian3").on('click',function(){
$.ajax({
url : "pages/beranda/proses3.php",
type : "POST",
cache : false,
success: function(
if(msg=="Sukses"){
$('#load_antrian1').load('pages/beranda/getAntrian1.php').fadeIn("slow");
$('#load_antrian2').load('pages/beranda/getAntrian2.php').fadeIn("slow");
$('#load_antrian3').load('pages/beranda/getAntrian3.php').fadeIn("slow");
$.ajax({
url : "pages/beranda/print.php",
type: "POST",
cache: false,
//success: function(data, textStatus, jqXHR)
success: function()
{
alert('Please take your ticket');
}
error:function (){
alert("There is an error when printing")
}
});
}
}
});
});
});
</script>
UPDATE
Well I've tried to make a new button for printing so it won't make a nested AJAX request, but unfortunately still can't do the trick...
Here's my last change
HTML
<div class="row">
<div class="col-lg-4 col-md-4 col-xs-12">
<button class="btn btn-app btn-purple">
<div >Certificate</div>
</button>
<button id="simpan_antrian1" class="btn btn-app btn-purple print">
<i style="padding:55px 0;font-size:100px" class="ace-icon fa fa-user-plus"></i>
</button>
<button class="btn btn-app btn-purple">
<div id="load_antrian1"></div>
</button>
</div>
<div class="col-lg-4 col-md-4 col-xs-12">
<button class="btn btn-app btn-purple">
<div >Test</div>
</button>
<button id="simpan_antrian2" class="btn btn-app btn-purple print">
<i style="padding:55px 0;font-size:100px" class="ace-icon fa fa-user-plus"></i>
</button>
<button class="btn btn-app btn-purple">
<div id="load_antrian2"></div>
</button>
</div>
<div class="col-lg-4 col-md-4 col-xs-12">
<button class="btn btn-app btn-purple">
<div >Course</div>
</button>
<button id="simpan_antrian3" class="btn btn-app btn-purple print">
<i style="padding:55px 0;font-size:100px" class="ace-icon fa fa-user-plus"></i>
</button>
<button class="btn btn-app btn-purple">
<div id="load_antrian3"></div>
</button>
</div>
<div class="col-lg-12 col-md-12 col-xs-12">
<button class="btn btn-app btn-purple" id="print">
<i style="font-size:2em" class="ace-icon fa fa-print"></i> Print your ticket
</button>
</div>
</div>
Javascript
$(document).ready(function(){
$('#load_antrian1').load('pages/beranda/getAntrian1.php');
$('#load_antrian2').load('pages/beranda/getAntrian2.php');
$('#load_antrian3').load('pages/beranda/getAntrian3.php');
// antrian sertifikat
$("#simpan_antrian1").on('click',function(){
$.ajax({
url : "pages/beranda/proses1.php",
type : "POST",
cache : false,
success: function(msg){
if(msg=="Sukses"){
$('#load_antrian1').load('pages/beranda/getAntrian1.php').fadeIn("slow");
$('#load_antrian2').load('pages/beranda/getAntrian2.php').fadeIn("slow");
$('#load_antrian3').load('pages/beranda/getAntrian3.php').fadeIn("slow");
}
}
});
});
// antrian Test
$("#simpan_antrian2").on('click',function(){
$.ajax({
url : "pages/beranda/proses2.php",
type : "POST",
cache : false,
success: function(msg)
{
if(msg=="Sukses"){
$('#load_antrian1').load('pages/beranda/getAntrian1.php').fadeIn("slow");
$('#load_antrian2').load('pages/beranda/getAntrian2.php').fadeIn("slow");
$('#load_antrian3').load('pages/beranda/getAntrian3.php').fadeIn("slow");
}
}
});
});
// antrian Test
$("#simpan_antrian3").on('click',function(){
$.ajax({
url : "pages/beranda/proses3.php",
type : "POST",
cache : false,
success: function(msg)
{
if(msg=="Sukses"){
$('#load_antrian1').load('pages/beranda/getAntrian1.php').fadeIn("slow");
$('#load_antrian2').load('pages/beranda/getAntrian2.php').fadeIn("slow");
$('#load_antrian3').load('pages/beranda/getAntrian3.php').fadeIn("slow");
}
}
});
});
$("#print").on('click',function () {
$.ajax({
url : "pages/beranda/print.php",
type: "POST",
cache: false,
//success: function(data, textStatus, jqXHR)
success: function()
{
alert('Please take your ticket');
},
error:function (){
alert("There is an error when printing");
}
});
})
});
well still can't do the printing, but the AJAX response it as success
UPDATE
For documentation purpose, I put the print script below
<?php
//date_default_timezone_set("ASIA/JAKARTA");
// panggil file config.php untuk koneksi ke database
require_once "../../../config/config.php";
// panggil file fungsi nama hari
require_once "../../../config/fungsi_nama_hari.php";
require 'pengunjung/vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
$hari_ini = date("Y-m-d");
$configID = "1";
// fungsi query untuk menampilkan data dari tabel sys_config
$result = $mysqli->query("SELECT nama_instansi FROM sys_config WHERE configID='$configID'") or die('Ada kesalahan pada query tampil data config: '.$mysqli->error);
$data_config = $result->fetch_assoc();
// fungsi query untuk menampilkan data dari tabel antrian
$result = $mysqli->query("SELECT max(no_antrian) as nomor, loket FROM antrian WHERE tanggal='$hari_ini' ORDER BY no_antrian DESC LIMIT 1") or die('Ada kesalahan pada query tampil nomor antrian: '.$mysqli->error);
$data = $result->fetch_assoc();
$nama_instansi = $data_config['nama_instansi'];
$loket = $data['loket'];
$no_antrian = $data['nomor'];
$hari = date("l");
$tanggal = date("d-m-Y");
$jam = date("H:i:s");
$connector = new WindowsPrintConnector("POS-58");
$printer = new Printer($connector);
$printer->setJustification(Printer::JUSTIFY_CENTER);
/* Name of shop */
$printer -> selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
$printer -> text($nama_instansi."\n");
$printer -> selectPrintMode();
$printer -> text($hari." ".$tanggal." ".$jam."\n");
$printer -> feed();
/* Title of receipt */
$printer -> setEmphasis(true);
$printer -> text("YOUR QUEUE\n");
$printer -> setEmphasis(false);
$printer -> feed();
//
$printer -> setJustification(Printer::JUSTIFY_CENTER);
$printer -> setTextSize(8, 8);
$printer -> text($no_antrian."\n");
$printer -> setTextSize(4, 4);
$printer -> text($loket."\n");
$printer -> feed();
$printer -> cut();
$printer -> pulse();
$printer -> close();
echo 'sukses';
?>
You have some mistakes in your js code. Check below code..
<script type="text/javascript">
$(document).ready(function(){
$('#load_antrian1').load('pages/beranda/getAntrian1.php');
$('#load_antrian2').load('pages/beranda/getAntrian2.php');
$('#load_antrian3').load('pages/beranda/getAntrian3.php');
// antrian sertifikat
$("#simpan_antrian1").on('click',function(){
$.ajax({
url : "pages/beranda/proses1.php",
type : "POST",
cache : false,
success: function(msg){
if(msg=="Sukses"){
$('#load_antrian1').load('pages/beranda/getAntrian1.php').fadeIn("slow");
$('#load_antrian2').load('pages/beranda/getAntrian2.php').fadeIn("slow");
$('#load_antrian3').load('pages/beranda/getAntrian3.php').fadeIn("slow");
$.ajax({
url : "pages/beranda/print.php",
type: "POST",
cache: false,
//success: function(data, textStatus, jqXHR)
success: function()
{
alert('Please take your ticket');
},
error:function (){
alert("There is an error when printing")
}
});
}
}
});
});
// antrian Test
$("#simpan_antrian2").on('click',function(){
$.ajax({
url : "pages/beranda/proses2.php",
type : "POST",
cache : false,
success: function(msg)
{
if(msg=="Sukses"){
$('#load_antrian1').load('pages/beranda/getAntrian1.php').fadeIn("slow");
$('#load_antrian2').load('pages/beranda/getAntrian2.php').fadeIn("slow");
$('#load_antrian3').load('pages/beranda/getAntrian3.php').fadeIn("slow");
$.ajax({
url : "pages/beranda/print.php",
type: "POST",
cache: false,
//success: function(data, textStatus, jqXHR)
success: function()
{
alert('Please take your ticket');
},
error:function (){
alert("There is an error when printing")
}
});
}
}
});
});
// antrian Test
$("#simpan_antrian3").on('click',function(){
$.ajax({
url : "pages/beranda/proses3.php",
type : "POST",
cache : false,
success: function(msg)
{
if(msg=="Sukses"){
$('#load_antrian1').load('pages/beranda/getAntrian1.php').fadeIn("slow");
$('#load_antrian2').load('pages/beranda/getAntrian2.php').fadeIn("slow");
$('#load_antrian3').load('pages/beranda/getAntrian3.php').fadeIn("slow");
$.ajax({
url : "pages/beranda/print.php",
type: "POST",
cache: false,
//success: function(data, textStatus, jqXHR)
success: function()
{
alert('Please take your ticket');
},
error:function (){
alert("There is an error when printing")
}
});
}
}
});
});
});
</script>
You should try to use promises and callback functions like the example above:
//an ajax call to return some data from the server, in this case is dynamic based on the action I want to perform
function _ajaxObtenerInfo(action,data){
return $.ajax({
url: 'ajsources/file.php',
type: 'POST',
dataType: 'html',
data: {action: action, data:data}
})
}
//a function to append the content returned on my ajax success
function cargarElement (response1,response2){//pass the responses
//in my case i need to load with data the first tab from a tab list so i have to loop the panels
//to find the id of the current active tab cause the ids where generated randomly
//if you know the id you would not need the loop i use under this comment
var href = $("#listData").children("li.ui-tabs-active").find('a').attr('href');
var div = $("#panels").children('div');
$.each(div, function(index, value) {
//console.log(index,value);
if ($(value).attr('id') == href.substring(1,href.length)) {
$(value).append(response1[0]+response2[0]); //note : my responses are html content so you should manage your response as you needed
}
});
}
//a when callback to manage all promises
$.when(_ajaxObtenerInfo('TPROGRAMADOS',data2),_ajaxObtenerInfo('TSEGUIMIENTO',data2))
//what happends here is that my when will wait 'til all my ajax calls are done and then
//it will execute a function to append my content
.then(function(response1,response2){
cargarElement(response1,response2);
})
Hope it helps =)
First I'm sorry, this is a mistake from my print.php code...
I've tried to run this script without AJAX, and found an error that can't find a file
require 'pengunjung/vendor/autoload.php';
So I guess it's a small mistake from this thing, and I change it to
require '../../vendor/autoload.php';
// you should know where this file located
And it works!
Once again, I'm sorry...
I have a form in modal as follows:
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<form id="Myform" action="/action_page.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="button" onclick="submitform()" value="Submit">
</form>
</div>
</div>
</div>
Javascript
function submitform() {
//try
//event.stopImmediatePropagation();
//event.stopPropagation();
//check validate is valid
if (formValid) {
$("#Myform").trigger("submit");
}
}
$("#Myform").submit(function (e) {
e.preventDefault();
// e.stopImmediatePropagation();
$.ajax({
type: this.method,
cache: false,
url: this.action,
enctype: 'multipart/form-data',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
$('#create-media').modal('toggle');
}
},
error: function (error) {
console.log(error);
}
});
});
Currently, when the user click on the submit button, the data will be sent to the server to process, during the time waiting for the results returned, the modal has not been closed, the user can click to submit more times. I do not want this to happen.
I want to prevent users submitting continuously, do not allow users to click on the second submit button, the user must wait for the results returned, if successful, the modal will be closed.
I was thinking of disabling the submit button, but that's not safe, because the user can enable that button because of javascript on the user machine.
I tried using event.stoppropagation () and event.stopimmediatepropagation () but it did not work.
Am I doing something wrong? How do I prevent users from submitting continuously?
Thanks AlL
Follwing CertainPerformance idea, I would suggest you use a variable. However, instead of placing the variable at the beginning of the code, I would suggest to use the beforeSend callback provided by Ajax, it will be called right before sending the request.
var isBusy = false;
$("#Myform").submit(function (e) {
e.preventDefault();
if(isBusy) {
return;
}
$.ajax({
type: this.method,
cache: false,
url: this.action,
enctype: 'multipart/form-data',
data: new FormData(this),
processData: false,
contentType: false,
beforeSend: function(xhr) {
isBusy = true;
},
success: function (data) {
$('#create-media').modal('toggle');
isBusy = false;
},
error: function (error) {
console.log(error);
isBusy = false;
}
});
});
You can learn more about the beforeSend callback here
P.S. You could also use the $.ajax.active variable, which returns the amount of active ajax request, this might be a more elegent method.
Give your submitform function a persistent alreadySubmitted variable. Also, try attaching the button handler from Javascript instead of HTML, and preventDefault:
const submitform = (() => {
let alreadySubmitted = false;
return (e) => {
e.preventDefault();
if (alreadySubmitted) return;
alreadySubmitted = true;
if (formValid) {
$("#Myform").trigger("submit");
}
}
})();
document.querySelector('#Myform input[type="button"]').addEventListener('click', submitForm);
I am following a link to allow a person to reset a password, however, everything that I have done so far isn't working and I can't figure out why as I am following the tutorial closely. I am using javascript and html so far, but there are no errors in the console so i am unsure what is wrong.
HTML
<div class="container-forgotPassword">
<div class ="row justify-content-center">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<img id="logologin" src="../img/logo1.png" alt="logo"/>
<input class="formPassword" id="email" placeholder="Please enter your Email Address">
<input type="button" class="btn-forgotPassword" value="Reset Password">
</div>
</div>
</div>
</div><!-- /container -->
jQuery
var email = $("#email");
$(document).ready(function () {
$('.btn-forgotPassword').on('click', function () {
if (email.val() != "") {
email.css('border', '1px solid green');
$.ajax({
url: 'php/forgotPassword.php',
method: 'POST',
dataType: 'text',
data: {
email: email.val()
}, success: function (response) {
console.log(response);
}
});
} else
email.css('border', '1px solid red');
});
});
In the tutorial so far he has gotten the input box to turn green/ red and when he enters text into the input field and then clicks the button it will create a response in the console log. But as I said mine is doing nothing, does anyone know how I can fix this? Not sure what I am doing wrong
you need error callback in ajax to show you the error
you miss write. there is no parameter named method in jquery ajax. this should be type
.
$.ajax({
url: 'php/forgotPassword.php',
type: 'POST', //not method
dataType: 'text',
data: {
email: email.val()
}, success: function (response) {
console.log('success');
console.log(response);
}, error: function(response){
console.log('error');
console.log(response); //get all error response
console.log(response.responseText);//get error responseText
}
});
I have a form on a bootstrap modal with two buttons. This form is tied to an action named "DeleteWidgetConfirmed" I am trying to remove a widget from the database and from the front end, the panel gets removed from the front end but does not seem to get removed from the database.
Here is my Modal
<div class="modal fade" id="deleteWidgetModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<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="myModalLabel">Delete widget?</h4><!--add depending on which panel you have clicked-->
</div>
<div class="modal-body" id="myModalBody">
<!--Depending on which panel insert content-->
#using (Html.BeginForm("DeleteWidgetConfirmed", "Dashboard", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
Do you wish to delete this widget?
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" value="DeleteWidgetConfirmed" class="btn btn-danger btn-ok" id="delete-widget">Delete</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
Here is my action:
// POST: DashboardModels/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteWidgetConfirmed(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DashboardModel dashboardModel = db.dashboards.Find(id);
db.dashboards.Remove(dashboardModel);
db.SaveChanges();
return new EmptyResult();
}
From my javascript I get the ID from the panel and store it into a variable, I then get the action attribute from my form and append the ID to the action attribute.
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('show');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
document.getElementById('delete-widget').onclick = function (event) {
event.stopPropagation();
//we make an ajax call to the controller on click
$.ajax({
url: '#Html.Raw(Url.Action("Dashboard", "DeleteWidgetConfirmed"))',
data: { id: widgetID},
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data){
var parentElement = $(panel).closest(".col-md-4.column");
var targetElement = $(panel).closest(".panel.panel-default");
targetElement.remove();
//parentElement.addClass("expand-panel");
checkEmptyPanelContainers();
$('#deleteWidgetModal').modal('hide');
},
error: function (response) {
}
})
}
})
});
I have a hunch that maybe within my javascript I have overridden the default behaviour of the event.
What I want to achieve ultimately is
within the onclick event for the button to remove the panels(which works)
remove the entry within the database related to that panel.
When executing the post method do not refresh.
Try using AJAX to asynchronously post to your controller:
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('toggle');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
$.ajax({
url: '/Dashboard/DeleteWidgetConfirmed/',
type: 'POST',
data: { id: widgetid },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
// request failed, handle here!
},
success: function (result) {
// request succeeded! handle that here. close the modal? remove the item from the UI?
}
});
}
});
});
How you handle the success callback depends on the UI, you can use the data- attributes to do so quite easily.
You need to decorate your action method as POST if you do this:
[HttpPost]
public ActionResult DeleteWidgetConfirmed(int id) {
...
}