PWA doesn't execute jQuery form on success event every time - events

I have a working installable PWA. Here's my service worker's fetch code:
self.addEventListener('fetch', async e => {
e.respondWith(
fetch(e.request)
.catch(error => {
console.log(error);
return caches.match(e.request) ;
})
);
});
In another JS file I have form handling logic (this file also registers the service worker):
$("#myForm").submit(function (e) {
console.log("form submit");
let url = $(this).attr("action");
let method = $(this).attr("method");
let data = $(this).serialize();
$.ajax({
type: method,
url: url,
data: data,
success: function (response) {
console.log("SUCCESS");
},
error: function(err) {
console.log(err);
}
});
});
The problem is that sometimes the form callback is not triggered, but the form submission is triggered every time (based on the "form submit" in console).

I think figured it out. I forgot to disable the generic form submission event.
I added this in the event handling:
e.preventDefault();

Related

WordPress ajax call with add_filter

I have a WordPress function that works exactly how I want. The function below changes the email recipient in Contact Form 7 to abc#aol.com.
Now I need to use AJAX to update the email recipient to a dynamic value.
function wpcf7_dynamic_email_field($args) {
if(!empty($args['recipient'])) {
$args['recipient'] = str_replace('%admin%', 'abc#aol.com', $args['recipient']);
return $args;
}
return false;
}
add_filter('wpcf7_mail_components', 'wpcf7_dynamic_email_field');
Here's my AJAX call. I do not know how to tell the call to initiate the wpcf7_dynamic_email_field() function. Can that be done?
$.ajax({
url: ajaxurl, // or example_ajax_obj.ajaxurl if using on frontend
data: {
'action': 'update_team_page_contact_form',
'emailAddress' : emailAddress
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});

mootools ajax request aborts sporadically (onFailure)

I have a javascript function called when the page loads. It just gets some user data through an ajax call and checks some checkboxes based on the user id's returned.
window.onload=function(){
getBlockedUsers();
}
function getBlockedUsers(){
var deptID = $('deptID').value;
var request_data = 'DeptID='+deptID;
var req = new Request.JSON({
url:'/ajax/getuserData.cfm',
method: 'post',
noCahe: true,
data: request_data,
onSuccess: function(response)
{
var jLength = response.json.length;
for(i=0;i<jLength;i++){
var user_id = response.json[i].id;
if($('user_'+user_id)){
$('user_'+user_id).checked = true;
}
}
},
onFailure: function (xhr)
{
alert('There was an error while trying to fetch data');
},
onException: function (xhr)
{
alert('There was an exception while trying to fetch data');
}
}).send();
}
I keep getting the alert in the onFailure() function for some reason and when I inspect the ajax call, it appears to be aborted. This does not happen all the time. Happens in IE9.
I had the function call within domReady but moved to onload thinking it would help but it's still the same. Any ideas on why this might be happening would really help.

Bind event after login

I have made a filter called auth that check if user is logged. If is not logged it redirect on the main page but if is a call ajax? I just checked if is it. If it is i just send an json status "no-log". Now i received my json response "no-log" on my client and i would like open a modal for ask login and password. The solution that i thougth was put easily for each ajax request an if statement to check if the response status is "no-log" and show the function of modal. BUT OF COURSE is not good for future update, I'm looking for a good solution where i can bind this event and if i want on the future add other status. Any suggest?
Route::filter('auth', function()
{
if (Auth::guest()) {
if ( !Request::ajax() ) {
Session::put('loginRedirect', Request::url());
return Redirect::to('/');
} else {
$status = "no-log";
return json_encode(array('status' => $status));
}
}
});
A example of call ajax
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
$.ajax({
type: "POST",
url: '/delete_post/' + USER,
data: { id_post: id_post.attr('id') },
beforeSend: function(request) {
return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
},
success: function(response) {
if (response.status == "success") {
id_post.parents('div.shared_box').fadeOut();
}
},
error: function(){
alert('error ajax');
}
});
} else {
console.log("close");
}
});
});
After 10 days of exploring an idea I found a way to override ajax comportment:
It just need you replace every $.ajax() by a custom one.
If I re-use your code:
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
myCustomAjax({ // In place of $.ajax({
type: "POST",
...
Then this custom function allow you to add some action before or after each ajax callback:
For instance checking the JSON return value in order to decide if I trigger the success callback or I show a warning:
function myCustomAjax(options) {
var temporaryVariable = options.success;
options.success = function (data, textStatus, jqXHR) {
// Here you can check jqXHR.responseText which contain your JSON reponse.
// And do whatever you want
// If everithing is OK you can also decide to continue with the previous succeed callback
if (typeof temporaryVariable === 'function')
temporaryVariable(data, textStatus, jqXHR);
};
return $.ajax(options);
}
If you return a 401 for all not loggedin requests, you can use $.ajaxSetup to handle all ajax errors in your application.
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status == 401) {
window.location = 'your-login-page';
}
}
});

Call ajax inside a custom method and return ajax result to called method

in my JSP I have link and button, for both I want to call Ajax action and use with result.
I am creating events for both link and button and calls Ajax. I need to return the result to the calling method.
//event for button
$(document).on('click', ".addComponent", function(){
var htmlContent=$(this).html();
$('.addComponent').html('Loading...').fadeIn();
var urlAction=$(this).attr("id");
var dataFields=$(this).data('val');
var data=callActionUsingAjax(urlAction, dataFields); //data not returning from ajax
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
return false;
});
//event for link
$(document).on('click', "#dimComponentList >TBODY > TR > TD > a", function(){
$("body").css("cursor", "progress");
var urlAction=$(this).attr("href");
var dataFields="";
var data=callActionUsingAjax(urlAction, dataFields);
var ajaxActionResult=ajaxResult(data); //ajax not returning data
$("body").css("cursor", "auto");
$('#applicationList').html(ajaxActionResult);
return false;
});
Here is my method to call Ajax
function callActionUsingAjax(urlAction,datafields)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
return data;
}
});
}
I tried this link but I don't know how to use call back on my custom method like that. There are some other events also I need to call this Ajax. That's why I used Ajax inside a custom method.
Can anyone give me a solution?
The Ajax call is asynchronous and takes its time to complete, while the execution goes on and that's why you don't have any data in the "return".
You need to pass a callback function to your callActionUsingAjax and call it in your success handler (or complete or error that depends on the logic.
Like this:
$(document).on('click', ".addComponent", function(){
//... other stuff
callActionUsingAjax(urlAction, dataFields, function (data) { //this is tha callback (third argument)
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
// all of the above happens when ajax completes, not immediately.
});
return false;
});
function callActionUsingAjax(urlAction, datafields, callback)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
callback(data);
}
});
}

Adding autoresize to server side generated textarea using jQuery

Am using a plugin called "jQuery Autosize!" on my textareas. How can i make it autoresize my server side generated textareas because they generated when the page has already loaded.
This is the code that generates the server side textareas. resultErrorObj.node_html contains the server side generated textarea as shown below.
$(document).ready(function() {
$("#postUpdate").submit(function(event){
// setup some local variables
var $form = $(this),
// let's select and cache all the fields
$inputs = $form.find("input"),
// serialize the data in the form
serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.attr("disabled", "disabled");
// fire off the request to /form.php
$.ajax({
url: base_url + "ajax/post_status_update",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
var resultErrorObj = jQuery.parseJSON(response);
if (resultErrorObj.status == 1)
{ $(resultErrorObj.node_html).hide().insertAfter('#activitiesStream').slideDown('fast');
}
else
{
alert(resultErrorObj.error);
}
},
// callback handler that will be called on error
error: function(jqXHR, textStatus, errorThrown){
// the error
alert("Error here " + errorThrown);
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
// prevent default posting of form
event.preventDefault();
});
});
Thank you!
The website for Autosize (http://jacklmoore.com/autosize) shows that you can manually trigger the autosizing.

Resources