ajax post refreshes the page when it shouldn't - javascript

I have a uses jquery post answers to a grader.php script, which works perfectly. Depending on the results, it brings a form so they can send message with contact info. When I try to post to the second script to process the mailer, the whole page refreshes without posting the data or returning the appropriate message. It turns out the call is not being made at all. If you want to see the staging site you're welcome to look. It's kind of a cheesy way for me to get my feet wet with jquery. However, I believe the suspect script is here.
I added an alert to the click event to see if it even triggers the click on the score button. No alert triggers and all I get is a page refresh.
Alternatively, is there any way log posts and console data to see exactly what's happening?
HTML:
<div id="result">
<form id="info" method="post" action="">
<input name="phone_number" placeholder="phone number" type="text" size="20" value="">
<input name="email_address" placeholder="email address" type="text" size="30" value="">
<textarea cols="50" rows="10" placeholder="Questions? Comments?" name="comments"></textarea>
<input type="submit" id="score" name="score" value="Send">
</form>';
</div>
Jquery:
$("#score").click(function(event){
alert("clicked");
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var info = $("#info").serialize();
$('#result').fadeOut().html("");
$.post('paider.php', info, function(data , status){
$('#result').fadeIn().html(data);
alert(status);
});
});

I think there are 2 problems here.
Problem 1:
As the form resides inside #result, setting #result's html to "" effectively empties the form before serialization? Have you tried?
$("#score").click(function(event){
var info = $("#info").serialize();
$('#result').fadeOut().html("");
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$.post('paider.php', info, function(data , status){
$('#result').fadeIn().html(data);
});
});
Problem 2:
Okay so I took a look at your staging site and think I've found the issue. You begin by having a form similar to the one in the question on this topic, but you then "replace" that form with a new form containing now a "#score" element (input type='submit').
You are applying your jquery event handler on document load but at that time the #score element does not yet exist in the DOM because you have not loaded it yet.
You believe you are running the script inside $("#score").click but in fact the page is simply using default behavior of a form with no action and a submit button.
To correct this issue you need to apply the event handler at either a higher level in the DOM tree OR you can do some easier way just to test if this is the problem
Please try this in your first #submitbuttonclick handler
$("#submitButton").click(function(event){
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var formdata = $('form').serialize();
$.post('grader.php', formdata, function(data , status){
$('ul').css('display', 'none');
$('#result').fadeIn().html(data);
//Here add the handler for #score click
$("#score").off("click").on("click", function(event){
//Insert code snippet shared above here
});
});
});
What this will do is bind the click event on the #score submit button after it has been written into the DOM. In case the script executes more than once we do not want the handler to fire multiple times, which is why we first call "off".
Hope this helps.

Related

JQuery submit() not working

I have this script:
<form action="" method="POST" id="regform">
<paper-material id="general">
<gold-email-input pw="mail" name="mail" label="Mail" auto-validate></gold-email-input>
<paper-input id="pw" name="pw" type="password" label="Password"></paper-input>
<paper-input id="pwrepeat" type="password" label="Repeat password"></paper-input>
<paper-button onClick="subform();" id="submitbutton" elevation="2" raised>Submit</paper-button>
</paper-material>
</form>
function subform(){
console.log("call");
$('#regform').submit(function(e){
console.log( "Data: " + $(this).serialize() );
e.preventDefault(); //no difference with or without this function
});
}
The method submit(function(e)) is not called by the script. Why? I want to prevent the submit and use the data. Is this the right way to seralize the data from the form?
As your code stands, the function might be called, depending on where your javascript code is located.
In general, using onClick is discouraged as it might cause nasty scoping issues. At the point, the html parser reaches your input with onclick="subform();", this function has to be registered to the global scope. This is not the case, if you use $(document).ready or have the javascript at the bottom of your page.
So please check your console for errors, because either you should see the console.log("call"); or an error message instead, which prevents the execution of your function in the first place.
Also, in the onClick handler, you are simply registering a handler for the submit event, so you could as well skip this entirely and simply register the submit handler directly.
Your code should simply look like this:
// this waits until your form is submitted
$('#regform').submit(function(e){
console.log("submit button was pressed");
console.log( "Data: " + $(this).serialize() );
// this prevents the the actual form submit, so you have to do
// some kind of ajax call, to get the data to the server
e.preventDefault();
});
Try assigning your submit button an input type.
<input type="submit" class="paper-button" onClick="subform();" id="submitbutton" elevation="2" raised>Submit</paper-button>
Also, the preventdefault is going to prevent the submission. Try removing it.
EDIT:
As Christopher pointed out, a library is being used, so option one is not going to work. Remove the preventdefault instead.

Jquery / Html form

reaching a point of confusion
I am creating a couple of input elements and a button to search.
From using HTML previously, I am lead to believe that i should create a and contain my elements and
But the data is not to be sent anywhere apart from to the javascript to show the correct place in the google map.
I've managed to confuse myself; do i need a element to contain and s ?
The problem is when i press a whether it be a test or a search button the page reloads.
I do not want the page to reload. The only way for me not to get this to happen is by removing element, this does not feel right, I am concerned with using good practice if possible.
This is my code:
<form id="maps_form">
<fieldset id="search_maps">
<label for="marker">Search Shop: </label>
<input name="searchName" id="searchName" type="text" placeholder="Enter Shop Name">
</fieldset>
<fieldset id="map_buttons">
<button id="test"> test</button>
<button id="searchSomething">Search</button>
</fieldset>
</form>
I feel like, whilst am learning this javascript, dipping into jquery and learning xml, I am forgetting the basics of html :s is this normally to lose touch whilst learning new languages?
The page will reload if your your click/submit handler doesn't return false. So page will refresh if:
If your Javascript listener isn't registered correctly
Your Javascript handler returns true
Your Javascript handler causes an error (check dev console for errors)
$("#maps_form").submit(function () {
// do stuff
return false; // Don't submit the form
});
Never do that! Wouldn't prevent go to next page if too many action after return false.
$("#maps_form").submit(function () {
// do stuff
return false; // Don't submit the form
});
This is correct form:
$("#maps_form").submit(function (event) {
event.preventDefault();
...
});

Jquery .load and POST data

This is really frustrating I would appreciate some help with this. I have a div, called comments and a form inside of that div. What I want to do is post a form to the current page and have it load inside of the div without reloading the entire thing. Here is my current code:
<div id="comments">
<form action="#" method="post" onsubmit="return false;" >
<input type="hidden" name="txtname" value="test">
<textarea id="wysiwyg" name="wysiwyg" rows="5" cols="50"></textarea>
<input type="submit" name="post" id="post" value="Submit">
</form>
<script type="text/javascript">
EDIT: Read edit below for current code
</script>
</div>
When I submit, the alert fires, but the page does not load. It works fine if I make the event as follows:
$("#comments").load("comments.asp");
It's not liking the posting of data. I have used .load before but never to post data. I got the above code from these very same forums.
I'm honestly not sure of the purpose of 'name' and 'tel' - do I refer to those variables or the form variable names when processing the code? This is in ASP classic.
What's wrong with the above code, how can I get it to send data from the forum via POST? Thanks!
EDIT:
I am now using the following code:
$("#post").submit(function(event){
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
$inputs.attr("disabled", "disabled");
$.ajax({
url: "/comments.asp",
type: "post",
data: serializedData,
success: function(response, textStatus, jqXHR){
console.log("comment posted");
},
error: function(jqXHR, textStatus, errorThrown){
console.log(
textStatus, errorThrown
);
},
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
event.preventDefault();
});
And now it's using properly getting the form handled...however it goes to comments.asp. How can I make all the action happen in a certain div (comments div?)
It seems to me you are blending a bunch of different techniques in a way that is not entirely coherent.
$.post is a shortened version of $.ajax (see here).
$.load takes a url and sticks it into a <div> or other DOM Element (see here).
If I understand it correctly (and I may not!), you're not really wanting to load the form, but put values into the form fields. $.load is an odd way to do this. (It may work, but I do it another way.)
If you're using $(#...).submit, you can also leave out a whole bunch of stuff in your form. The following should work fine.
<form id="form_id">
...
<input type="submit" value="Submit">
</form>
My method is: (1) have a hardcoded HTML form (or build it by AJAX), (2) get the values from the DB (or wherever) using $.post (or $.ajax), (3) stick the values into the form using .val() (or equivalent - whatever is right for the input type) and the DOM id of that input, and then (4) use .submit (in a manner similar to yours). You will need to add preventDefault as the others have suggested.
You're also muddying the waters using #post as the DOM id. You really want to give the form itself the ID, and then use $(#form_id).submit(... I can't test it now, but having the submit on the input field may cause some grief. The official example attaches the .submit to the form id.
I'm also not sure the <div> with id 'comments' really does much. I have a container id like your 'comments', but that's because I build forms by AJAX and stick them into the container. If you don't need to do that, the id 'comments' is unnecessary to the whole procedure.
Your text box element dont have an id with value txtname. But in your script you are trying to access using # (which is supposed be with an id context). So add an id element to your input box.
<input type="hidden" name="txtname" id="txtname" value="test">
And as expascarello said, You need to stop the default behaviour of the submit button . Other wise it will do the normal form posting so you wont be able to feel the ajax effect.
Use preventDefault
$(function(){
$("#post").click(function(e) {
e.preventDefault()
alert("clicked");
$("#comments").load("comments.asp", {
'name': $("#wysiwyg").val(),
'tel': $("#txtname").val()
});
});
});
You are not cancelling the clicking of the button so the form is submitting and resetting the page.
$("#post").click(function(evt) {
evt.preventDefault();
...
jQuery event.preventDefault()
The load() method does a get and not a post.

jquery .click form submit not working in ie8 or below-

im having trouble with a form submit script im using with javascript and jquery- its a form i have loaded into a facebook tab which when submit should pass a variable to another tab.
it works in ie9, chrome, ff and safari but client is stuck on ie 7 and 8. I dont know what the problem is- I have tried replace the button with a div and image incase .click wouldnt overwrite the submit function.
this should be a common problem with fix? or what am i doing thats completely wrong?
<script>
$('document').ready( function(){
$('#my_button').click(function (e) {
//this.form.onsubmit();
var_app = "444444";
url = "http://www.facebook.com/tab/?sk=bladadasd&app_data=" + var_app;
parent.window.location.replace(url);
e.preventDefault();
return false;
});
});
</script>
<form id="submit" method="POST" >
<ul>
<li><span>Photo code <sup class="required">*</sup></span><input id="barcode" name="barcode" type="text"/></li>
<li><span>First name</span><input id="firstName" name="firstName" type="text"/></li>
<li><span>Last name</span><input id="lastName" name="lastName" type="text"/></li>
<li><span>Email address</span><input id="optional_email" name="optional_email" type="text"/></li>
</ul>
<a class="help">Need help?</a>
<input value="" type="submit" id="my_button" />
</form>
edit the form bounces on to the correct page in normal browsers but in ie8 it just submits upon itself going nowhere and displaying the same again
If it is a submit button , then instead you should be working with onsubmit even on that form.
P.S. why is your var_app variable in global scope ?
Try the submit event instead of click event.
$('#my_button').submit(function(event) {
event.preventDefault();
});
You are also missing an action for your form.
I wonder if you should also specify the script type
Declare var_app & url variables.
var var_app = "444444";
var url = "http://www.facebook.com/tab/?sk=bladadasd&app_data=" + var_app;
The error lay with the line
parent.window.location.replace(url);
internet explorer only allowed the following statement and would throw a permission error
parent.location.replace(url);
nothing to do with jquery or my form syntax :( only realised this when i ran the code on a different machine in ie7

Prevent form redirect OR refresh on submit?

I've searched through a bunch of pages, but can't find my problem, so I had to make a post.
I have a form that has a submit button, and when submitted I want it to NOT refresh OR redirect. I just want jQuery to perform a function.
Here's the form:
<form id="contactForm">
<fieldset>
<label for="Name">Name</label>
<input id="contactName" type="text" />
</fieldset>
<fieldset>
<label for="Email">Email</label>
<input id="contactEmail" type="text" />
</fieldset>
<fieldset class="noHeight">
<textarea id="contactMessage" cols="20"></textarea>
<input id="contactSend" class="submit" type="submit" onclick="sendContactForm()" />
</fieldset>
</form>
<small id="messageSent">Your message has been sent.</small>
And here is the jQuery:
function sendContactForm(){
$("#messageSent").slideDown("slow");
setTimeout('$("#messageSent").slideUp();$("#contactForm").slideUp("slow")', 2000);
}
I've tried with and without an action element on the form, but don't know what I'm doing wrong. What has annoyed me more is that I have an example that does it perfectly:
Example Page
If you want to see my problem live, goto stormink.net (my site) and check out the sidebar where it says "Send me and email" and "RSS Subscription". Both are forms that I'm trying to get this to work on.
Just handle the form submission on the submit event, and return false:
$('#contactForm').submit(function () {
sendContactForm();
return false;
});
You don't need any more the onclick event on the submit button:
<input class="submit" type="submit" value="Send" />
Here:
function submitClick(e)
{
e.preventDefault();
$("#messageSent").slideDown("slow");
setTimeout('$("#messageSent").slideUp();
$("#contactForm").slideUp("slow")', 2000);
}
$(document).ready(function() {
$('#contactSend').click(submitClick);
});
Instead of using the onClick event, you'll use bind an 'click' event handler using jQuery to the submit button (or whatever button), which will take submitClick as a callback. We pass the event to the callback to call preventDefault, which is what will prevent the click from submitting the form.
In the opening tag of your form, set an action attribute like so:
<form id="contactForm" action="#">
It looks like you're missing a return false.
If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):
<input name="o" required="required" aria-required="true" type="text">
You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:
$('form').on('submit', function(event) {
event.preventDefault();
my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment
As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.
So if you want to get rid of these default pop-ups, use the click event on the submit button:
$('form input[type=submit]').on('click', function(event) {
event.preventDefault();
my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes
An alternative solution would be to not use form tag and handle click event on submit button through jquery. This way there wont be any page refresh but at the same time there is a downside that "enter" button for submission wont work and also on mobiles you wont get a go button( a style in some mobiles). So stick to use of form tag and use the accepted answer.
Unlike most of the previous answers, the solution that is described here demonstrates how to prevent a page from refreshing/redirecting on <form> submission using pure Javascript, instead of JQuery.
The HTML form
Below is the HTML <form>. There is no need to use the onclick event (which fires when the user uses the mouse to click on a button) or the onsubmit event (which fires when the user hits the enter key) on the submit button. These events are taken care of by the JS code described in the following section.
<form id="myForm">
<input type="text" name="contactName" id="contactName">
<input class="submit" type="submit" value="Submit">
</form>
The JavaScript code
Below is the JavaScript code to handle the <form> submission on the submit event. The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
Note: Make sure to register the event handler after the HTML element is added to the DOM tree (when loading the webpage); otherwise, a runtime error will be caused, as you'll be trying to set a property (an event handler) of a non-existent object. One way to ensure this is to simply place the script after the element in question (i.e., <form>), but as this might be a bit dangerous—since you are relying on how you assume a browser works—you can assign the event handler after the initial HTML document has been completely loaded and parsed, using the DOMContentLoaded event. Example:
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault() // Cancel the default action
sendContactForm();
});
});
All together
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault() // Cancel the default action
sendContactForm();
});
});
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="contactName" id="contactName">
<input class="submit" type="submit" value="Submit">
</form>
</body>
</html>

Categories

Resources