jQuery dialog: how to prevent closing the dialog + an extra get request! - javascript

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;},

Related

Javascript Sweetalert is sending form multiple times

my following javascript function is sending the form multiple times.
4 to 9 posts at the same time and I cannot get it right now.
Here is the function:
function formModal(url, id, type, text, send_type) {
$(document).ready(function () {
$('#' + id).on('submit', function (e) { //id of form
$.ajax({
url: url, // PHP file
data: $(this).serialize(),
type: send_type,
success: function (data) {
console.log(data);
// Success Alert
swal({
html: true,
title: text,
type: type,
timer: 1500,
showConfirmButton: false
});
setTimeout(function () {
// Refresh after 2 seconds
window.location.href = "";
}, 2200);
},
error: function (data) {
//Error Alert
swal("Oops...", "Something went wrong :(", "error");
}
});
e.preventDefault(); //This is to Avoid Page Refresh and Fire the Event "Click"
});
});
};
The function will be used in a HTML/ PHP Script:
<script> formModal('/dashboard_scripts/module/wiki/edit_wiki_article.php', 'edit_article', 'success', 'Artikel wurde gespeichert', 'GET') </script>
what are you doing in your code , why $(document).ready() inside the function formModal() and then inside that $(document).ready() you are binding submit handler which means every time you call the formModal() you are binding a submit event handler and thats the main reason of multiple submits of the form. you should either remove the submit handler from the function and make a simple ajax call or change
$('#'+id).on('submit', function (e) {
to
$('#'+id).off('submit').on('submit', function (e) {
Sweet Alert has nothing to do with the multiple submits of your form

Jquery ajax button click event firing twice?

I have a Employee page which shows list of employees with an edit option. On clicking the edit button jquery-ajax is used to fetch the data from the server.
The problem is when I click the edit button the event is firing twice.
I am using a seperate js file and is referring the file to the main page.The script was working fine until i moved it to the seperate js file.
The Jquery script is
//ajaxGet on edit button click
$(document).on('click', '.editRole', ajaxGet);
var ajaxGet = function (e) {
var spinner = $(this).parent('div').find('.spinner');
var href = $("#editMenuSettings").data("url");
var menuRoleId = $(this).data('id');
spinner.toggle(true);
var options = {
type: "GET",
url: href,
data: { menuRoleId: menuRoleId }
};
$.ajax(options).success(function (data) {
spinner.toggle(false);
$(".modal-body").html(data);
$(".modal").modal({
backdrop: 'static'
});
});
$.ajax(options).error(function (data) {
spinner.toggle(false);
toastr.error("Oops..Some thing gone wrong");
});
return false;
};
You call $.ajax twice.
At lines
$.ajax(options).success(function(data)...
$.ajax(options).error(function(data)...
you actually make two different AJAX calls - one with success callback only, another one with error callback.
In your case, your call should look like this:
var options = {
type: "GET",
url: href,
data: { menuRoleId: menuRoleId }
};
$.ajax(options)
.success(function (data) {
spinner.toggle(false);
$(".modal-body").html(data);
$(".modal").modal({
backdrop: 'static'
});
})
.error(function (data) {
spinner.toggle(false);
toastr.error("Oops..Some thing gone wrong");
});
return false;
It will set both callbacks to the single AJAX call and execute this one.

Javascript onclick change button text for a few seconds

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.

Updating drop down from json message, code not working

my json response is
["Day", "Week"]
and the jquery which is supposed to run is
$("#id_granularity").click(function(event)
{
event.preventDefault();
var $form1=$('#dashboardForm')
var $success2 = function(data)
{
$("id_granularity").empty();
$.each(data,function(i,value)
{
alert("hello");
$("id_granularity").append($('<option>').text(value).attr('value',value));
});
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr,settings) {
xhr.setRequestHeader('X-CSRFToken',csrftoken);
}
});
var dposting = $.post("/grain", $form1.serialize(), $success2, "json");
});
the event occurs but the dropdown is not updating or new items are not getting appended to
id_granularity
Change all instances of $("id_granularity") to $("#id_granularity") and see how that goes

Get data from the server and display in the Edit Form

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

Categories