Im trying to send multiple pieces of information via a form submit. On this submit I would like to return false (cancel page request as it has been ajax) and close the form. Unfortunately close seems to also do return, true i assume.
So that the post request doesn't fail. This leaves the dialog still on the screen.
And if I call $("#dialog-form").dialog("close"); then return false does not run and the page changes.
If anyone knows how to fix this or if im doing something wrong it would be very helpful:
javascript:
$('#modifyConsoleForm').submit(function(evt) {
$.ajax({
type : 'POST',
url : jQuery("#modifyConsoleForm").attr("action"),
data : jQuery(this).serialize(),
dataType : "json",
success : function(data) {
hideError();
},
error : function(data) {
setError('modify of console failed');
}
});
$("#dialog-form").dialog("close");
return false;
});
and my dialog initialisation:
$("#dialog-form").dialog({
autoOpen : false,
height : 300,
width : 350,
modal : true,
close : function() {
allFields.val("").removeClass("ui-state-error");
}
});
I have also tried always returning false in the dialogs close but it didnt seem to work.
Am I missing something?
Try using event.preventDefault() to stop the page changing
eg:
$('#modifyConsoleForm').submit(function(evt) {
evt.preventDefault();
$.ajax({
type : 'POST',
url : jQuery("#modifyConsoleForm").attr("action"),
data : jQuery(this).serialize(),
dataType : "json",
success : function(data) {
hideError();
},
error : function(data) {
setError('modify of console failed');
}
});
$("#dialog-form").dialog("close");
return false;
});
Closing the dialog and returning true/false should be done when the ajax request has been finished, in the success and error functions.
It is also wise that you put an activity indicator while you run ajax requests and hide/remove it once you got the response from the server, this way users know that there is a process going on.
Related
I have a project which involves live notification. So I stumbled upon using socket io but I didn't have enough time to learn it yet. So I tried doing it with AJAX and jQuery. Below is my code structure and I was wondering if this is gonna work with no drawbacks?
setInterval(function(){
if( !element.hasClass('processing') ){
element.addClass('processing');
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {},
success: function( response ){
/* Success! */
element.removeClass('processing');
}
});
}
}, 2500);
Some Extra Info
The way you described will work. From Experience I would just like to point out some things.
I usually do a recursive function, allows you to wait your interval between ajax calls and not a fixed rate. //OPTIONAL BUT DOES GIVE THE SERVER SOME BREATHING ROOM.
Use window.setTimeout() with an isActive flag. //ALLOWS YOU TO STOP POLLING FOR WHATEVER REASON, AND BECAUSE FUNCTION IS RECURSIVE START UP AGAIN IF NEED BE
For Sake of being thorough, I found it is always a good idea to handle the error case of the $.ajax() post. You could perhaps display some message telling the user he is no longer connected to the internet etc.
Some Sample Code:
var isActive = true;
$().ready(function () {
//EITHER USE A GLOBAL VAR OR PLACE VAR IN HIDDEN FIELD
//IF FOR WHATEVER REASON YOU WANT TO STOP POLLING
pollServer();
});
function pollServer()
{
if (isActive)
{
window.setTimeout(function () {
$.ajax({
url: "...",
type: "POST",
success: function (result) {
//SUCCESS LOGIC
pollServer();
},
error: function () {
//ERROR HANDLING
pollServer();
}});
}, 2500);
}
}
NOTE
This is just some things I picked up using the exact method you are using, It seems that Web Sockets could be the better option and I will be diving into that in the near future.
Please refer :
Jquery : Ajax : How can I show loading dialog before start and close after close?
I hope this could help you
$("div.add_post a").click(function(){
var dlg = loadingDialog({modal : true, minHeight : 80, show : true});
dlg.dialog("show");
$.ajax({
url : "/add.php",
complete : function (){
dlg.dialog("hide");
}
});
return false;
});
//--Loading dialog
function loadingDialog(dOpts, text = "пожалуйста подождите, идет загрузка...")
{
var dlg = $("<div><img src='/theme/style/imgs/busy.gif' alt='загрузка'/> "+text+"<div>").dialog(dOpts);
$(".ui-dialog-titlebar").hide();
return dialog;
}
I am using ui-grid to display my table in UI. I have a requirement where I don't want table to auto-save the data. I want user to edit all data in a table and click a button to update all the edited data.
Above behavioud is working fine but only problem what I am getting is whenever a user edits a cell in a row, after few seconds, that cell becomes grey and uneditable. On browser cnsole I am getting this error:
A promise was not returned when saveRow event was raised, either nobody is listening to event, or event handler did not return a promise
Because of above JS error, whole row becomes un-editable.
How to tell ui-grid to don't save the data unless I click my button.
If I handle saveRow event then my button is not working. Please help me in this regard.
Here are the snippets of relevant codes:
var grid = {
data : 'hwData['+key+']',
paginationPageSizes: [25, 50, 75],
paginationPageSize: 25,
enableGridMenu: true,
enableFiltering: true,
enableSelectAll: true,
enableColumnResize : true,
exporterCsvFilename: 'myFile.csv',
exporterMenuPdf: false,
exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
onRegisterApi: function(gridApi){
$scope.gridApi.push(gridApi);
gridApi.edit.on.afterCellEdit($scope,function(rowEntity, colDef, newValue, oldValue){
if(oldValue == newValue){
return false;
}
$("#test").prepend('<font color= "red"> ' +colDef.name+ 'Edited ');
})
},
..............some more code
..............
$.ajax({
type:'POST',
url:'/HardwareInventory/ajax/storage/edit_owned_storage',
data: jsonHostNames,
dataType:"json",
contentType: "application/json; charset=utf-8",
success : function(result){
if(result.status == "Success"){
location.reload(true);
}else{
bootbox.alert("Either hostname is not correct or you don't have permission to edit this team's data");
}
},
statusCode: {
500: function(){
alert("Oops!, there has been an internal error");
}
},
complete: function(result){
}
});
}
});
Set "rowEditWaitInterval :-1" in your grid options and it will never call saveRow method by default , so you can save modified data in your custom method.
And you can access dirtyrows like this
var dirtyRows = $scope.gridApi.rowEdit.getDirtyRows($scope.gridApi.grid);
#Jha : Have a look on below url where I have just added fake save method, which will not save any data until you will define your save function inside it.
http://plnkr.co/edit/T0TLGLpLsk25vY6SUnzR?p=preview
// Save each row data
gridApi.rowEdit.on.saveRow($scope, $scope.saveRow);
$scope.saveRow = function (rowEntity) {
var promise = $q.defer();
$scope.gridApi.rowEdit.setSavePromise(rowEntity, promise.promise);
promise.resolve();
};
The above code will resolve your error"A promise was not returned when saveRow event was raised, either nobody is listening to event, or event handler did not return a promise". Do not forget to add "$q" in controller function. I hope your save function will also work properly.
I m uploading files to server with FormData api and ajax in php-codeigniter. My upload just works fine on file select event..But I want to show a progress bar beside every file that is being uploaded with the updated percentage. My ajax is:
$.ajax({
url : "<?=site_url('admin/commoncontroller/upload')?>",
type : "POST",
beforeSend : function( xhr ) {
xhr.overrideMimeType("text/plain; charset=x-user-defined-binary");
},
processData : false,
cache : false,
contentType : false,
data : fd
}).done(function(res){
alert (res);
})
And I have found two ajax event viz AjaxSend and Complete to put the progress event in but I dont know how would I bind a progress(or any) event to a $.ajax() call. I already used the ajaxSend and Complete like:
$(document).bind("ajaxSend", function(){
$(".easyPieChart").show();
}).bind("ajaxComplete", function(){
$(".easyPieChart").hide();
});
But those events just show a progress bar(it's a canvas) on start end dissappear on complete.. not update in percentage. Any ideas how to do it.. thanks.
Found a way to do this..
$.ajax({ //all prviuos codes and the new things to add as follows:
....
....
xhrFields : {
onprogress: function (e) {
if (e.lengthComputable){
var percentage= Math.round(e.loaded / e.total * 100);
$("#percentage").prop('data-percent',percentage);
$(".percent").text(percentage);
canvas.update(percentage);}
},
onload : function(e){
if (e.lengthComputable){
canvas.update(100);
}
}
},
//Other ajax context here..
});
Thats it my progress is being shown now... :)
I have a form on the following page:
http://mmicet.yazminmedia.com/qseries
(Click the "Keep me updated on the Q" button at the bottom.)
It's a form that uses frmValidator: http://www.javascript-coder.com/. It's basically the same form I'm using successfully on the contact page.
I read on the FancyBox API page that there is a resize function that would resize the modal when new data is added. However, the modal isn't resizing. Instead, my form is getting pushed down and the bottom portion is getting pushed down out of view. (The behavior can be duplicated by simply submitting the form without entering any information in it.)
These are the options I setup for the modal:
$("#qs_button").fancybox({
'titleShow' : false,
'scrolling' : 'no',
'autoDimensions' : false,
'autoScale' : false,
'width' : 600,
'height' : 870,
'showCloseButton': true,
'onClosed' : function() {
$("#login_error").hide();
}
});
I'm firing the resize function on submit of form:
$("#qseries_form").bind("submit", function() {
$.fancybox.resize();
$.ajax({
type : "POST",
cache : false,
url : "/qseries.php",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
return false;
});
Anyone have any ideas why the resize isn't working?
Thanks!
Just a guess, but shouldn't you resize the Fancybox after the data's been put there? Something like:
$("#qseries_form").bind("submit", function() {
$.ajax({
type : "POST",
cache : false,
url : "/qseries.php",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
// resize after data's updated...
$.fancybox.resize();
}
});
return false;
});
Hopefully I'm not completely off the mark here!
Just try with this,
Because this worked in one of my recent project where i have to increase/decrease window size on click of radio button.
$('#fancybox-content').css('height','253px');
I am trying to allow a button to be clicked only once and then some data be submitted via ajax. The problem I am facing is that a user can click 50x and the data is POST submitted each time ?
jQuery("#id").unbind('click');
jQuery.ajax({
type: "POST",
url: ajax_url,
data: ajax_data,
cache: false,
success: function (html) {
location.reload(true);
}
});
How can I ensure that if a user clicks #ID 100x - that the data is only submitted once ? And then #ID is re-enabled ?
You could use the .one() function in jQuery.
jQuery("#id").one('click', function()
{
jQuery.ajax({
type: "POST",
url: ajax_url,
data: ajax_data,
cache: false,
success: function (html) {
location.reload(true);
}
});
});
Bear in mind this will completely remove the click event, even if you have an error with your ajax, you still won't able to click it again.
just disable the button
$("#id").attr("disabled", "disabled")
and then in the success function enable it
$("#id").removeAttr("disabled")
Easiest way would be to use a flag which gets reset when the success is fired:
if(clicked == False){
clicked = True;
jQuery("#id").unbind('click');
jQuery.ajax({
type: "POST",
url: ajax_url,
data: ajax_data,
cache: false,
success: function (html) {
location.reload(true);
clicked = False;
},
error: function () {
alert("Error happened");
clicked = False;
}
});
}
You can disable to control, or use one of the many modal libraries to show the spinning wheel
see this Jquery modal dialog question on SO
You could disable the button on click event and enable it back when ajax request is completed.
In your click event you could disable the button and then re-enable the button in the success function of the ajax event.
Another option would be to set a parameter on the element that is being clicked to indicate the button was clicked and then check to see if it is set if it is don't send the ajax request if not then do send it. Once the ajax is done you can unset the parameter again to allow it to be run.
try this:
$(document).ajaxStart({ function() {
$('#submit_button').click(function(){
return false;
});
});
where: #submit_button is id of the element U want to disable
that code will disable clicking on the submit button