jQuery AJAX success not firing even though data is being captured - javascript

I have a form that I'm submitting by AJAX and trying to replace the form once it's been submitted with a success message.
Using this:
jQuery(function($){
var $form = $('#ajax_form'),
$message = $('#thanks');
$form.submit(function(e){
$.ajax({
type: "POST",
data: $form.serialize(),
url: $form.attr('action')
})
.done(function(data) {
console.log(data);
if (data.success) {
$form.hide();
$message.fadeIn('slow');
}
});
e.preventDefault();
});
});
when I click the submit button, nothing happens, and I don't get anything written to the console. But the form is hooked up to a database and I can see in the back end that submissions are being saved.
So why is that nothing within the done function is returning?

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

AJAX/JQuery: Submit form and call function without refreshing page

I'm attempting to use ajax/jquery to submit a form comprised of dropdown menus, with the intention of displaying information from a MySQL database based on the form input. Without ajax/jquery, the page functions properly. However, I don't want the page to refresh once the form is submitted, so that the selected dropdown options remain showing. My ajax/jquery is not very good, and I know this is where I'm having trouble. my code is as follows:
<script>
$(document).ready(funtion(){
var $form = $('form');
$form.submit(funtion(){
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
success: displayResults
});
});
});
</script>
the function displayResults is the function that I want to call when the form is submitted, but as of right now, when i click submit, the form refreshes and no results are displayed. Any help would be greatly appreciated. Thanks in advance.
<script>
$(document).ready(funtion(){
var $form = $('form');
$form.submit(funtion(e){
e.preventDefault();
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
success: displayResults
});
});
});
</script>
This prevents the form from submitting by preventing the event from firing. In vanilla javascript you could return false on submit and it would be the same.
Try this way to submit your form and prevent default behavior of form submit using e.preventdefualt() which will prevent event from firing,To serialize form data use serializeArray() ,use success and error to debug ajax call.
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
console.log(data); //display data Results
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(errorThrown); // dispaly error
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
The .submit() it will be the same as use the submit button. You have to use a button with the click event.
<script>
$(document).ready(funtion(){
var data1 = $('#field1').val();
// the same with all the values
$('#button').click(function(){
$.ajax({
type: "POST",
data: ({dat1: data1} ),
cache: false,
success: function(data) {
displayResults();
}
});
});
});
</script>

One submit button for multiple forms. Master save strategy,

Picture below shows simplification of the html page layout I am working with. It has 3 forms, every form has it's own submit button and can be submitted individually. At the top of the page "Master Save" is located. This button should save all 3 forms.
Every form have submit() function overloaded and they look like this:
form1.submit(function () {
Form1SubmitOverloaded(this);
return false;
});
Form1SubmitOverloaded = function (form) {
$.post(form.action, $(form).serialize(), function (data) {
//DOM manipulation, etc/
}).fail(function () {
//error parsing etc.
});
return false;
};
After pressing "Master Save" I want to submit forms in order 1 > 2 > 3. But I want Form 2 to wait until form 1 has ended.
Form1 submitted >> Form2 submitted >> Form3 submitted.
$('#masterSave').click(function () {
$('#form1').submit();
$('#form2').submit(); // wait until form1 ended
$('#form3').submit(); // waint until form2 ended
return false;
});
Please provide method to order submits in 'click' function as presented.
Thanks.
.post() method doesn't look to have a synch property. But .ajax() has.
I suggest you use the .ajax() method instead of the .post() shortcut method. That way you could force ajax to be synchronious
$.ajax({
[...]
async : false
}
you can use something like this
Form1SubmitOverloaded();
$.ajax({
type: "POST",
url: test1.php,
data: $( "#form1" ).serialize(),
success: function(){
Form2SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
Form3SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
alert("All submit successfully");
}
});
}
});
}
});

Have to click submit twice for AJAX request to fire on form submission

My Form HTML looks like this.
<form novalidate action="register.php" method="post" >
<label for="username">Username</label>
<input type="text" name="username" required placeholder="Your username" autofocus/>
<input type="submit" name="register" value="Register" cid="submit" />
</form>
And My jQuery looks like this
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
e.preventDefault();
});
The sad thing is that it logs hello to the console but it never submits the form with one click on the submit button. I need to press two times to submit button.
Can anyone tell me the problem and how can I fix it so that 1 click is sufficient for form submission.
NOTE: The data of form is send for validation not actually for submission . If data like email , username etc are valid i want the form to be submitted with one click.
Try separating the validation from the form submit.
Simply changing this line:
$("form").submit(function(e) {
to
$("input[name='register']").click(function(e) {
First of all I think it would be cleaner to use a success function instead of a .done() function. For example:
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
// Merge the check.php and register.php into one file so you don't have to 'send' the data twice.
url: "register.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON",
success: function() {
console.log("This form has been submitted via AJAX");
}
});
});
Notice that I removed the .unbind() function, as I suspect it might be the reason your code is acting up. It removes the event handlers from the form, regardless of their type (see: http://api.jquery.com/unbind/). Also, I put the e.preventDefault() at the start. I suggest you try this edited piece of code, and let us know if it does or does not work.
EDIT: Oh, and yeah, you don't need to submit it when you're sending the data via AJAX.
Try this one.
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
});
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datatype: "JSON",
success: function(data) {
return data;
}
});
});
So, to break it down.
Stop the form submission with the preventDefault().
Get the form data and submit it to your validator script.
The return value, I assume, is a boolean value. If it validated, it'll be true, or false.
Return the value which will continue the form submission or end it.
NB.: This is a horrible way to validate your forms. I'd be validating my forms on the server with the form submission, because javascript can be terribly easily monkeyed with. Everything from forcing a true response from the server to turning the submission event listener off.
Once I have the same issue
What I found is I have some bug in my url xxx.php
it may return error message like "Notice: Undefined variable: j in xxx.php on line ....."
It may let ajax run unexpected way.
Just for your info.
Instead of doing prevent default when clicking a submit button, you can create a normal button and fire a function when you click it, at the end of that function, submit the form using $('#form').submit();. No more confusing prevent default anymore.
You don't need to call submit() since you are posting your data via ajax.
EDIT You may need to adjust the contentType and/or other ajax params based on your needs. PHP example is very basic. Your form is most likely much more complex. Also, you will want to sanitize any php data - don't rely on just the $_POST
jQuery:
$("form").submit(function(e) {
$.ajax({
'type': 'post',
'contentType': 'application/json',
'url': 'post.php',
'dataType': 'json',
'data': { formData: $(this).serialize},
'timeout': 50000
).done(function(data) {
// Response from your validation script
if (data === true)
{
// SUCCESS!
}
else
{
// Something happened.
}
).fail(function(error) {
console.log(error);
});
e.preventDefault();
});
PHP
$is_valid = FALSE;
$name = $_POST['name'];
if ($name !== '')
{
$is_valid = TRUE;
}
else
{
return FALSE;
}
if ($is_valid)
{
// insert into db or email or whatver
return TRUE;
}

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