Two near-identical forms functioning differently - forms

I have two nearly identical forms on two different pages which take in a user's name and email address. When I press the submit button, both of them call a validator, which works correctly, and then both are supposed to make an Ajax call and display the results. At this point, one of them makes the call successfully, and the other simply refreshes the page. I'm not sure what the difference is that causes one to work successfully and the other to fail. With the one that works, I already had this problem once with the form that works, which was caused by me generating the form through javascript. I have no idea what is causing it now. Here is the inline code for the functioning one:
<!--// MODAL: INVITE //-->
<div id="inviteModal" class="modal" style="display: none">
<div class="response"></div>
<form id="inviteForm" >
<script type="text/javascript" src="/includes/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var invites = <?php echo $user->getInvitesLeft(); ?>;
</script>
</form>
</div>
Response is where it displays the response from the Ajax call. I have to generate the content later on using Javascript because I take different actions depending on the value of invites. I was originally generating the whole thing, but I found that I had to have the form tags in place to prevent the refreshing problem the first time. Here is the code that generates the form the user sees:
if(invites < 1){
$("#inviteModal").html("You have no invites left. You can get more by increasing your score.");
}
else{
$("#inviteForm").html("<h2>Please enter the specified information for the friend you wish to invite. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
$("#inviteModal").css('display', "block");
$("#overlay").css("display", "block");
And here is the validator function:
$("#inviteForm").validate({
//Rules for invite validation
rules: {
first: "required",
email: {
required: true,
email: true
}
},
//Messages to print if validation fails
messages: {
first: "Please provide your friend's name.",
email: "We cannot contact your friend without a valid email address.",
},
//What to do when validation succeeds
submitHandler: function(form) {
//Form is valid, make Ajax call
$.ajax({
type: "POST",
url: '/invite/process',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
if(data.indexOf("Thank you") >= 0 ){
$("#inviteModal .response").text(data);
invites -=1;
}
else{
$("#inviteModal .response").text(data);
}
}
}); //End ajax
} //End submitHandler
}); //End validator
As I said, this one works perfectly fine. The only difference between this one and the one that refreshes is that the non-functioning one is on a page that you don't have to be logged in to see, and takes different actions depending on whether or not a user is logged in. Here is the inline code:
<!--// MODAL: INVITE //-->
<div id="inviteModal" class="modal" style="display: none">
<div class="response"></div>
<form id="inviteForm" >
<script type="text/javascript" src="/includes/js/jquery-1.7.2.min.js"></script>
<?php
if(!$user || $user == null){ //No user logged in, display invite request form instead
$loggedin = false;
}
else{ //Allow user to invite friends
$loggedin = true;
}
?>
</form>
Here is the generation code, almost identical except for one extra if layer:
if(!loggedin){
$("#inviteForm").html("<h2>Please enter the specified information to request an invitation. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
else{
invites = <?php echo $user->getInvitesLeft(); ?>;
if(invites < 1){
$("#inviteModal").html("You have no invites left. You can get more by increasing your score.");
}
else{
$("#inviteForm").html("<h2>Please enter the specified information for the friend you wish to invite. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
}
$("#inviteModal").css('display', "block");
$("#overlay").css("display", "block");
And here is the validator:
$("#inviteForm").validate({
//Rules for invite validation
rules: {
first: "required",
email: {
required: true,
email: true
}
},
//Messages to print if validation fails
messages: {
first: "Please provide your friend's name.",
email: "We cannot contact your friend without a valid email address.",
},
//What to do when validation succeeds
submitHandler: function(form) {
//Form is valid, make Ajax call
if(loggedIn){ //They are inviting a friend
$.ajax({
type: "POST",
url: '/invite/process',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
if(data.indexOf("Thank you") >= 0 ){
$("#inviteModal .response").text(data);
invites -=1;
//$("#overlay").css("display", "none");
//$("#inviteModal").fadeOut(5000);
}
else{
$("#inviteModal .response").text(data);
}
return false;
}
}); //End Ajax
}
else{ //They are requesting an invite for theirself
$.ajax({
type: "POST",
url: '/invite/request',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
$("#inviteModal .response").text(data);
return false;
}
}); //End ajax
}
return false;
} //End submitHandler
}); //End validate
Again almost identical except for one extra layer of if. So why would the bottom one refresh the page instead of making the Ajax call while the first one works perfectly fine?

how about commenting out those return false statement in the ajax success callback functions for the second one?

Related

my website posts forms on http but not on https

hello I'm in the process of converting my HTTP website to https but after getting https to work no post request from forms work
I have looked around a lot but nothing really describes what I have going on here, I doubt it nginx because when I start burp suite and make the website server HTTP it sends a post request like usual, but when I run it on https the post request isn't even sent doesn't show anything on the burp suite logs
<form action="" method="post" autocomplete="off">
<p><input type="text" name=username id="username">:username
<p><input type="password" name=password id="password">:password
<p><input type="checkbox" name = "rmbm" id="rmbm">
<label for = "rmbm">remember me</label>
<p><input type=submit value=Login>
forgot password?
</form>
this is my form but I don't even see a post request
I should see a post request but I don't on burp sute
update:
hello, I've just had an epiphany. could it be the service worker and yes I was right after unregistering the service worker it worked perfectly so the problem is the service worker.
knowing this I will post the code
my service worker:
console.log('Hello from sw.js');
'use strict';
var cacheVersion = 1;
var currentCache = {
offline: 'offline-cache' + cacheVersion
};
this.addEventListener('install', event => {
event.waitUntil(
caches.open(currentCache.offline).then(function(cache) {
return cache.addAll([
'/static/html/offline.html',
'/sw.js'
]);
})
);
});
this.addEventListener('fetch', event => {
console.log("fetching");
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request.url).catch(error => {
// Return the offline page
return caches.match('/static/html/offline.html');
})
);
}
else{
event.respondWith(caches.match(event.request)
.then(function (response) {
return response || fetch(event.request);
})
);
}
});
now looking at my code it just dosnt handle post request
so i will try to fix this on my own

SAILS - How to close modal with ajax-form after receiving "notFound" error from action

So, I am using Sailsjs - and I am using a modal form to confirm deletion of an item. What I want to do is to detect a double deletion (someone deleted an item - while it was in someone else's page - and the second person tries to delete it too).
I managed to do that - my action is returning "notFound".
The problem is - how can I make the Modal close when getting "notFound" back from the action instead of success?
Here is an excerpt of my action code:
exits: {
forbidden: {
description: 'The user making this request is not the owner of this thing and therefore cannot delete it.',
responseType: 'forbidden'
},
notFound: {
description: 'The item was not found in the database. Maybe it has already been deleted?',
responseType: 'notFound'
}
},
fn: async function (inputs, exits) {
var thing = await Thing.findOne({
id: inputs.id
});
if (!thing) {
throw 'notFound';
}
if (thing) {
if (thing.owner !== this.req.me.id ) {
throw 'forbidden';
}
}
await Thing.destroy({ id: inputs.id });
return exits.success();
}
and here is an excerpt of my modal using ajax-form component:
<% /* Confirm DeleteThing Modal */%>
<modal v-if="confirmDeleteThingModalOpen" #close="closeDeleteThingModal()">
<ajax-form action="destroyOneThing" :syncing.sync="syncing" :cloud-error.sync="cloudError" :handle-parsing.sync="handleParsingDeleteThingForm" #submitted="submittedDeleteThingForm()">
<div class="modal-header">
<h3 class="modal-title">Are you sure?</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
You can use #rejected on your ajax-form. So somethinglike:
<ajax-form action="destroyOneThing" #rejected="rejectedDeleteOneThing"
Then tell it what you want it to do on your page script
something like:
rejectedDeleteOneThing: function() {
this.confirmDeleteThingModalVisible = false;
}

Form - new page on submit button

Last year i build a form for one of our costumers, when visitors submitted the form they
got a message on the same page. But now he asks me if it is possible to
make a succes page if the form is filled in correctly.
I can't make it work. It's a bit out of my league.
So i hope anyone of you can help me out!
$(document).ready(function() {
$("#ajax-contact-form").submit(function() {
$('#load').append('<center><img src="ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
var fem = $(this).serialize(),
note = $('#note');
$.ajax({
type: "POST",
url: "contact/contact2.php",
data: fem,
success: function(msg) {
if ( note.height() ) {
note.slideUp(500, function() { $(this).hide(); });
}
else note.hide();
$('#loading').fadeOut(300, function() {
$(this).remove();
// Message Sent? Show the 'Thank You' message and hide the form
result = (msg === 'OK') ? '<div class="success">Uw bericht is verzonden, we nemen z.s.m. contact met u op!</div>' : msg;
var i = setInterval(function() {
if ( !note.is(':visible') ) {
note.html(result).slideDown(500);
clearInterval(i);
}
}, 40);
}); // end loading image fadeOut
}
});
return false;
});
<form id="ajax-contact-form" target="_blank" method="post" action="javascript:alert('success!');" >
Instead of displaying the "success" message, redirect to a new page:
window.location = successPageUrl;
Just redirect to success page after ajax success.

AngularJS ignores form submit

I'm using AngularJS v1.2.13 to create a page with a form which will download a user's file on click.
I'm using $sce to enable the injection of the file URL which works fine.
However, the loading of the resource disables the form submit. I'm sure it has to do with the resource load because when I remove the load and hardcode the url it works fine. I've also created a JSFiddle without it and have not been able to reproduce the problem there.
Any ideas on why this is happening and how it can be fixed?
HTML:
<div ng-controller="viewProfileController" data-ng-init="findOne();">
<form method="get" action="{{downloadFileURL}}">
<button type="submit" class="no-button comment-small" >
Download File
</button>
</form>
</div>
Controller:
'use strict';
angular.module('bop.viewProfile').controller('viewProfileController', [
'$scope', 'Users', '$sce', '$routeParams',
function($scope, Users, $sce, $routeParams) {
$scope.downloadFileURL = '';
// Find current user
$scope.findOne = function() {
Users.get({
userId: $routeParams.userId
}, function(user) {
$scope.user = user;
$scope.downloadFileURL = $sce.trustAsResourceUrl($scope.user.file.url);
});
};
}]);
Users Service:
var userServices = angular.module('bop.users', ['ngResource']);
userServices.factory('Users', ['$resource', function($resource) {
return $resource(
'users/:userId',
{ userId: '#_id' },
{ update: { method: 'PUT' } }
);
}]);

Jquery, Validate, Submit Form to PHP (Ajax Problem)

Very early days playing Javascript, Jquery and Validate.
I am using the Submit Button onClick method for form submission.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using the submit, in case no data or not every field has been tested.
The logic is working, but the AJAX call does not appear to be working. I have stripped down the PHP to
<?php
touch('phpTouch.txt');
phpinfo();
sleep(30;)
?>
The javascript is
$(document).ready(function () {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form() ) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
$.ajax({
url: "testPHP.php",
type: "POST",
data: frmData,
dataType: "json",
success: function () {
alert("SUCCESS:");
},
error: function () {
alert("ERROR: ");
}
});
} else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
return false; // Prevent the default SUBMIT function occurring (is this a fact ??)
};
Can anyone advise as to what I am doing wrong.
Thanks
Do these things
Change onClick="submitForm()" on the HTML markup to onclick="submitForm(event)"
Now change the submitForm function like this.
function submitForm(evt) {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').valid() ) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
$.ajax({
url: "testPHP.php",
type: "POST",
data: frmData,
contentType: "application/json;",
success: function () {
alert("SUCCESS:");
},
error: function (a, b, c) {
alert(a.statusText);
}
});
} else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
evt.preventDefault();
};
Please note these things
Check .valid() to determine form validity
Call .preventDefault() instead of return false; ( Its more jQuery-ish )