I have a dialog box that loads a partial view, called from a number of different views in my MVC 4 app. It has a text area and a small notice of how many characters are remaining in the text area. All works fine on page load, however when the dialog box is closed, whether by the send button or the close button in the dialog titlebar, when it is reopened the '#textarea_feedback' div content disappears until a page reload. I believe I should be using dialog('destroy') but cannot seem to get the syntax right. Either it has no effect or it displays the partialview at the bottom of the page. Please advise, hope I've included enough code to identify the issue. Thanx
$(document).ready(function () {
var text_max = 160;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#txtMessage').keyup(function () {
var text_length = $('#txtMessage').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
$('#send').click(function (e) {
if ($('#txtSMSMessage').val().trim()) {
e.preventDefault();
$.ajax({
type: "POST",
data: $('form#Composer').serialize(),
url: '/MyController/MyAction',
success: function (data) {
alert('Sent');
$('#Composer').closest("div.ui-dialog-content").dialog("close");
},
error: function (a, b, c) {
$("#Composer").unblock();
alert(b);
}
});
//$('#Composer').closest("div.ui-dialog-content").dialog("destroy");
}
});
//var dialog = $('#Composer').closest("div.ui-dialog-content").dialog();
//console.debug(dialog);
//dialog.on("dialogbeforeclose", function (event, ui) {
// dialog.dialog('destroy')
//});
});
Wanted to post answer in case it could help someone else, really was LShetty's comment that lead me in the right direction. Added to the CLOSE function of the Ajax call that created the dialog box:
$.ajax({
url:
...
type: "POST",
success: function (responseText, textStatus, XMLHttpRequest) {
dialog.html(responseText);
dialog.dialog({
...
title: 'Send message',
open: function () {
...
},
close: function () {
$(this).dialog('destroy').remove()
},
...
});
}
Related
I've created a news system, where i should be able to edit articles dynamically without redirect, from a modal. Also, i should be able to delete and create articles.
When something is changed, jQuery Load is called, but the problem is when i have to edit the loaded content.
$("#toolbox-items").load('inc-toolbox');
The above code loads the articles (the file is called inc-toolbox on purpose and works fine).
$(function () {
$('form').on('submit', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});
But, when ever something has to be edited or deleted, the whole page reloads and nothing changes, although i'm still able to add things.
The add-button is not loaded dynamically from the script, but is in there from the start.
What in the world might the problem be?
Try code like this
$(function () {
$(document).on('submit','form', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});
Trying to change the text on a button to processing for a few seconds when it is click
<div id="send"></div>
<button id="button">Send</button>
<script>
$(document).on("click", "#button", function() {
var Path = $('#send').html();
var success = function() { alert("Successful"); };
var error = function(message) { alert("Oopsie! " + message); };
</script>
You're close, you just need to do this $('#button').html("Processing");
Then in the success and error functions, you'll probably want to modify the button text to something else so that it no longer displays "Processing".
This is what you are probably looking for:
$(document).on("click", "#button", function() {
var defaultBtnValue = $('#send').html();
$('#send').html("Processing...");
$.ajax({
url: your_url,
type: "GET",
success: function() {
alert("Successful");
},
error: function(message) {
alert("Oopsie! " + message);
},
complete: function() {
$('#send').html(defaultBtnValue);
}
});
});
I'm assuming you wan't this "Processing" to show while something is.. well, processing, like doing an ajax call (this may be a setTimeout function as well). Good practice is to first save the default value of the button and make sure to reset it once an action is complete (succes or not) in case something goes wrong.
I have a nifty little piece of Ajax code that loads in PHP.
http://www.moneyworrier.com/client-stories/
What happens is that when you click on a menu item on the left-hand navigation, it reloads a Div with content appropriate.
What it does however is loop through previous requests, which is bothersome (Click on any left hand item 3x and you will see what I mean). I think I need to find a function that does the equivalent of exit; and clears any post data.
My call in code is:
Video
And my JS looks like:
$(document).ready(function () {
$('a.media').click(function () {
var usr = $(this).attr('rel');
$("#displaystories").html('Retrieving..');
$.ajax({
type: "POST",
url: "/client-stories/media.php",
data: "showcode=" + usr,
success: function (msg) {
$("#displaystories").ajaxComplete(function (event, request, settings) {
$(this).html(msg);
});
}
});
});
});
You're binding a new listener to ajaxComplete on every click. Your success callback should just be:
success: function(msg) {
$("#displaystories").html(msg);
}
This question is continuation of the following question Add JSON data to the view that unfortunately ended up unresolved yet.
In my main view which has a form with 2 controls and placeholder for flexigrid I added the following at the bottom
<div id="add-edit-dialog" style="display: none" title="Add / Edit Client">
#Html.Partial("_ClientForm", Model)
</div>
The flexigrid pluglin instantiates in run-time and adds 3 buttons: Add, Edit, Delete.
For Edit button I need to get the current row information from the server and then display it in the Form. For Add button I do not need to go to the server (I think).
This is my current code for the Edit button:
function edit(com, grid) {
$('.trSelected', grid).each(function () {
var id = $(this).attr('id');
id = id.substring(id.lastIndexOf('row') + 3);
currentId = id;
$('#fntype').val('Edit');
var ClientName;
ClientName =$('.trSelected td:eq(2)').text();
var url = '/Client/Edit/' + id ;
$.getJSON(url, function (html) {
// setFormControls(data.Id, data.Role, data.Location, data.JobType,
// data.Description);
// alert(data);
$($dlg).html(html);
});
//location.replace(url);
RunModalDialog("Edit Client: " + ClientName);
});
So, it is going to Edit controller action and returns that same partial view _ClientForm with correct information passed as a model. If I look at the response result returned in FireBug I can see that the returned HTML is correct and all the textboxes have correct information in their values.
However, the dialog that opens looks exactly the same as the dialog for the Add button - in other words, all form controls come blank. I can not figure out what is wrong and why it is not working the way I want it.
This is what I have for the RunModalDialog:
var validator = $("#add-edit-form").validate();
var $dlg = $("#add-edit-dialog").dialog({
autoOpen: false,
show: "blind",
closeOnEscape: true,
resizable: true,
width: 1200,
height: 750,
minHeight: 600,
minWidth: 950,
buttons: {
"Save": function () {
if ($("#add-edit-form").valid()) {
// jobPost.setVals(txtId.val(), txtRole.val(),
// txtLocation.val(), txtJobType.val(),
// txtDescription.val());
$.ajax({
type: 'POST',
//data: JSON.stringify(clientInformation),
url: '/Client/Save',
dataType: 'json',
contentType: 'application/json',
success: function (result) {
// insert new list into grid
$('#flexClients').flexAddData(result);
}
});
$(this).dialog('close');
} else return false;
},
Cancel: function () {
$(this).dialog("close");
clearForm();
if (validator)
validator.resetForm();
}
},
close: function () {
clearForm();
},
open: function () {
//$("#add-edit-dialog").parent().appendTo($("#add-edit-form"));
}
});
function RunModalDialog(title, url) {
if (title) {
$dlg.dialog("option", {"title": title });
}
if (url) {
$dlg.load(url).dialog("option", { "title": title }).dialog("open");
//$dlg.load(url, function () {
// var validator = $("#sform").validate();
// if (validator)
// validator.resetForm();
// $dlg.dialog("option", { "title": title }).dialog("open");
//});
} else {
$dlg.dialog("open");
}
}
The code with the load (and commented code) was another attempt to solve this problem. That sort of worked (the form displayed with the info), but the main Client view was also reloaded so I was seeing double grid.
Do you see what should I change in my code to get this thing working?
Thanks a lot in advance.
With Jazzen Chen from MS help we solved this problem. All I needed to do to display the data correctly was to change getJSON to just get jquery function. Now my form comes with data populated correctly and the next challenge will be to save the data.
I posted a blog post with what I have so far - hope it may help
http://blogs.lessthandot.com/index.php/WebDev/UIDevelopment/AJAX/asp-net-mvc-project-with
The work flow:
user click the button, a dialog box opens with a search form. An ajax post request is sent to the server, and get a json response. I get the callback on success handler. Now two issues.
the dialog closes upon success callback (successFn). I get the json response in the success call back, and I want the user to see the result and press close button to terminate the dialog,.
Soon after the dialog closes, a get request is sent to server. After closing the dialog by itself, the url is like http://localhost:8080/search?query= . I do not send any GET request explicitly
jQuery(document).ready( function(){
jQuery("#myButton").click( showDialog );
$myWindow = jQuery('#myDiv');
$myWindow.dialog({ width: 400, autoOpen:false, title:'Hello World',
overlay: { opacity: 0.5, background: 'black'},
modal: true,
/*open: function (type, data) {
// include modal into form
$(this).parent().appendTo($("form:first"));
}, */
buttons: {
"Submit Form": function() { $('form#myform').submit();},
"Cancel": function() {$(this).dialog("close");}
}
});
});
var showDialog = function() {
$myWindow.show();
$myWindow.dialog("open");
}
var closeDialog = function() {
$myWindow.dialog("close");
}
var successFn = function (response) {
var obj = JSON.parse(response);
$("#result").html('').html(obj.name);
}
var errorFn = function (xhr, ajaxOptions, thrownError){
$("#myform").parent().html('').html(xhr.statusText);
}
var query = $("input#query").val();
var dataString = 'query='+ query ;
$('form#myform').submit(function(){
$.ajax({
type: 'post',
dataType: 'json',
url: '/search',
async: false,
data: $("#myform").serialize(),
success: successFn,
error: errorFn
});
});
It would be a good idea to add method="post" to your form to avoid any accidental GET data being sent.
Adding return false; to the success function may stop the dialog from closing. I'll test this if I can.
Edit: also check that all your code is inside jQuery(document).ready( function(){
Hope that helps!
I think you just need to add return false.
"Submit Form": function() { $('form#myform').submit(); return false;},