Post [object%20HTMLInputElement] 404 not found on $.ajax submit - javascript

I am having a slight issue trying to implement smoothState.js (https://github.com/miguel-perez/smoothState.js) with my JSP backend.
I get this error when I try to submit the form for the first time. The second time I press submit it goes through, I have no idea what is the cause of it but found a possible clue.
POST http://localhost:8080/internal/inquiry/[object%20HTMLInputElement] 404 (Not Found)
It only happens on the forms that have a hidden input with name="action". For example if I have this in my form:
<input type="hidden" name="action" value="<%=Inquiry.CREATE_ACTION_DESCRIPTION_DATA%>" />
This is the code for my submit.
$(document).ready(function(){
$('#descriptionData').parsley().on('form:success', function() {
var $form = $("#descriptionData");
var action = "<%=Inquiry.CREATE_ACTION_DESCRIPTION_DATA%>";
var formUrl = '/inquiry.do?action=' + action + '&ajax=1';
$form.submit(function (ev) {
$.ajax({
type : "POST",
url : formUrl,
data : $form.serializeArray(),
async : true,
success : function(data) {
var smoothState = $('#main-cont').smoothState().data('smoothState');
smoothState.load(data.redirectPage);
}
});
ev.preventDefault();
});
});
});
Any help would be appreciated.
EDIT: Additional photos
Response on first submit
Response on second submit

it would be great to see some jsp code, but now my guess is that if #descriptionData is actual from, then you'd better be using just $form.serialize() to send data

Related

AJAX call failing to process form

I have an email sign-up form on a website.
The form appears in two areas of each web page: the header and the footer
It's the same exact form, just available on the top and bottom of the page for better UX and accessibility.
The form uses a jQuery/AJAX script to provide success and error responses to the user. (i.e., "Success! Your subscription is complete." and "Error. Please review and re-submit")
The problem I'm having is that the header form processes but the footer form does not.
Any ideas what's wrong with this code? Thanks.
P.S. The form was working perfectly when the header and footer forms each had their own script. The problem started when the scripts were consolidated into one file. I've posted the original scripts at the bottom. Also, nothing has been changed in the PHP, so I don't think the problem is there.
$(function() {
// get the forms
var form = $('#header-form, #footer-form');
// set up event listener
$(form).submit(function(e) {
// disable html submit button
e.preventDefault();
// get the submit button
var submitButton = $('[type=submit]', this);
// get the messages element
var formResponses = $('#header-form-responses, #footer-form-responses', this);
formResponses.text(" ");
// serialize form data
var formData = $(form).serialize();
// disable submit button to prevent unnecessary submission
submitButton.attr('disabled', 'disabled');
// tell users that form is sending
submitButton.text('Processing...');
// submit form via AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// make sure formResponses element has 'success' class
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
// set message text
$(formResponses).text('Your subscription is complete. Thank you!');
// clear form
$('input').val('');
})
.fail(function(data) {
// make sure formResponses element has 'error' class
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
// set the message text
$(formResponses).text('Input error. Please review and re-submit.');
})
.always(function(data) { // this will always fire even if the request fails
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- simplified HTML -->
<form action="form_processing.php" method="post" id="header-form">
<input type="email" name="email_subscription">
<button type="submit" id="header-form-submit">Submit</button>
<div id="header-form-responses"></div>
</form>
<form action="form_processing.php" method="post" id="footer-form">
<input type="email" name="email_subscription">
<button type="submit" id="footer-form-submit">Submit</button>
<div id="footer-form-responses"></div>
</form>
Here's the original header code (works perfectly):
$(function() {
var form = $('#header-form');
var formResponses = $('#header-form-responses');
var submitButton = $("#header-form-submit");
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
submitButton.attr('disabled', 'disabled');
submitButton.text('Processing...');
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
$(formResponses).text('Your subscription is complete. Thank you!');
$('input').val('');
})
.fail(function(data) {
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
$(formResponses).text('Input error. Please review and re-submit.');
}).always(function(data) {
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
Here's the original footer code (works perfectly):
$(function() {
var form = $('#footer-form');
var formResponses = $('#footer-form-responses');
var submitButton = $("#footer-form-submit");
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
submitButton.attr('disabled', 'disabled');
submitButton.text('Processing...');
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
$(formResponses).text('Subscription complete.');
$('input').val('');
})
.fail(function(data) {
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
$(formResponses).text('Input error. Please review and re-submit.');
}).always(function(data) {
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
Within the $(form).submit( you're still using $(form), eg
var formData = $(form).serialize();
as form = $('#header-form, #footer-form') any call to $(form) (or just form) will affect/apply to/read from both forms. This depends on what the call is, eg form.attr("action") will always get the action from the first form.
Within the handler, change all $(form) (or just form) to $(this):
var formData = $(this).serialize();
...
url: $(this).attr('action'),
be careful using this inside a callback, so if you do need the relevant form then instead, change to
$('#header-form, #footer-form').submit(function(e) {
var form = $(this);
and continue to use form.
Note that in your code form is already a jquery object, but jquery allows you to "double wrap" - ie $(form) is the same as $($(form))
I recommend you remove the outer form variable completely, ie change to
// set up event listener
$('#header-form, #footer-form').submit(function(e) {
which will help to remove the issue of using form not meaning this form.

Unable to render inner HTML for AJAX form with Node.js

I've coded a straightforward form which submits via Mailchimp's API to a waiting list.
This works, and the form upon submission doesn't reload the page (good), and submits the request to the server to store in Mailchimp (also good).
However, I'm wanting to update the inner HTML of the form to reflect whether the form was submitted successfully or not, without reloading the page. I've followed other questions but can't get it to work.
Here's my code at present:
Form -
<form id="early-access" class="hero-form " action="early-access" method="POST">
<input type="email" name="email" placeholder="Enter your email">
<button class="cta-button" type="submit" name="button">Get early access</button>
</form>
My AJAX jQuery code -
<script type="text/javascript">
$("#early-access").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
done: function(data)
{
alert(data);
}
});
});
</script>
EDIT: Now adding my Early Access POST code. Noting that the form successfully adds the user to my waiting list..
module.exports = (req, res) => {
const email = req.body.email;
const data = {
members: [{
email_address: email,
status: "subscribed"
}]
};
const jsonData = JSON.stringify(data);
const url = process.env.MAILCHIMPURL;
const options = {
method: "POST",
auth: process.env.MAILCHIMPAPIKEY
};
const request = https.request(url, options, function(response) {
response.on("data", function(data) {
// console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end();
};
Also for reference - my backend is Node.js, not PHP.. Not sure if that impacts things with jQuery either.
The 'alert' in the success / error call in my AJAX isn't working, neither is my console.log. There's no mention of the request in my log. If the alert was working, I'd assume that I could just use .html to update the #early-access form.. I've tried that already but no luck unfortunately.
EDIT: In my console, after perhaps 2 minutes (roughly) after successfully submitting my form I get a 'error' alert pop up, and my console shows a 'Failed to load resource: The network connection was lost' error.
If anyone could advise, that'd be appreciated!

Prevent Form Resubmission With Javascript After Ajax Post (No Redirect)

A similar question has been asked before with regards to POSTing a form without redirecting, but none of the solutions actually have worked in my case, and those answers are about 8 years old. In my situation, I have a simple form that submits a few text fields to a URL using Ajax:
<form id="f">
<input type="text" name="name">
<button type="submit" form="f">Submit</button>
</form>
<script>
$("#f").submit(function() {
var arr = $("#f").serializeArray();
var name = arr[0].value;
var ajaxConfig = {type: "post", url: "submit_form", data: {name: name}};
$.ajax(ajaxConfig);
return false;
});
</script>
This works perfectly as far as submitting the data to the server goes. The POST request is sent and received, but whenever the page is visited again the browser will attempt to resubmit the data for no reason (Why?). This results in an invalid request being sent to my sites homepage and an HTTP 405 "Page not working error". The page will work again upon subsequent requests. This happens in both Chrome and Safari.
I've tried the history.replaceState(null, null, location.href);, which others have stated works for them, but for me it did not work, neither in Chrome or Safari.
Post/Redirect/Get is not a viable solution as I am wanting to stay on the same page. Please do not recommend that I use the Post/Redirect/Get solution as it does not fit my use case.
One solution is to not use the default "submit" functionality, and simply have the form be submitted through a custom javascript function and click handler:
<form id="f">
<input type="text" name="name">
<button form="f" onmousedown='submit()'>Submit</button>
</form>
<script>
function submit() {
var arr = $("#f").serializeArray();
var name = arr[0].value;
var ajaxConfig = {type: "post", url: "submit_form", data: {name: name}};
$.ajax(ajaxConfig);
});
</script>
But this answer seems to be hacky. Is there a way to submit using canonical form submit buttons without required resubmission upon the next page visit? Furthermore, why would forms be implemented such that they are resubmitted for no reason on page revisiting, even after it's been confirmed they've been submitted once before?
Edit:
Using preventDefault() does not do anything:
<script>
$("#f").submit(function(e) {
e.preventDefault();
var arr = $("#f").serializeArray();
var name = arr[0].value;
var ajaxConfig = {type: "post", url: "submit_form", data: {name: name}};
$.ajax(ajaxConfig);
return false;
});
</script>
You need to run preventDefault() on your form submission event.
It prevents the default action of the form - as form is supposed to reload your page every time it is submitted.
Read more at official documentation
<script>
$("#f").submit(function(e) {
e.preventDefault();
var arr = $("#f").serializeArray();
var name = arr[0].value;
var ajaxConfig = {type: "post", url: "submit_form", data: {name: name}};
$.ajax(ajaxConfig);
return false;
});
</script>

on form submit using ajax and getting value from php function

I have a form calling submitting as follow
<form action="" method="post" id="member_form" onsubmit="return json_add('member','<?php echo ($admin->getnew_id()); ?>','0','slider_form');">
The problem I have is to get the $new_id before submitting the form from another function class.
this is not working
It keep running the funtion getnew_id() and generate the ID before it is saved
I need the process as follow.
Form Open
User complete form
onsubmit it need to do follow.
a. get new id = $new_d
b. then do
return json_add('member','','0','slider_form');">
I tried the following but dont work
$("form").submit(function(){
$.ajax({
url:"lastid.php",
type:'POST',
success:function(response) {
var $new_id = $.trim(response);
return json_add('member-add',$new_id,'0','slider_form');
alert("Submitted");
}
});
The problem seems to be in the third step.
What you should do is prevent the form from submitting and handle it in ajax.
you need onsubmit="return false" to prevent the form from submitting
Next, handle the submission in ajax
$("form#member_form").submit(function(){
$.ajax({
url: "lastid.php",
type: "POST",
data: { // this is where your form's datas are
"json": json_add('member-add',$new_id,'0','slider_form'),
"key": $("form#member_form").serialize()
},
success: function(response) {
var $new_id = $.trim(response);
alert("Submitted");
// alerting here makes more sense
}
// return json_add('member-add',$new_id,'0','slider_form');
// returning here do nothing!
});
You can read more about using ajax in jQuery here

Jquery and the plug-in Validate, testing for no errors

I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(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>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)

Categories