Ajax call just before form submitting does not work - javascript

I've got a Spring MVC - JSP web application. Before submitting a specific form I need to fill a text value input with JS/jQuery so the form POSTed contains that info. This text value is the result of an ajax call that should be done when the submit button is clicked but before the form data is send to the controller.
The relevant pieces of code in my JSP are the following:
<script>
//Gets from model a new valid file code number
function getFileCodeNumber(res){
$.ajax({
type: "post",
url: "getFileCodeNumber",
cache: false,
data: { department: $("#department").val(), docType: $("#docType").val() },
success: res,
error: function(){ alert('Error while request..');}
});
}
</script>
<script>
$(function() {
//Other JS code
$("#submitForm").click((function(event) {
if($("#chkLanguage").prop('checked')){
//some stuff
}else{
getFileCodeNumber(function(data){
//do some stuff with 'data'
});
}
}));
});
</script>
<form:form id="form" class="form-horizontal" method="post" action="AddDoc" commandName="document" enctype="multipart/form-data">
<div class="row" style="text-align:center;">
<input id="submitForm" type="submit" class="btn btn-primary btn-lg" name="commit" value="Finish">
</div>
</br>
</form:form>
Just to let you know, the ajax call works perfectly when called from another trigger action in the same JSP, but when called from the "click" function it retrieves an alert error but is shown on screen for less than 1 second and therefore I cannot tell you what does it say. By the way, Firebug throws "NS_ERROR_NOT_AVAILABLE: prompt aborted by user".
Note that I tried to replace "click" trigger for "submit" that happens exactly the same. My guess would be that the form is being submitted before the ajax call is completely done, but I expected "submit" and "click" functions to do the its job before POSTing the data.
Does anybody have a clue?
EDIT : I found out that the alert that I wasn't able to see is printing the error code of the ajax call. However, I've checked the controller's function that gives response to this call and I've seen it gets completed succesfully and retrieves the expected value. What's more, when I call this function from another trigger in the same JSP it works perfectly. Just to let you see the simple code in the controller:
#RequestMapping(value = "getFileCodeNumber", method = RequestMethod.POST, headers = "Accept=*/*")
public #ResponseBody
String getFileCodeNumber(#RequestParam(value = "department", required = true) String department,
#RequestParam(value = "docType", required = true) String docType) {
int n = cdocs.getNewCode(department, docType);
if (n == 0) {
return "EEEE";
} else {
char[] zeros = new char[4];
Arrays.fill(zeros, '0');
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
System.out.println(df.format(n));
return df.format(n);
}//END_IF
}//END_METHOD
Any ideas?

Try that:
function getFileCodeNumber(res) {
return $.ajax({
type: "post",
url: "getFileCodeNumber",
cache: false,
data: {
department: $("#department").val(),
docType: $("#docType").val()
},
success: res,
error: function () {
alert('Error while request..');
}
});
}
$("#submitForm").click(function (event) {
event.preventDefault();
if ($("#chkLanguage").prop('checked')) {
//some stuff
} else {
getFileCodeNumber(function (data) {
//do some stuff with 'data'
}).done(function () {
$('#form').get(0).submit();
});
}
});

Instead of executing your javascript when the submitbutton is pressed, use a normal button and execute the submit function from the script.

You could do something like this:
function getFileCodeNumber(res){
$.ajax({
type: "post",
url: "getFileCodeNumber",
cache: false,
data: { department: $("#department").val(), docType: $("#docType").val() },
success: res,
error: function(){ alert('Error while request..');}
})
}
$(function() {
if($("#chkLanguage").prop('checked')){
//some stuff
$("#form").submit();
}else{
getFileCodeNumber(function(data){
//do some stuff with 'data'
}).done(function(){
$("#form").submit();
});;
}
});

Related

validating ajax data values

Is it possible to validate if there empty input?
I want to check if data has gotten values from html. If true then should disable button. If not then don't disable button.
This the sample html
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<label>email
<input type="text" name="email" />
</label>
</form>
</body>
</html>
thats the sample html
<script>
$(document).ready(function () {
$("#Submit").click(function(event) {
Execute();
});
function Execute(){
$.ajax({
type: 'POST',
url: 'test.php',
data: { 'email': $("input[name='email']").val() },
success: function(res) {
if (data) {
$("#Submit").attr("disabled", true);
$('#success').text(res.response);
} if (!data) {
$("#Submit").attr("disabled", false);
$('#error').text(res.error_msg);
} else { // do nothing }
},
error: function(resp) {
alert("failed");
}
});
};
});
</script>
U can validate the values before triggering an ajax request. As u can serialize your form data and then validate your required values for the request and if they validate then trigger the ajax call with required data
function Execute(){
// Contains all the inputs that are present in your form
var formData = $('form').serializeArray();
// Validate your values
// If values does not matches your requirements, return false with error like
alert('All required values not filled');return false;
// If code reaches here, means you have all your required values.
// So, making ajax request makes more sense now as it can be executed successfully as values are first validated then ajax is triggered
$.ajax({
// Your code for ajax request
})
}
Try this one. I just modified your code. Hope it helps you out. Basically ajax call is not called untill you validate youe values and once you validated your values you can proceed with ajax and handling your button state using ajax lifecycle functions ( I don't know the exact term for these (beforeSend, complete, success etc) ) :)
LOL it was more easy like this
i got fixed D:)
only Before send was the solution
<script>
$(document).ready(function () {
$("#Submit").click(function(event) {
Execute();
});
function Execute(){
$.ajax({
type: 'POST',
url: 'test.php',
data: { 'email': $("input[name='email']").val() },
beforeSend: function(){
if ($("form input[name='email']").val() == "") {
alert("Text-field is empty.");
return false;
}
},
success: function(response) {
$("#Submit").attr("disabled", true);
$('#resp').text(response.feedback);
},
error: function() {
alert("failed");
}
});
};
});
</script>

laravel, ajax call from input to controller function 500 error

I'm not sure what's happening with this but when my ajax call is made to my php controller method, I'm getting a 500 error and I'm wondering if it's possibly a data type error or just simply syntax.
The value I'm passing from my form input through tha ajax call and into my function is being passed into a url endpoint in my service.php file.
The ajax itself is calling the function successfully but I can't verify the results from my $searchResults in the function because it seems to fail at the point of passing.
I started typing Test into my input with a breakpoint in the browser and it showed the value for my input as "T". Should I need to strip quotes or anything like that if it's being used in the query of the endpoint?
What else does it look like I could be doing wrong here?a
service.php
public function getSearch($query)
{
return $this->get("/search/search?query={$query}" );
}
I also set a new route for the controller and function
Route::post('autocomplete','Controller#autoComplete');
controller.php
public function autoComplete(Request $request)
{
$search_result = $request->search_result;
$service = new service();
//$search_result = "test"; /*this hard coded value works for passing*/
$searchResults = $service->getSearch($search_result);
return $searchResults;
}
view.blade.php
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
type: 'POST',
success: function(response){
console.log(response);
}
});
}
});
Add this to your head
<meta name="csrf-token" content="{{ csrf_token() }}">
and pass the token to ajax:
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
"_token": "{{ csrf_token() }}", // **** THIS LINE IS ADDED ***** //
type: 'POST',
success: function(response){
console.log(response);
}
});
}
});
I take the ajax part from this answer, so thanks to Deepak saini. If this answer solved your problem, give his answer a plus.

Submit form with jQuery (json encoded, ajax, parse original url/method)

I found a lot of questions about submitting forms without json and submitting forms statically specifying the url and method in the javascript code.
But all I am really looking for is a way to make all my forms send an ajax request in the exact way the form specified it in the first place with the only difference being that I want the data to be json encoded.
For instance a form like this
<form role="form" action="api/login" method="POST">
<input name="email" value="my#email.com" type="text"/>
<input name="password" value="mypassword" type="text"/>
<button type="submit">Login</button>
</form>
should automatically generate an ajax request like this when submitted:
POST /api/login HTTP/1.1
Content-type: application/json
{
"email": "my#email.com",
"password": "mypassword"
}
without me having to specify the method or url in the javascript code again.
And I don't want to write new code for every form I write. I'd simply like to have one snippet that automatically applies the above mentioned to any form.
You try something like this
$(document).on('submit','form',function(e){
e.preventDefault();
$form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: getObject($form.serializeArray()),
success: function (response) {
//Success Handler
}
});
return false;
});
function getObject(data) {
var paramObj = {};
$.each(data, function(_, kv) {
if (paramObj.hasOwnProperty(kv.name)) {
paramObj[kv.name] = $.makeArray(paramObj[kv.name]);
paramObj[kv.name].push(kv.value);
}
else {
paramObj[kv.name] = kv.value;
}
});
return paramObj;
}
$(function() {
$('form').submit(function(){
$.post(
$(this).attr('method'),
$('form').serialize(),
function (data) {
proccessmyData(data);
}
);
return false;
});
});
you can write function for success call back with proccessmyData(data)

AJAX: Submitting a form without refreshing the page

I have a form similar to the following:
<form method="post" action="mail.php" id="myForm">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="submit">
</form>
I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.php script to run behind the scenes without refreshing the page.
I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):
$.post('mail.php', $('#myForm').serialize());
If possible, I would like to get help implementing this using AJAX,
Many thanks in advance
You need to prevent the default action (the actual submit).
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('mail.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
You haven't provided your full code, but it sounds like the problem is because you are performing the $.post() on submit of the form, but not stopping the default behaviour. Try this:
$('#myForm').submit(function(e) {
e.preventDefault();
$.post('mail.php', $('#myForm').serialize());
});
/**
* it's better to always use the .on(event, context, callback) instead of the .submit(callback) or .click(callback)
* for explanation why, try googling event delegation.
*/
//$("#myForm").on('submit', callback) catches the submit event of the #myForm element and triggers the callbackfunction
$("#myForm").on('submit', function(event, optionalData){
/*
* do ajax logic -> $.post is a shortcut for the basic $.ajax function which would automatically set the method used to being post
* $.get(), $.load(), $.post() are all variations of the basic $.ajax function with parameters predefined like 'method' used in the ajax call (get or post)
* i mostly use the $.ajax function so i'm not to sure extending the $.post example with an addition .error() (as Kristof Claes mentions) function is allowed
*/
//example using post method
$.post('mail.php', $("#myForm").serialize(), function(response){
alert("hey, my ajax call has been complete using the post function and i got the following response:" + response);
})
//example using ajax method
$.ajax({
url:'mail.php',
type:'POST',
data: $("#myForm").serialize(),
dataType: 'json', //expects response to be json format, if it wouldn't be, error function will get triggered
success: function(response){
alert("hey, my ajax call has been complete using the ajax function and i got the following response in json format:" + response);
},
error: function(response){
//as far as i know, this function will only get triggered if there are some request errors (f.e: 404) or if the response is not in the expected format provided by the dataType parameter
alert("something went wrong");
}
})
//preventing the default behavior when the form is submit by
return false;
//or
event.preventDefault();
})
try this:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
The modern way to do this (which also doesn't require jquery) is to use the fetch API. Older browsers won't support it, but there's a polyfill if that's an issue. For example:
var form = document.getElementById('myForm');
var params = {
method: 'post',
body: new FormData(form),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
};
form.addEventListener('submit', function (e) {
window.fetch('mail.php', params).then(function (response) {
console.log(response.text());
});
e.preventDefault();
});
try this..
<form method="post" action="mail.php" id="myForm" onsubmit="return false;">
OR
add
e.preventDefault(); in your click function
$(#yourselector).click(function(e){
$.post('mail.php', $(this).serialize());
e.preventDefault();
})
You need to prevent default action if you are using input type as submit <input type="submit" name="submit" value="Submit">.
By putting $("form").submit(...) you're attaching the submit handler, this will submit form (this is default action).
If don't want this default action use preventDefault() method.
If you are using other than submit, no need to prevent default.
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'save.asmx/saveData',
dataType: 'json',
contentType:"application/json;charset=utf-8",
data: $('form').serialize(),
async:false,
success: function() {
alert("success");
}
error: function(request,error) {
console.log("error");
}
Take a look at the JQuery Post documentation. It should help you out.

.ajax() refreshes the page after ENTER is hit

I am using ajax to update the db with a new folder but it refreshes the page after ENTER is hit.
on my form I have onkeypress="if(event.keyCode==13) savefolder();"
here is the javascript code that I have: what it does basically is after you hit enter it calls the function savefolder, savefolder then sends a request through ajax to add the folder to the db. Issue is it refreshes the page... I want it to stay on the same page.
any suggestions? Thank you
<script>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
// ajax request to add the folder
jQuery.ajax({
type: 'get',
url: 'addfolder.php',
data: 'foldername=' + foldername + '&foldercolor=' + foldercolor,
beforeSend: function() { alert('beforesend');},
success: function() {alert('success');}
});
return false;
}
</script>
This is working:
<form>
<input type="submit" value="Enter">
<input type="text" value="" placeholder="search">
</form>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
jQuery.ajax({
type: 'get',
url: '/echo/html/',
//data: 'ajax=1&delete=' + koo,
beforeSend: function() {
//fe('#r'+koo).slideToggle("slow");
},
success: function() {
$('form').append('<p>Append after success.</p>');
}
});
return false;
}
jQuery(document).ready(function() {
$('form').submit(savefolder);
});
http://jsfiddle.net/TFRA8/
You need to check to see if you're having any errors during processing (Firebug or Chrome Console can help). As it stands, your code is not well-formed, as the $(document).ready() is never closed in the code you included in the question.
Simply stop the propagation of the event at the time of the form submission
jQuery(document).ready(function($) {
$("#whatever-form-you-are-pulling-your-values-from").submit(function(event) {
var foldername = $('#foldername').val();
var foldercolor = $('#foldercolor').val();
event.stopPropagation();
// ajax request to add the folder
$.ajax({
type: 'get',
url: '../addfolder.php',
data: 'ajax=1&delete=' + koo,
beforeSend: function() { fe('#r'+koo).slideToggle("slow"); },
success: function() { }
});
});
Since by default on a form the enter button submits the form, you need to not only handle this with your own code, but cancel the event after.
Try this code instead:
onkeypress="if(event.keyCode==13) {savefolder(); return false;}"
The onkeypress event will that the return value of the javascript and only continue with it's events if it returns true.

Categories