There was an error in my code and there was also a js file included inside my page which prevented anything from executing inside $(document).ready(function () { ...
i'm trying to sumbit this login form:
<form class="form" id="AjaxForm">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit" id="login-button">Login</button>
</form>
Via ajax with this code:
var request;
$("#AjaxForm").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: "login.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();
});
Which i found here: jQuery Ajax POST example with PHP
I'm trying to post it to login.php which checks if it is a valid username and password. But when i press the Login button it just puts the username and the password in the url and does nothing. And when i add action="login.php" method="POST" It submits the form but not via ajax because when i comment the ajax code out it still submits. I'm trying to prevent that. Any insights on my problem?
EDIT: lives here for now: http://5f6738d9.ngrok.io/test/public/index.html username and password are test
Check that the event is bound within a $(document).on('ready' ... otherwise the event won't fire and the form will just submit normally or not via AJAX.
Your code should look like:
$(document).on('ready', function () {
var request;
$("#AjaxForm").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: "login.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();
});
});
Note that these callback events are actually deprecated as of jQuery 1.8.
You will also need to ensure that your POST and action attributes are set on the form in all cases.
Your submit button is a standard submit type button which means that your form will be submitted normally. Based on your HTML code it will just submit the form to the same URL. The JS code will not have time to execute.
All you need to do is cancel de default HTML form submit by adding
event.preventDefault();
You need to add this first thing in your submit listener.
So your JS code will start like this
$("#AjaxForm").submit(function(event){
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
//....
Try using the following code:
$(document).ready(function(){
$('#AjaxForm').on('submit', function(event){
event.preventDefault();
if(request){
request.abort();
request = false;
}
var $form = $(this);
var serializedData = $form.serialize();
var $inputs = $form.find("input, select, button, textarea");
$inputs.prop("disabled", true);
var request = $.ajax({
url: 'login.php',
type: 'POST',
data: serializedData,
success: function (data, textStatus, jqXHR) {
// login was successful so maybe refresh the page
window.location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
// display form errors received from server
},
complete: function (jqXHR, textStatus) {
request = false;
}
});
});
});
Personally I would use this instead:
$(document).ready(function(){
$("#AjaxForm").on("submit",function(e){
e.preventDefault();
var $form = $(this);
var $cacheData = $form.find("input, submit");
var serializedData = $form.serialize();
$.ajax({
url: $form.attr("action"),
type: $form.attr("method"),
data: serializedData,
xhrFields: {
onprogress: function(e){
$cacheData.prop("disabled", true);
console.log(e.loaded / e.total*100 + "%");
}
},
done: function(text){
if(text == "Succes!"){
alert(text);
} else {
alert(text);
}
},
fail: function(xhr, textStatus, errorThrown){
alert(textStatus + " | " + errorThrown);
},
always: function(){
$cacheData.prop("disabled", false);
}
});
});
});
This allows you to do some usefull things:
You're able to monitor the progress in the console
Just because Ajax is succesfull, doesn't mean you can't have an error returned. For example: Wrong password. So now you can simple echo errors back this script will show them. Echo "Succes!" when the login was fine.
Keep in mind though that this script requires that you set the HTML attributes action and method in your form.
Related
I have a ajax section to submit data in laravel. I want if I submit success then don't reload the page and submit the error then reload the page. In the code below, when the error reloads the page correctly, I am having a problem in the success case, the page must not be reloaded, but the result is reloaded. I have added the line e.preventDefault () then true in the success case but wrong in the error case
$(document).ready(function() {
$('form').submit(function(e){
//e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:'{{ route('contracts.store') }}',
method: "POST",
data: form_data,
dataType: "json",
success: function(data) {
$("#mgsContract").text("Add successfully");
$("#hideForm").css("visibility", "visible");
$("#hideForm").css("height", "auto");
$("#result-contract-id").val(data.contract_obj);
},
error: function(data) {
$("#mgsContract").text("Something wrong");
}
})
});
});
Add back that e.preventDefault() to prevent the form submission, and in the error case, call location.reload(). (Or if you want to submit the form conventionally in the error case, use e.target.submit(); instead. Since that's calling submit on the DOM element [not a jQuery wrapper], it won't call your submit handler again. [This is one of the differences between programmatically calling submit on a DOM element vs. calling it on a jQuery object.])
when you use ajax, laravel automatically responds in JSON for validation errors. therefore to access the validation errors you can use this.responseJSON.errors in error section of your ajax. there is no need to reload the page to access validation errors.
however in any case if you need to reload or go to specific location you can use window.location
window.location.href = "an address"; // going to specific location
window.location.reload(); //reloading the page
an ajax example is the following, in which a loop for showing all errors inside the form is specified.
$("#form_id").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
method: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function (data) {
// code in the case of success
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
// code in the case of error
console.log(err.responseJSON);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="' + i + '"]');
el.removeClass('is-valid');
el.addClass('is-invalid');
var parent = el.parents('.form-group');
parent.append("<small class='error-message text-right text-danger d-block pr-5 ' role='alert'>" + error + "</small >");
});
}
},
});
});
I have a form that I have set up to POST using Ajax. Currently my validation is basically this function:
// Function for making all fields required
$(function(){
$("input").prop('required',true);
});
This works fine, however since parts of my form are hidden using CSS depending on previous answers selected - I get the following error for all hidden fields in the console:
An invalid form control with name='providerName' is not focusable.
Is there an easier way to add validation to an Ajax form, perhaps with more control?
E.g. some fields require a link - I think I can validate that the input has a 'link structure'
Example of my Ajax POST code:
// Wait for the DOM to be loaded
$(document).ready(function() {
// Make sure New Provider is unchecked by default
document.getElementById("typeNew").checked = false;
// Variable to hold request
var request;
// Bind function to form submit event
$("#createPanelForm").submit(function(event){
// Abort any pending request
if (request) {
request.abort();
}
// Setup local variable
var $form = $(this);
// Select and cache form fields
var $inputs = $form.find("projectName, projectLink, type, providerName, completeLink, quotaFullLink, screenoutLink, existingProvider");
// Serialize the data in the form
var serializedData = $form.serialize();
// Disable the inputs for the duration of the Ajax request
// Disabled form inputs will not be serialized.
$inputs.prop("disabled", true);
// Send the request
request = $.post({
url: "actions/createpanel.action.php",
method: "POST",
data: serializedData,
function(result){
alert(result);
}
});
// Callback handler for successful request
request.done(function (response, textStatus, jqXHR){
// Log data to console
console.log(serializedData);
console.log(response);
document.getElementById('submitSuccess').style.display = 'block';
});
// Callback handler for failed request
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to console
console.error("Error: "+textStatus, errorThrown);
document.getElementById('submitError').style.display = 'block';
});
// Callback handler for both outcomes
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
// Prevent default form posting
event.preventDefault();
// Hide form and show response
$("#createPanelForm").fadeOut(1000);
$("#submitResponse").delay(1001).fadeIn(1000);
});
})
Adding a novalidate attribute to the form will help:
<form name="myform" novalidate>
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.
I have a HTML form with ID hello
and i have ajax like this
jQuery(document).ready(function($) {
$("#hello").submit(function(){
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "/blog/ajaxphp/registration_check.php",
type: "post",
data: {formData:serializedData},
datetype: "JSON"
});
request.done(function (response, textStatus, jqXHR){
console.log("hellosss");
if(jQuery.parseJSON(response).success==undefined){
$form.unbind('submit').submit();
}else{
return false;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("error");
});
return false;
});
});
But Submit button is not working . i mean it is working if i pressit two times ..
It logs this
Uncaught TypeError: object is not a function in this line $form.unbind('submit').submit();
Question :
How do i make form enable submit when jQuery.parseJSON(response).success==undefined is true otherwise disable form to submit .
How do i disable ajax button while ajax process is being performed.
$("#hello").submit(function(){
return false; <-- You are exiting the function right away
//nothing runs here
Use evt.preventDefault();
$("#hello").submit(function(evt){
evt.preventDefault();
or if you really want to use return, but it at the BOTTOM.
Also the return false in an asynchronous Ajax call does nothing. It is impossible to return anything from an asynchronous call.
EDIT
and you have a typo
if(jQuery.parseJSON(response).sucess==undefined){ <-- that is not how you spell `success`
Double Edit, see if breaking it up into two parts work.
$form.unbind('submit');
$form.submit();
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>