AJAX POST success and error firing - javascript

I checked many posts here regarding same issue but nothing was working, and more or less it behaves like a glitch:
function onbtnclick(){
var user_email=$('#user_email').val();
var send_data = {email:user_email};
$.ajax({
type: 'POST',
url: 'someURL.php',
crossDomain: true,
data:send_data,
dataType: 'text',
success: function(responseData, textStatus, jqXHR) {
alert("Thank you for the mailing list");
},
error: function (responseData, textStatus, errorThrown) {
alert('Your email is already in our mailing list.');
console.log('log e:'+responseData);
console.log('log e:'+textStatus);
console.log('log e:'+errorThrown);
}
});
return false;
}
};
<form name="myform">
<input id="user_email" type="email" name="email" placeholder="Your Email Here" style="width:300px" required><br>
<br><button type="submit" class="leka-button button-style2 offer_button" onclick="onbtnclick()"><h5>SIGN UP</h5></button>
</form>
Simply i'm trying to alert the proper message if the user new to fire success or if he registered to fire error, I tried to remove dataType:'text' or adding 'json' and\with removing crossDomain attribute as well but all didn't give me the reason.
In case this was useful, here is where I fire the AJAX script.

You call the JavaScript when you click on a submit button.
The JavaScript runs. The Ajax request is prepared. The JavaScript finishes. The submit button's default behaviour submits the form. The page unloads. The Ajax request is canceled. The regular form submission takes place.
Get rid of the onclick attribute. Bind your event handlers with JavaScript instead.
$(function () {
var $form = $([name="myform"]); // `name` is obsolete for form elements, give it an ID instead
$form.on('submit', onbtnclick);
function onbtnclick(event) { // Give this function a better name
event.preventDefault(); // Don't submit the form normally
// Then put the rest of your existing code
}
});

Related

Calling same controller's method using ajax GET and POST type

Hi I am a newbie to Grails and Groovy. Please help me to solve the below issue related to calling controller's method using ajax call.
The scenario behind the code is to recover the password using the username whenever the user is unable to remember the password. I have explained the code flow in detail below.
Application begins with the below auth.gsp page:
<form action='${postUrl}' method='POST' id='loginForm' autocomplete='off'>
<input type='text' name='j_username' id='username'/>
<input type='password' name='j_password' id='password'/>
<input type='submit' id="submit" value='${message(code: "default.button.login")}'/>
<g:message code="etranscripts.forgotPassword"/>
</form>
When I click on the Forgot password link of the anchor tag, it will call the below ajax method:
<script>
$(document).ready(function () {
$('#recovery-link').click(function () {
var url = $(this).attr('recovery-url')
$.ajax({
url: url,
dataType: "html"
}).done(function (html) {
$('#loginForm').replaceWith(html)
$('#sign-in-instruct').text('<g:message code="js.resetEnterName"/>')
}).fail(function (jqXHR, textStatus) {
console.log("Request for url failed: " + url)
})
event.preventDefault()
return false
});
});
The controller method for the above call is as below.
def recoverPassword = {
println "RecoverPassword method of ctrl....."
if (!request.post) {
// show the form
render(template: "recoverPassword" )
return
}
//some other stuff based on the input conditions.
The successful output template for the above ajax call is:
<div id="recover-password" >
<ul>
<li>
<span><g:textField name="username" id="username" value="" /></span>
<input type='submit' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>
</li>
</ul>
Till here my code works perfect. But the issue begins from here.
i.e When I enter some value in the username field of the template and click on submit, it should call the below ajax method.
$(document).on('click', '#submit-username-link', function (event) {
var url = $(this).attr('recovery-url')
var username = $('input#username').val();
$.ajax({
url: url,
type: "POST",
data: {username:username},
dataType: "json"
}).done(function (responseJson) {
$('#sign-in-instruct').text(responseJson.message)
$('div.copyright').css('margin','74px 0px 0px 140px')
$('#home-link').show()
if ( responseJson.status == 'success') {
$('#recover-password').remove()
}
}).fail(function (jqXHR, textStatus) {
$('#recover-password').remove()
$('#sign-in-instruct').text(textStatus)
console.log("Failed to send the email " + textStatus)
})
event.preventDefault()
return false
});
The thing is, url refers to the same method of the controller but the only change is POST type is used and that will be taken into consideration inside the method using if conditions.(i.e some other stuff of the controller)
These GET and POST type of method calls are configured as shown below in the URLMappings.groovy file.
"/recoverPassword/recoverPassword"(controller: 'recoverPassword') {
action = [GET: "recoverPassword", POST: "recoverPassword"]
}
The whole summary of this question is, for the same method of controller, GET request is working but POST type of ajax call is not able to reach the controller's method.
Am I doing anything wrong over here? Please help me to solve this issue. Thanks in advance :-)
Overcomplicated. Why don't you use separate function in controller for GET (rendering the form) and separate function for POST (for handling the recovering the password)?
Check out also https://en.wikipedia.org/wiki/KISS_principle
Change input Type submit to button
<input type='button' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>

When and when doesn't success: value executes in jQuery Ajax method? (Header location not changed)

I'm submitting a form using jQuery Ajax.
The data is submitted successfully but there's a little problem. When I add the commented statements in this code, the success: function(){} doesn't run (location is not changed).
Q. 1 When I remove those statements, it runs. I don't understand this logic. When does it actually executes and how does checking for xy affects this?
Here's my Ajax code:
$(document).ready(function(){
$("#button").click(function(){
**//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result){
$(location).attr('href', 'login2.php');
},
error: function(){
alert(error);
}
});
// }
});
});
Here's concerned input tag:
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">
<input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required />
......
Q.2 When I write event.preventDefault(); to stop the default action of submit button, the required atrributes of input fields don't work. Why is it so? Can it be solved?
To Question 2:
If you call preventDefault for the event of the click on the submit button, then the default behaviour (initiating the submit) is prevented, so the input fields are not checked.
You have to listen on the submit event of the form instead and prevent the default behaviour of this, because the submit event is send after the input elements are checked and before the form is submitted.
$(document).ready(function() {
$("#signupform").on('submit', function(e) {
e.preventDefault();
//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result) {
$(location).attr('href', 'login2.php');
},
error: function() {
alert(error);
}
});
// }
});
});
When you use jquery ajax there is two types of result:
400 - OK status which be capture by the success function
402 or 500 are internal errors and those will be capture by the error function.
Now, in your error function youre trying to print an error variable that does not exist.
Also, when you use preventDefault you have pass variable that handles de event too cancel.

[jQuery]Page refreshes after appending html with .html()

So I'm trying to get some data from the server with php but as soon as it's loaded onto the page it seems to reload the page and make it disappear again.
My html:
<form id="searchForm">
<input name="searchValue" type="text" id="search">
<input type="submit" name="Submit" value="Zoek op klant" onclick="getKlanten()">
</form>
<div id="klanten">
</div>
My js:
function getKlanten(){
var value = $("#search").val();
$.ajax({
url:'includes/getKlanten.php',
async: false,
type: 'POST',
data: {'searchValue':value},
success: function(data, textStatus, jqXHR)
{
$('#klanten').html(data);
},
error: function () {
$('#klanten').html('Bummer: there was an error!');
}
});
}
Can anyone help? It gets put into the div but then instantly disappears again.
Firstly, avoid inline click handlers. The page reloads because by default a form submits the form content to the url specified in action attribute.
Instead attach an event to the form and use preventDefault to avoid the page from refreshing. Do something like this
$('#searchForm').on('submit', function(e){
e.preventDefault();
// your ajax request.
});
Or attach an event to input button like this
$('input[type="submit"]').on('click', function(e){
e.preventDefault();
// your ajax request
});
Read more about preventDefault here

Prevent page reload and redirect on form submit ajax/jquery

I have looked through all the similar posts out there but nothing seems to help. This is what I have
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
Send Message
Clear Form
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
function sendForm(){
// all your code
return false;
}
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
Have you tried using
function sendForm(event){
event.preventDefault();
}
Simple and Complete working code
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
I expect anyone to understand my idea very well as it's a very simple idea.
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:
// element refers to the form DOM after you got it in a variable called element for example:
element.addEventListener('submit', (e) => {
e.preventDefault();
// rest of your code goes here
});
The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
Of course it will work only with forms.
The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
Note:
The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.

post method not working

I want to submit form data using post using ajax because in form post after submit it is redirected to a new page.
<form id="myContactForm">
<p>
<label for="byour_name">Your name</label><input type="text" name="byour_name" value="" id="byour_name">
</p>
<p>
<label for="byour_email_address">Your email address</label><input type="text" name="byour_email_address" value="" id="byour_email_address">
</p>
<p>
What's on your mind?<br>
<textarea name="Message" rows="10" cols="25"></textarea>
</p>
<p>
<input type="submit" value="Send it!" onClick="sendMail()">
</p>
</form>
function sendMail() {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),
success: function( response) {
alert(response);
},
error: function() {
alert('failure');
}
});
}
Every time I make request error function is executing.I am writing app on google app engine. I am keep getting this error:
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
My post request handler is:
def post(self):
Content = self.request.get("Message")
byName = self.request.get("byour_name")
byEmailAddress = self.request.get("byour_email_address")
gmailUser = 'id#gmail.com'
gmailPassword = 'password'
dataSend = byName
mail.send_mail(sender = gmailUser,
to = gmailUser,
subject ="Email Sent By : "+ byName + "#" + byEmailAddress,
body = Content)
self.response.out.write(byEmailAddress)
And after I click submit button URl changes to:
http://localhost:8080/?byour_name=username&byour_email_address=userEmail#gmail.com%40gmail.com&Message=mlm%0D%0A#contact
as I am making a get request can someone help me..But how post request changes to get request.
You're not preventing the default submit. Either return false from your sendMail function, or take the event as a parameter and call preventDefault() on it.
Please remove form tag and the get the desired values by id and then use ajax method. Because may be ajax post and form request method are conflicting. I think form has default get method as you said earlier may be that's the reason whenever you click on submit first ajax post make request soon after form get method and may be that's the reason the error is thrown by your server.
I think I know what your trying to do , to fix this you can do the following:
remove onclick="sendMail()"
and change your JavaScript function to something like:
$('#myContactForm').submit(function () {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),success:
function( response) {
alert(response);
},
error: function(){
alert('failure');
}
});
});

Categories

Resources