post method not working - javascript

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');
}
});
});

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'/>

Laravel: no data being sent via ajax

I made a custom Jquery plugin to help me easily send data via Ajax to the server that has been tailored to suit laravel, but apparently I am not able to send any data. when I use dd($request->all()) to check what has been sent to the laravel server, I receive an empty array in console implying that I have not sent anything. Below is my code
JS
(function($){
'use strict'
$.fn.lajax=function(options){
//overwrite options
var optns=$.extend({
dataType: 'json',
debug:false,
processData: true,
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
acceptedInputFile:'/*/',
//functions that are very similar to the ajax optns but differ a little
//as the paramters give easy access to the ajax form element
lajaxBeforeSend: function(form,formData,jqXHR,settings){},
lajaxSuccess: function(form,formData,data,textStatus,jqXHR){},
lajaxError: function(form,formData,jqXHR,textStatus,errorThrown){},
},options);
//loop through every form, 'this' refers to the jquery object (which should be a list of from elements)
this.each(function(index,el){
$(el).submit(function(e){
//prevent submission
e.preventDefault();
//form jquery instance & form data
var $form=$(this);
var formData = new FormData($form[0]);
//catch url where the ajax function is supposed to go
var url=$form.attr('action');
//check if REST based method is assigned
if($form.find('input[name="_method"]').length)
{
var method=$(this).find(':input[name="_method"]').val().toUpperCase();
if(optns.debug)
console.log("'"+method+"' method registered for form submission");
}
//If no REST method is assigned, then check method attr
else if($form.attr('method'))
{
var method=$form.attr('method').toUpperCase();
if(optns.debug)
console.log("'"+method+"' method registered for form submission");
}
//method is not assigned
else
{
var method='GET';
if(optns.debug)
console.log('The form that submitted has no method type assigned. GET method will be assigned as default');
}
//object that will be fed into jquerys ajax method
var ajax_options={
url: url,
method: method,
beforeSend: function(jqXHR,settings){
console.log(jqXHR);
console.log(settings);
if(optns.debug)
console.log('executing beforeSend function');
optns.lajaxBeforeSend($form,formData,jqXHR,settings);
},
success: function(data,textStatus,jqXHR){
if(optns.debug)
console.log('executing success function');
optns.lajaxSuccess($form,formData,data,textStatus,jqXHR)
},
error: function(jqXHR,textStatus,errorThrown){
if(optns.debug)
console.log('error encountered. ajax error function procked');
optns.lajaxError($form,formData,jqXHR,textStatus,errorThrown);
var errors = jqXHR.responseJSON;
console.log(errors);
},
}
//check if files are included in the submitted form if the method is not GET
if($form.find('input:file').length && method!='GET'){
ajax_options.processData=false;
ajax_options.contentType=false;
ajax_options.cache=false;
ajax_options.data=formData;
}
if(optns.debug)
console.log('About to send ajax request');
//sending request here
$.ajax(ajax_options);
if(optns.debug)
console.log('finished with form '+$form+'. Looping to next form if exists');
return false;
});
});
return this;
}
}(jQuery));
HTML
<form class="lajax" action="{{ action('AlbumController#store') }}" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Album Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="coverFile">Album Cover Image</label>
<input name="cover" type="file" id="coverFile">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="form-group">
<label for="albumFiles">Album Images</label>
<input type="file" name="photos[]" multiple>
</div>
<button type="submit" class="btn btn-primary">Create Album</button>
</form>
I think my JS is not sending my data over to the server but im not sure why. Please help
Did you define a Post route in your route file that exactly point to AlbumController#store Controller method

AJAX POST success and error firing

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
}
});

PHP Ajax Call Navigating to Action Page on Form Submit

I have this ajax call in my php code that still navigates to action page. I want the ajax call to stay on the same page and only update part of the page. What I'm doing wrong here:
<form method="post" id="holderSave" action="student_add_scene.php">
<h3> Save to Holder</h3><br/>
<div id="cutfrom">
<input placeholder="Cut from" name="from" id="from">
<button href="#" onclick="captureElapsed('elapseFrom', 'from');
return false;">capture</button>
</div>
<div id="cutto">
<input placeholder="Cut to" name="to" id="to" >
<button href="#" onclick="captureElapsed('elapseTo', 'to');
return false">capture</button>
</div>
<div id="savecapt">
<input placeholder="add label" id="label" name="label"/>
<input type='submit' value='Save' class='button'>
</div>
</form>
<script>
$('#holderSave').on("submit", (function (e) { // catch the form's submit event
e.preventDefault();
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
var posting = $.post( url, { from: $('#from').val(), label:$('#label').val(), to: $('#to').val()});
posting.done(function(response)){
$('#holderSave').html(response); // update the DIV
alert(response);
}
});
return false;
}));
</script>
This is a syntax error:
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
You seem to be trying to treat the object literal you pass to ajax as a function body. It isn't, so you can't just write statements in it.
Since you make the ajax request with $.post later, $.ajax is entirely pointless. Remove that line and it should work.
Fixed code. Aside from the pointless half-a-call to .ajax, you had a bunch of syntax errors which I've fixed while reformatting it.
Use your browser's developer tools console. Use http://jshint.com/
// Remove pointless ( from before the second argument of the call to on().
$('#holderSave').on("submit", function(e) {
e.preventDefault();
// Remove half a call to .ajax
var $form = $(this),
url = $form.attr('action');
var posting = $.post(url, {
from: $('#from').val(),
label: $('#label').val(),
to: $('#to').val()
});
posting.done(function(response) {
$('#holderSave').html(response);
alert(response);
// Remove line with extra } here
});
return false;
// Remove extra ) here
});
Change submit into button with id
<input type='button' id="save" value='Save' class='button'>
Trigger click event for button, serialize the form data and post the data via ajax
$(document).ready(function() {
$('#save').click(function(){ // catch the form's submit event
var form = $('#holderSave');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form .serialize(),
success: function( response ) {
console.log( response );
}
} );
});
});

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.

Categories

Resources