jquery form submit can't handle success/error notifications - javascript

I want to show a success notification if the submit was successful with this js notify library but it's doesn't works.
If I change the new Notify({ ... }) function to a simple alert("success"); then the alert is showing up...
But if I insert the same js code in the browser's Console then it's showing the notify ...
<form action="" method="post">
<div class="form-group">
<label for="title"><h6>Title</h6></label>
<input type="text" class="form-control" name="title" id="title">
</div>
<div class="form-group">
<label for="content"><h6>Content</h6></label>
<textarea class="form-control" id="content" name="content"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" id="edit">Save</button>
</div>
</form>
<script>
$("#edit").click(function() {
var title = $("#title").val();
var content = $("#content").val();
$.ajax({
type: "POST",
url: "edit.php",
data: {
title: title,
content: content
},
cache: false,
success: function(data) {
new Notify({
status: 'success',
title: 'Test',
text: 'Success',
effect: 'fade',
speed: 300,
customClass: null,
customIcon: null,
showIcon: true,
showCloseButton: true,
autoclose: false,
autotimeout: 3000,
gap: 20,
distance: 20,
type: 1,
position: 'right top'
})
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
});
</script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/simple-notify#0.5.5/dist/simple-notify.min.css" />
<script src="https://cdn.jsdelivr.net/npm/simple-notify#0.5.5/dist/simple-notify.min.js"></script>

This statement in your comment under the question clarifies the issue:
I want to send the form's data then the page is just reloading immadiatelly and the notify doesn't showing up
The issue is because you've not called preventDefault() on the event which is raised. Therefore the form is still submit through the standard manner and a page redirect occurs. As you're using AJAX you need to prevent this behaviour.
Also note that it's slightly more semantic to hook the event handler to the submit event of the form element instead of the click of the submit button. Try this:
$("form").on('submit', e => {
e.preventDefault(); // stop form submission
$.ajax({
type: "POST",
url: "edit.php",
data: {
title: $("#title").val(),
content: $("#content").val()
},
cache: false,
success: function(data) {
new Notify({
status: 'success',
title: 'Test',
text: 'Success',
effect: 'fade',
speed: 300,
customClass: null,
customIcon: null,
showIcon: true,
showCloseButton: true,
autoclose: false,
autotimeout: 3000,
gap: 20,
distance: 20,
type: 1,
position: 'right top'
})
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
});

Related

How to close a jquery dialog from inside the open function?

I want to open this dot_card.php page in a dialog box. I want to interrupt the the form submission to do some stuff and them do an ajax call. After the form is submitted via ajax, I want to close the dialog box. But the code below doesn't seem to close it.
What am I doing wrong?
Here is my code.
$('<div><div id="addDotDiv"></div></div>').appendTo('body').dialog({
modal: false,
title: 'title',
closeOnEscape: true,
zIndex: 10000,
autoOpen: true,
minWidth: 650,
resizable: false,
position: { my: 'top+50', at: 'center', of: '#id-top' },
open: function() {
$('#addDotDiv').load('dot_card.php', '', function() {
$('#create_dot_form').submit(function(e) {
e.preventDefault();
var actionUrl = $('#create_dot_form').attr('action');
$.ajax({
type: "POST",
url: actionUrl,
data: $('#create_dot_form').serialize(),
success: function() {
$(this).closest('.ui-dialog').dialog('close');
}
});
});
});
},
close: function() {
$(this).remove();
}
});

Calling href with Angular to open modal

Context
I´m working in this Tutorial, is about CRUD with DataTable, but difference I´m using Asp.Net WebApi with Angular
I´m into step 9, where tutorial made partial views for pop-up window, but I don´t use partial view, instead it, I use Angular Views
Problem
I don´t know how to replace that partial View for my Angular View
Code
View
<table class="table table-striped table-hover table-bordered dt-bootstrap no-footer" id="tabla_catalogos" role="grid" aria-describedby="sample_editable_1_info">
<thead>
<tr>
<th class="hidden"></th>
<th style="width: 200px;"> Codigo </th>
<th> Nombre </th>
</tr>
</thead>
<tbody></tbody>
</table>
JS
$('#tabla_catalogos')
.DataTable({
searching: true,
dom: 'ftpB',
autoWidth: false,
buttons: [
//'excelHtml5', 'csv', 'print'
],
paging: true,
select: {
style: 'single'
},
info: false,
ordering: true,
"processing": true,
ajax: {
method: 'GET',
url: "../../api/Catalogo/GetCatalogoRegistro/" + selected.ID,
dataSrc: '',
beforeSend: function(request) {
request.setRequestHeader("Version", $scope.usuario.Version);
request.setRequestHeader("Origen", 'Web');
}
},
columns: [
{ data: 'Catalogo', visible: false, searchable: false },
{ data: 'Codigo' },
{ data: 'ID', visible: false, searchable: false },
{ data: 'Nombre' },
{ data: 'Padre', visible: false, searchable: false },
{
data: 'ID',
render: function(data){
return '<a class="popup" href="root.detalleregistros'+data+'">Editar</a>';
}
},
{
data: 'ID',
render: function (data) {
return '<a class="popup" href="root.detalleregistros' + data + '">Eliminar</a>';
}
}
],
pageLength: 10 //,
//pagingType: "simple_numbers"
,
language: {
"emptyTable": "No se encontraron registros",
"zeroRecords": "No encontraron coincidencias",
"search": "Buscar: "
}
});
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'));
});
function OpenPopup(pageUrl) {
var $pageContent = $('<div/>');
$pageContent.load(pageUrl, function () {
$('#popupForm', $pageContent).removeData('validator');
$('#popupForm', $pageContent).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
});
$dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
.html($pageContent)
.dialog({
draggable: false,
autoOpen: false,
resizable: false,
model: true,
title: 'Popup Dialog',
height: 550,
width: 600,
close: function () {
$dialog.dialog('destroy').remove();
}
})
$('.popupWindow').on('submit', '#popupForm', function (e) {
var url = $('#popupForm')[0].action;
$.ajax({
type: "POST",
url: url,
data: $('#popupForm').serialize(),
success: function (data) {
if (data.status) {
$dialog.dialog('close');
oTable.ajax.reload();
}
}
})
e.preventDefault();
})
$dialog.dialog('open');
}
};
Angular Service, invoke view:
.state('root.detalleregistros', {
url: "detalleRegistros.html",
templateUrl: "../SPA/administrador/catalogos/detalleRegistros.html",
controller: "detalleRegistrosCtrl",
authenticate: true
})
When I clic into url as mi code '<a class="popup" href="root.detalleregistros'+data+'">Editar</a>'; it redirect me to http://localhost:55720/admin/root.detalleregistros/1
instead
http://localhost:55718/admin/#/detalleRegistros.html
What I´am doing wrong there? help is very appreciated. Regards
I try '<a class="popup" ui-sref="root.detalleregistros({data:11})">Editar</a>'; as #Agam Banga comment but modal just don´t open, I need to add something to table view? or what can be wrong there?
You have defined the state for "root.detalleregistros". To Open this state, you need to use the inbuild directive of ui-router which is ui-sref.
<a ui-sref="root.detalleregistros">Editar</a>
Also, if you want to pass params, you can use
<a ui-sref="root.detalleregistros({data:11})">Editar</a>

Passing a variable from onclick to ajax

i am trying to passing a variable (region) from an onclick element to an ajax-function.
I am using PHP, SQL and the plugin http://t4t5.github.io/sweetalert/
Here is my Code in the head of an index.php
<script type"text/javascript">
function save(){
$.ajax({
type: "POST",
url: "addlandtovisited.php",
data: {region: region},
success: function(data) {
alert("Ajax save executed!");
}
});
}
</script>
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#ffffff',
hoverOpacity: 0.7,
selectedColor: '#666666',
enableZoom: true,
showTooltip: true,
scaleColors: ['#C8EEFF', '#006491'],
values: sample_data,
normalizeFunction: 'polynomial',
onRegionClick: function (element, code, region) {
var boton = "button";
swal({
title: ''+region,
showCancelButton: true,
showConfirmButton: false,
text: 'test',
html: true
});
}
});
});
</script>
The addlandtovisited.php:
<?php
if(isset($_POST['region'])){
?>
When i set a string to the ajax-function and delete the region from save(region), it works fine:
data: {region: "TEST"},
text: 'test',
As this thread suggests, there are some issues with the sweetalert repo. For example, I could not make the swal render html text in the body. Switching to sweetalert2 and applying the patch the thread mentions might be a good idea.
I would suggest you use the confirm button instead of creating your own link inside the body of the swal. For example:
swal({
title: '' + region,
showCancelButton: true,
showConfirmButton: true,
confirmButtonText: "save",
text: "anything",
html: true
}, function() { // save button callback
save(region);
});
Don't forget to add the region parameter to your save() method : save(region).

Open the Results of Autocomplete in Fancybox

I have the following autocomplete searchbox code
$("#searchbox").autocomplete({
source: function(request,response) {
$.ajax({
type: "POST",
dataType: "json",
data: { term: request.term },
url: "/Settings/Find?searchString="+request.term,
success: function(data) {
response($.map(data,function(item) {
return { label: item.Name ,value: item.Type, ID: item.ID};
}
))
}
})
},
messages: {
noResults: "No Results",results: "Results"
},
select: function(e, ui) {
window.location.assign('/Item/Details/'+ui.item.ID);
}
},
});
When the user clicks on the autocompleted items, I redirect them to the detail page of the item using this
window.location.assign('/Item/Details/'+item.ID);
Now, I want to display the details of the item in a fancybox without redirect the user to another page. So when the user clicks on the autocompleted results, a fancybox opens up with the details of the selected item.
Here is the fancybox code That i would like to call.
$('.fancyboxdisplay').fancybox({
fitToView: false,
autoSize: false,
closeClick: false,
width: '550px',
height:'680px',
padding: 15,
closeBtn:true,
'afterClose': function() {
window.location.reload();
},
});
I looked everywhere for a possible solution but i can't figure it out. Can you please help !
Thanks
Within your select setting, try replacing window.location.assign by the fancybox script like :
select: function (e, ui) {
// window.location.assign('/Item/Details/' + ui.item.ID);
$.fancybox({
href: '/Item/Details/' + ui.item.ID,
type: "iframe",
fitToView: false,
autoSize: false,
closeClick: false,
width: 550,
height: 680,
padding: 15,
closeBtn: true,
afterClose: function () {
window.location.reload();
}
});
}
It's assumed you have previously loaded fancybox js and css files

jqGrid open dialog in front of edit/add dialog

I can achieve the opening of a new dialog, but is opens behind the edit-/add-dailog. How can I make it opening in front of the edit-/add-dialog? If I do the same with an alert-box it works instantially.
<style>
.dialogue{ z-index: 1000; }
</style>
<script type="text/javascript">
jQuery(document).ready(function(){
$('#A').dialog({
autoOpen: false,
buttons: {
"Open Dialog B": function(){
$('#B').dialog('open');
}
}
});
$('#B').dialog({
autoOpen: false
});
jQuery("#list").jqGrid({
sortable: true,
url:'{{=URL('get',args=table)}}',
datatype: 'json',
mtype: 'GET',
colNames:{{=h}},
colModel :{{=b}},
ondblClickRow: function (rowid) {
myClickHandle.call(this, rowid);
},
jsonReader: {
repeatitems: false
},
width: 1024,
height: '100%',
pager: '#gridpager',
rowNum:10,
rowList:[10,20,30],
sortname: 'id',
sortorder: 'desc',
viewrecords: true,
gridview:true,
caption: '{{=table}}',
editurl:'{{=URL('adu',args=table)}}'
});
jQuery("#list").jqGrid('navGrid','#gridpager',
{edit:true},
{ beforeShowForm: function(form) {
$('.basic').live('click',function() {
$('#A').dialog("open");
});
},
width:500,height:'100%',
reloadAfterSubmit:false,
closeAfterEdit:true}, // edit options
{width:500,height:'100%',
closeAfterAdd:true}, // add options
{reloadAfterSubmit:false,
closeAfterSubmit:true}, // del options
{} // search options
);
jQuery("#list").jqGrid('navButtonAdd','#gridpager',{
caption: "",
title: "Reorder Columns",
onClickButton : function (){
jQuery("#list").jqGrid('columnChooser',{
done: function(perm) {
if (perm) {
var gridWidth = this.jqGrid('getGridParam', 'width');
this.jqGrid('setGridWidth', gridWidth);
this.jqGrid('remapColumns', perm, true);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "{{=URL('ps',args=(table,id))}}",
data: $('#list').jqGridExport({
exptype: 'jsonstring',
root: 'Settings'
})
});
}
}
});
}
});
});
</script>
<table id="list"></table>
<div id="gridpager">
</div>
<div title="Dialog A" id="A" class="dialogue">Dialog A</div>
<div title="Dialog B" id="B" class="dialogue">Dialog B</div>
Greets Kluther
Try using the modal option in the dialogues (jsFiddle http://jsfiddle.net/r4meJ/):
$('#A').dialog({
autoOpen: false,
modal: true,
buttons: {
"Open Dialog B": function(){
$('#B').dialog('open');
}
}
});
$('#B').dialog({
autoOpen: false,
modal: true
});
This should provide what you require

Categories