Having trouble submitting a form with AJAX - javascript

HTML:
<form id="message">
<input id="message-text" name="message" type="text" value="" autofocus="autofocus" />
<input type="submit" value="Send" />
</form>
JAVASCRIPT:
$(document).ready(function () {
// submit new message
var request;
$("#message").submit(function(event) {
// abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var postData = $form.serialize();
// note: we disable elements AFTER the form data has been serialized
$inputs.prop("disabled", true);
request = $.ajax({
url: "submit.php",
type: "POST",
data: postData
})
.done(function(response, textStatus, jqXHR) {
console.log('Success: ' + textStatus, jqXHR);
})
.fail(function(jqHXR, textStatus, errorThrown) {
console.error('Error: ' + textStatus, errorThrown);
});
});
});
I've confirmed that submit.php works when not using AJAX to submit, so I don't think that's the problem. The console log simply says: Error: error on line 66: console.error('Error: ' + textStatus, errorThrown); which is completely non-descriptive nor helpful... The page also refreshes when I hit enter or click submit, which isn't supposed to happen.
Any ideas what I'm doing wrong?

This happens because you use submit input, this is the default behavior of submit input, so you have 2 options first is disable the submit using event.preventDeafult(); on the submit process, or you can easily change your send button:
<input type="submit" value="Send" />
to
<input type="button" value="Send" />

$("#message").submit(function(event) {
event.preventDefault();
...

I prepare demo for you please download it from
https://www.dropbox.com/s/24h0o9n08iuvpo1/ajaxdemo.rar
Change as per your requirement. I think it is helpful

Related

Submit form only if a function return true

I need a way to submit the form ONLY if foo return true. I tried this code but it submits the form even if foo return false.
<input type="submit" value="submit" onclick="return foo();" />
<script type="text/javascript">
function foo() {
// if... return true
// else return false
}
</script>
If I use the onsubmit function, then it submits first. So it's not good in my case.
you can try alternative method using jquery ajax submit as follows, which I am using, may helpful to u too..
var request;
$("#YourFormId").submit(function(event){
if(yourFunction()==false) {
return false;
}
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "yourFormActionPage.php",
type: "post",
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
//ok
});
request.fail(function (jqXHR, textStatus, errorThrown){
//track it
});
request.always(function () {
$inputs.prop("disabled", false);
});
event.preventDefault();
});
One possible solution is to use the form's submit event. You can put the conditional in the submit event handler so the submission is halted when foo() does not return true.
(NOTE: I had to guess what the selector might be for your form since it's not part of your question)
document.getElementById('myForm').submit(function(e) {
if (!foo()) {
e.preventDefault();
}
})
You can use ajax submit.
<form class="formbox" method="post" action="/your/action/url" id="myForm" name="myForm">
<input type="text" id="name" class="name" name="name" value=""/>
<input type="submit" value="submit" onclick="return foo();" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function foo() {
if(1==1) {
alert("Success: Going to call the function");
$("#myForm").submit(); //calling function.
} else {
alert("Error: ");
}
}

Redirect from client side using html and ajax or js

I have a login page basically connecting to a location, and do a simple post call. I want to redirect the page to somewhere else if a user clicks submit and if post returns 200 or success. If not, return fail.
What would be the simplest way to do it? I am looking into client side redirect.
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="/1.1.1.1:80/login" method="POST">
<p>Username: <input type="text" name="username" /><p>
<p>Password: <input type="password" name="password" /><p>
<p><input type="submit" value="Log In" /></p>
{% module xsrf_form_html() %}
</form>
</body>
</html>
UPDATE:
<html>
<head>
<title>Please Log In</title>
<script src="/Users/src/downloads/app/jquery-2.1.4.min.js" type="text/javascript"></script>
</head>
<body>
<form action="https://1.1.1.1:80/login" method="POST">
#Tried as well, but doesn't redirect <form action="https://google.com" method="POST">
<input class="form-control" type="text" required name="username" placeholder="username">
<input class="form-control" type="password" required name="password" placeholder="Password">
<input class="form-control" type="hidden" required name="eauth" value="pam">
<p><input type="submit" value="Log In" /></p>
{% module xsrf_form_html() %}
</form>
</body>
</html>
<script type="text/javascript">
$('form').submit(function(){
$.ajax({
type: "Post",
url: $('form').attr('action'),
success: function (response) {
window.location = 'http://www.google.com';
//error handling
}
});
//return false so the form does not submit again
return false;
});
</script>
you can post your form by jquery(ajax) and when result back decide what you want to do.
this link should help you
// Variable to hold request
var request;
// Bind to the submit event of our form
$("#foo").submit(function(event){
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
// Prevent default posting of form
event.preventDefault();
});
include jQuery and Try to use this according your code input
<script type="text/javascript">
$(document).ready(function(){
$('form').submit(function(){
$.ajax({
url: 'your-php-file.php',
dataType: 'html',
success: function(response) {
window.location.href = response;
}
});
});
});
</script>
Try something like this:
Make sure you have downloaded jquery.js file, put it in your directory somewhere, and put this in the head tag
<script src="path to your jquery file" type="text/javascript"></script>
Put this at the end of your html:
<script type="text/javascript">
$('form').submit(function(){
$.ajax({
type: "Post",
url: $('form').attr('action'),
success: function (result) {
if(result.Code == 200) //change this to your status code return
window.location = 'http://www.google.com';
else
//error handling
}
});
//return false so the form does not submit again
return false;
});
</script>
This should capture the form's submit event and instead post it via ajax which will allow you to handle the response however you want.

AJAX form script isn't executed

I want to use a form via AJAX, so I got this Code Snippet from another post on stackoverflow. It didn't work, so I added an alert to check, if the script is even executed. That doesn't seem to be the case and I'm wondering why.
<head>
<script src='jquery.js'></script>
<script>
var request;
$("#foo").submit(function(event){
alert("Hallu");
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "/action.php",
type: "post",
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
event.preventDefault();
});
</script>
</head>
<body>
<form id="foo">
<input type="text" id="name" name="name" />
<textarea id="msg" name="msg"></textarea>
<input type="submit" value="Senden" />
</form>
</body>
When the script runs, #foo does not exist, so there is nothing to bind the event hander to.
Move the script so it appears after the form, or convert it to a function and bind it as a ready or load event handler.
The reason is very simple. You do something to $('#foo') before it has been loaded. At this point of time JS does not know anything about an object with id="foo", because it is not loaded yet.
Wrap the whole code in $(document).ready(function() { ... });.
This should look like this:
var request;
$(document).ready(function() {
$("#foo").submit(function(event){
alert("Hallu");
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "/action.php",
type: "post",
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
event.preventDefault();
});
});
Please consider using a good IDE, like NetBeans or Eclipse. It helps you to detect unclosed brackets and other stuff.

jquery submit not working when migrating to higher version

Hi i just migrated from jquery 1.10.2 to 1.2.1 in order to use tablesorter.js addon, but my problem is that my jquery ajax post is not working anymore with this jquery version, i hope someone can figure out the problem or what im missing, here is my code:
js file
// variable to hold request
var request;
// bind to the submit event of our form
$("#postAtencion").submit(function(event){
// abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "/admin/atencion",
type: "post",
data: serializedData,
success: function(response){
// we have the response
$('#tableSubView').html(response);
}
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Atencion Posted");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
Jsp File
<div class="container">
<h2>Consulta</h2>
<form id="postAtencion" style="padding:19px;">
<div>
Number: <input type="text" name="msisdn" style="margin-left: 15px;" class="inputAtencion">
</div>
Init Date: <input type="date" name="fechaInicio" class="inputAtencion">
Final Date: <input type="date" name="fechaFin" class="inputAtencion">
<input type="submit" value="Search" class="buscar"/>
</form>
<div id="tableSubView"></div>
</div>
<script src="js/file.js"></script>
<script src="js/atencion-post.js"></script>
<script src="js/jquery-requiered.js"></script>
<script src="js/jquery.tablesorter.js"></script>

image input type not being detected

I am trying to submit a form using an image input type. The ajax request performs fine, and I get a response back from my php script. My problem is that I want the image button to change it's image when it is submitted (and it wasn't doing that). The firebug console said that form.pic is undefined, and the image does not get updated. Any Ideas why?
javascript/jquery
function new_user(form){
var url = "attendance.php";
var dataString = "status="+form.astatus.value;
dataString = dataString+"&id="+form.mark_attend.value;
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function(data) {
form.pic.src = data; //Error here
},
error: function(jqXHR, textStatus, errorThrown){ console.error("error: " + textStatus, errorThrown);}
});
return false;
}
HTML
<form method="POST" onSubmit="return new_user(this);" >
<input type="hidden" value="attended" name="astatus" />
<input type="hidden" value="idKey" name="mark_attend" />
<input type="image" src="greencheck.png" name="pic" />
</form>
$(form).find('input[name="pic"]').attr('src', data);
This, I think, is the cleanest way to do this considering that you are using jQuery.

Categories

Resources