About Form , Ajax - javascript

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

Related

NO refresh the page when success ajax

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

Validation with Ajax POST

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>

AJAX post form won't work. It does absolutely nothing

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.

how to make two dependent ajax requests on one buttonclick

I want insert two forms as two table rows in db using a button click event.I have used ajax request to insert in database and done for one form, while making another ajax request depending on first form it is not working
here is my java script using jquery.
var transportid = 2;
$.ajax({
url : '/TransportJob/create',
type : 'POST',
data : $('form[action="/TransportJob/Create"]').serialize(),
success : function sfn(data, textStatus, jqXHR) { // **success spelling mistake**
transportid = parseInt(data);
alert('inserted id :' + data);
$('#TransportJobId').val((transportid));
$.ajax({
url : '/TransportJobAddress/create',
type : 'POST',
//beforeSend: function myintserver(xhr){
// $('#addAddress').html('<div id="temp_load" style="text-align:center">please wait ...</div>');
//},
data : $('form[action="/TransportJobAddress/Create"]').serialize(),
success : function poste(data, textStatus, jqXHR) {
$('#addAddress').html(data);
},
error : function err(jqXHR, textStatus, errorThrown) {
alert('error at address :' + errorThrown);
}
});
},
error : function myfunction(jqXHR, textStatus, errorThrown) {
alert("error at transport :" + jqXHR.textStatus);
},
complete : function completefunc() {
alert('ajax completed all requests');
}
});
return false;
});
The first ajax sucess spelling problem make correction success then it will work
In your first ajax call, changesucess to success ?
I have modify your code first ajax request success portion spelling mistake.
sucess : function sfn(data, textStatus, jqXHR) {
Change to
success : function sfn(data, textStatus, jqXHR) {
Second error at end of request is
Remove extra code
return false;
});
and Put return false; after closing complete method.
e.g.
complete : function completefunc() {
alert('ajax completed all requests');
}
return false;
});

Given a form submit, how to only submit if the server first responses back with a valid flag?

I have a form, with a text input and a submit button.
On submit, I want to hit the server first to see if the input is valid, then based on the response either show an error message or if valid, continue with the form submit.
Here is what I have:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
if (data.valid) {
return true
} else {
// Show error message
return false;
e.preventDefault();
}
}
});
});
Problem is the form is always submitting, given the use case, what's the right way to implement? Thanks
Try like this:
$('#new_user').submit(function(e) {
var $form = $(this);
// we send an AJAX request to verify something
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
// if the server said OK we trigger the form submission
// note that this will no longer call the .submit handler
// and cause infinite recursion
$form[0].submit();
} else {
// Show error message
alert('oops an error');
}
}
});
// we always cancel the submission of the form
return false;
});
Since you're already submitting via AJAX why not just submit the data then if it's valid rather than transmit the data twice?
That said, the function that makes the Ajax call needs to be the one that returns false. Then the successvfunction should end with:
$('#new_user').submit()
The fact that AJAX is asynchronous is what's throwing you off.
Please forgive any typos, I'm doing this on my cell phone.
Submitting the same post to the server twice seems quite unnecessary. I'm guessing you just want to stay on the same page if the form doesn't (or can't) be submitted successfully. If I understand your intention correctly, just do a redirect from your success handler:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
location.href = "success.htm";
},
// if not valid, return an error status code from the server
error: function () {
// display error/validation messaging
}
});
return false;
});
Another approach
EDIT: seems redundant submitting same data twice, not sure if this is what is intended. If server gets valid data on first attempt no point in resending
var isValid=false;
$('#new_user').submit(function(e) {
var $form = $(this);
/* only do ajax when isValid is false*/
if ( !isValid){
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
isValid=true;
/* submit again, will bypass ajax since flag is true*/
$form.submit();
} else {
// Show error message
alert('oops an error');
}
}
});
}
/* will return false until ajax changes this flag*/
return isValid;
});

Categories

Resources