How to add reset button in Dialog box - javascript

I want to add a RESET button in dialog box whose work is to delete the Hidden field value from database and close the dialog box:
Here is my code
<script type="text/javascript">
function OpenPopup() {
var data = document.getElementById('<%=hflinkData.ClientID %>').value;
var keyval = data.split(';');
var table = '<table>';
for (var i = 0; i < keyval.length; i++) {
var arr = keyval[i].split('=');
table += "<tr><td>" + arr[0] + "</td><td>" + arr[1] + "</td></tr>";
}
table += '</table>';
$('#WindowBody').html(table);
$('#dialogWindow').dialog({
autoOpen: false,
modal: true,
height: 200,
width: 500,
title: "Device Info",
resizable: false,
draggable: false,
position: ['center', 'center'],
closeOnEscape: true,
open: function (event, ui)
{
$('.ui-dialog').css('top', 100);
},
create: function (event) { $(event.target).parent().css('position', 'fixed'); }
});
$('#dialogWindow').dialog('open');
return false;
}
`
and this my HTML code
<div id="dialogWindow" >
<label></label>
<div id="WindowBody">
</div>
</div>`
Where "hflinkData" is the name of hidden field

Kindly use ajax post to achieve your requirement. Use normal html input button inside dialog. Kindly see the below code snippet.
<div id="dialogWindow" >
<label></label>
<div id="WindowBody">
</div>
<input type="button" onclick="deleteValue();" value="RESET" />
</div>
And send the AJAX post to code behind in 'deleteValue' method. Please see the below javascript code snippet.
<script type="text/javascript">
function deleteValue() {
$.ajax({
url: "Default.aspx/DeleteData",
type: "POST",
data: {value:$("#hflinkData").val()},
error: function (data) {
alert(data);
},
success: function (result) {
alert(result);
}
})
}
</script>
And write the required code for delete operation in code behind.
[WebMethod]
public static void DeleteData(string value)
{
//get the hidden value from parameter
//code for delete corresponding value from data base
}
Regards,
Sunil Prabakar C

Related

Reload script (Poptrox) after ajax request

So I'm using an AJAX request to load data from the database into a DIV. At the same time, I'm using the same data inside the DIV in a different script (Poptrox) witch does some design stuff.
Without the AJAX request, poptrox works, but if I'm using it together with poptrox it doesn't do the designing anymore.
Is there a way to reload the poptrox-script after the ajax request?
NOTE: the AJAX-Code and the Poptrox-code are placed inside the "main.js"!
Thanks in advance!
php:
<script src="assets/js/jquery.min.js"></script>
<section class="wrapper">
<form action="kochbuch.html" method="get" id="searchfilter">
<input type="text" class="searchBox" name="searchBox" id="searchBox" placeholder="Search..">
<button type="submit" id="searchBtn"><i class="fas fa-search"></i></button>
</form>
</section>
<section class="wrapper">
<div id="gerichte"></div>
</section>
<script src="assets/js/main.js"></script>
js-ajax:
var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
if (urlParams.has('searchBox')){
var searchBox = urlParams.get('searchBox');
$.ajax({
type: "POST",
url: "kochbuch/fetchdata.php",
data: {
"search_post_btn": 1,
"searchBox": searchBox,
},
dataType: "json",
success: function (response) {
$("#gerichte").html(response);
}
});
};
js-poptrox:
// Gerichte.
var $gerichte = $('#gerichte');
// Thumbs.
$gerichte.children('.thumb').each(function() {
var $this = $(this),
$image = $this.find('.image'), $image_img = $image.children('img'),
x;
// No image? Bail.
if ($image.length == 0)
return;
// Image.
// This sets the background of the "image" <span> to the image pointed to by its child
// <img> (which is then hidden). Gives us way more flexibility.
// Set background.
$image.css('background-image', 'url(' + $image_img.attr('src') + ')');
// Set background position.
if (x = $image_img.data('position'))
$image.css('background-position', x);
// Hide original img.
$image_img.hide();
});
// Poptrox.
$gerichte.poptrox({
baseZIndex: 20000,
caption: function($a) {
var s = '';
$a.nextAll().each(function() {
s += this.outerHTML;
});
return s;
},
fadeSpeed: 300,
onPopupClose: function() { $body.removeClass('modal-active'); },
onPopupOpen: function() { $body.addClass('modal-active'); },
overlayOpacity: 0,
popupCloserText: '',
popupHeight: 150,
popupLoaderText: '',
popupSpeed: 300,
popupWidth: 150,
selector: '.thumb > a.image',
usePopupCaption: true,
usePopupCloser: true,
usePopupDefaultStyling: false,
usePopupForceClose: true,
usePopupLoader: true,
usePopupNav: true,
windowMargin: 50
});
// Hack: Set margins to 0 when 'xsmall' activates.
breakpoints.on('<=xsmall', function() {
$main[0]._poptrox.windowMargin = 0;
});
breakpoints.on('>xsmall', function() {
$main[0]._poptrox.windowMargin = 50;
});
alright, i found one possible solution, but know the preloaded data ist formated:
the whole poptrox code has to be wrapped by this function:
$(document).ajaxStop(function () {
// function after ajax
});
If you know any better solution, feel free to submit :)
EDIT:
alright, my solution was as follows:
if (urlParams.has('searchBox')){
var searchBox = urlParams.get('searchBox');
} else {
var searchBox = '';
}
$.ajax({ .....

Ajax serialize form - PHP can't get individual input data

I have a JQuery UI dialog that is used for making a backup of a file. It contains an input box so users can add a short description that will become part for the name of the backup file. So if the user enters "blue", the backup file name will be: file_blue_2020-08-08-11:10:23.
The form name is: bckup
In my Ajax code, I'm using var frm = $('form[name="bckup"]').serialize(); for the form.
The name of the input field is: dscrb
As you can see in my PHP code, I'm trying to get the value of dscrb but it does not work. The resulting file name is: file_2020-08-08-11:10:23. However, if I change the PHP code to use $_POST["frm"] instead of $_POST["dscrb"], the resulting file name is: file_dscrb=blue_2020-08-08-11:10:23
So this tells us that the data is being posted to the PHP page.
Why then does $_POST["dscrb"] not work?
HTML:
<div id="dialog-backup" style="display: none;" title="Blah?">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0px 12px 22px 0px;"></span>Blaha.</p>
<form name="bckup">
<p style="margin-left: 28px;"><label for="dscrb">Description: </label><input id="dscrb" type="text" style="z-index:10000" name="dscrb"> (optional)</p>
</form>
<p style="margin-left: 28px;">Blah?</p>
</div>
JS:
$("#backup").click(function() {
$( "#dialog-backup" ).dialog({
stack: true,
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Save": function() {
//$( this ).dialog( "close" );
$("#saveConf").trigger("click");
},
"Create a backup": function() {
$( this ).dialog( "close" );
var frm = $('form[name="bckup"]').serialize();
$.ajax({
url : "ajax_functions.php",
type: "post",
data: { action: "backup", frm: frm },
//dataType: "text",
dataType: 'json',
success : function (response) {
var response = response[0]
if (response && response.toLowerCase().indexOf("success") >= 0) {
$("#dialg-success-msg").text(response);
$("#dialg-success").dialog("open");
} else {
$("#dialg-failed-msg").text(response);
$("#dialg-failed").dialog("open");
}
},
error : function(response) {
$("#dialg-failed-msg").text(response);
$("#dialg-failed").dialog("open");
}
});
//return false;
//////////////////
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
PHP:
$dscrpn = isset($_POST["dscrb"]) ? trim(stripslashes($_POST["dscrb"]))."_" : '';
$backup_file = "backups/File_".$dscrpn.date('Y-m-d-H:i:s');
Since you are sending your post-data as frm: frm you will have to use $_POST['frm'] in PHP.
You will get a string like dcsbr=.... To convert this to an array use parse_str.
$form = [];
parse_str($_POST['frm'], $form);
var_dump($form);
Working example.

How can I send data to controller by dialog?

EDIT2: I'm trying to update my code with java, but it's not working (I suppose I miss something in controller):
$(document).ready(function() {
var listGraphic = new Array();
function addPhoto(u, d) {
$.ajax({
url: "aggiungiEpigrafe",
type: "POST",
data: {"graphicUrl": u, "graphicDesc": d},
success: function(data) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc, "<br /><br />");
$(this).dialog("close");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$("#newPhoto").submit(function(e) {
e.preventDefault();
var url = $("#graphicUrl").val();
var desc = $("#graphicDesc").val();
listGraphic.push(url);
listGraphic.push(desc);
console.log(listGraphic);
addPhoto(url, desc);
$("#graphicUrl").val("");
$("#graphicDesc").val("");
if ($('#insertPhoto').dialog("isOpen")) {
$('#insertPhoto').dialog("close");
}
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
$("#newPhoto").submit();
}
}
});
});
EDIT1:
Following Twisty suggestion I uptaded the dialog in order to not have any form inside (since this dialog is already in a form): https://jsfiddle.net/e57sj6hp/18/
As Twisty was also commenting, I probably need ajax, but I have to understand how use it; I think I need to use serialize() or seralizeArray(), but I don't understand well how should the controller receive the json and use it.
I have a controller like this:
public String myMethod(#ModelAttribute MyObject object, ModelMap model){...}
The object include a List of photos, and two variables url and description:
List<Photo> photos;
String url;
String description;
each photo in the list is formed by an url and a description.
In my jsp I created a dialog with jquery where a user can put an url and a description, what I want to do is to add each value into a list and send it to the controller, then clean the dialog in order to allow another submission.
I have tried a lot of but can't understand how I should do it. I'm using the spring's form and I have tried many different ways, but I think that the problem is in my javascript code. Here's one example: https://jsfiddle.net/e57sj6hp/12/
In this example the input fields and the textarea inside the dialog aren't surrounded with spring's form tags, since I've append the result inside the div and I supposed that, at the moment of the submitting, the controller should receive the data inside the form:input just created.
Not familiar with Spring, so I may miss an element, but matching what you put in your example, I can offer some potential updates.
Working Example: https://jsfiddle.net/Twisty/e57sj6hp/16/
HTML Updated
<div id="insertPhoto" style="display:none" title="Insert a Photo">
<form id="newPhoto">
<label>Url:</label>
<br/>
<input id="graphicUrl" />
<br/> Description:
<br/>
<textarea rows="4" cols="20" id="graphicDesc"></textarea>
</form>
</div>
You cannot call form.reset() without a form element. I wrapped the the form elements in a form. This has the added benefit of now responding to the form being submitted, for example if the user enters a url and hits enter.
jQuery
$(document).ready(function() {
var listGraphic = new Array();
function addPhoto(u, d) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc);
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$("#newPhoto").submit(function(e) {
e.preventDefault();
var url = $("#graphicUrl").val();
var desc = $("#graphicDesc").val();
listGraphic.push(url);
listGraphic.push(desc);
console.log(listGraphic);
addPhoto(url, desc);
$(this)[0].reset();
if ($('#insertPhoto').dialog("isOpen")) {
$('#insertPhoto').dialog("close");
}
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
$("#newPhoto").submit();
}
}
});
});
Lots of little fixes and improvements here. I moved listGraphic out of the functions, so it can be updated more globally. This allows it to be updated and read from other callbacks.
I created the function to make it a little easier to repeat.
Now regardless of how the form is submitted, the array is updated and so is the page. The dialog is closed and it's form is reset.
UPDATE 1
See new jQuery: https://jsfiddle.net/Twisty/e57sj6hp/21/
jQuery
$(document).ready(function() {
function addPhoto(u, d) {
$.ajax({
url: "aggiungiEpigrafe",
type: "POST",
data: JSON.stringify({
"graphicUrl": u,
"graphicDesc": d
}),
complete: function(data) {
var $url = $("<form:input>").attr({
path: "graphicUrl",
disabled: true
}).html(u);
var $desc = $("<form:input>").attr({
path: "graphicDesc",
disabled: true
}).html(d);
$("#listGraphic").append($url, "<br />", $desc, "<br /><br />");
}
});
}
$("button#insertFoto").button().click(function() {
$('#insertPhoto').dialog("open");
return false;
});
$('#insertPhoto').dialog({
autoOpen: false,
buttons: {
"Close": function() {
$(this).dialog("close");
},
'Insert': function() {
addPhoto($("#graphicUrl").val(), $("#graphicDesc").val());
// Reset values
$("#graphicUrl").val("");
$("#graphicDesc").val("");
// Close Dialog
$(this).dialog("close");
}
}
});
});

How to call an AJAX function on anchor tag?

I'm using PHP, jQuery, AJAX, Smarty for my website. I'm having following line of code from smarty template. I wan to call the jQuery AJAX function on the onclick of that hyperlink but I'm not able to call it. Can you help me in giving call to the jQuery AJAX function?
Following is my code.
Code from Smarty template:
<a class="edit_user_transaction_status" href="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}">Update</a>
jQuery AJAX function is as follows:
$(".edit_user_transaction_status").click(function(e) {
e.preventDefault();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('href');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
});
If I try to print the alert at the beginning of function it's not getting printed. Can you help me in achieving this? Thanks in advance.
Corrected Code:
$(".edit_user_transaction_status").click(function(e) {
e.preventDefault();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('href');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
Note: Remove }); from the last line.

Update row in WebGrid with JQuery

FOUND THE PROBLEM:
Just needed to replace row.replaceWith with row.parent().parent().replaceWith().
I'm trying to update a WebGrid row with JQuery after I've clicked a submit button in a modal dialog, but the updated data just append the last column, not the whole row as I want.
Let's say I want the table to look like this after the update:
ID - Name - Phone number
But with my code it looks like this after the update:
ID - Name - ID - Name - Phone number
as it just replaces the last column with a new table within the last column with the updated data.
I'm getting the correct data as output, but in the wrong place in the row.
Please help! :)
Here is the Javascript code:
$(function () {
$("#edit-event-dialog").dialog({
resizable: false,
height: 300,
modal: true,
autoOpen: false,
open: function (event, ui) {
var objectid = $(this).data('id');
$('#edit-event-dialog').load("/Events/CreateEditPartial", { id: objectid });
},
buttons: {
"Save": function () {
var ai = {
EventID: $(this).data('id'),
Name: $("#Name").val(),
Phone: $("#Phone").val()
};
var json = $.toJSON(ai);
var row = $(this).data('row');
$.ajax({
url: $(this).data('url'),
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
var grid = $(".pretty-table");
row.replaceWith('<tr><td>' + data.ev.EventID + '</td><td>' +
data.ev.Name + '</td><td>' + data.ev.Phone + '</td></tr>');
},
error: function (data) {
var data = data;
alert("Error");
}
});
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#event-edit-btn").live("click", function () {
var url = $(this).attr('controller');
var row = $(this);
var id = $(this).attr('objectid');
$("#edit-event-dialog")
.data('id', id)
.data('url', url)
.data('row', row)
.dialog('open');
event.stopPropagation();
return true;
});
You have set row to $(this) which is your case represents $("#event-edit-btn") ( btw i suggest using classes as identifiers, but it's not a problem ). Later on you replace your actual button with the new <tr> set but what you actually need to do is traverse to the tr parent of that button and replace it.
Change your live handler to:
$("#event-edit-btn").live("click", function () {
var url = $(this).attr('controller');
var row = $(this).closest('tr'); //or use some #id or .class assigned to that element
var id = $(this).attr('objectid');
$("#edit-event-dialog")
.data('id', id)
.data('url', url)
.data('row', row )
.dialog('open');
event.stopPropagation();
return true;
});

Categories

Resources