NO refresh the page when success ajax - javascript

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

Related

jQuery AJAX success not firing even though data is being captured

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?

Prevent submit on a jQuery form

I'm setting up a password control on a login form with jQuery and ajax.
So far, this is the script
$(document).ready(function() {
$("#login-form").submit(function(e) {
var csrftoken = getCookie('csrftoken');
var password = $('#login-password').val();
var email = $('#login-email').val();
$.ajax({
url: "/password_check/",
type: "POST",
dataType: "json",
data : {
csrfmiddlewaretoken: csrftoken,
password: password,
email: email
},
success: function(result) {
document.getElementById("login-error").innerHTML = result.response;
event.preventDefault();
}
});
return false;
});
});
With this, the error gets caught when firing the submit button, but if the password is correct the submit doesn't work (even though the error doesn't show up anymore).
What am I missing?
You have an asynchronous ajax call, so by the time your success function fires, the form submit event has passed so you need to submit the form again but use the DOM method, which will bypass the jQuery event handler and allow the form to submit.
success: function(result) {
if(result == "correct"){
document.getElementById("login-form").submit();
} else {
document.getElementById("login-error").innerHTML = result.response;
}
}
As you didnt say what response indicates a correct password, I have used result == "correct", so change that accordingly.
You have to return false only if u dont want to submit the form.
If password is correct you need to return true in your case.

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;
}

Error with Jquery Ajax Success Event and Receiving Response Message

I am calling jQuery Ajax function, everything works fine.. except, it is not receving any response and appending it in.
When form is submitted.. beforeSend event is called and loading image successfully runs, and also there is an alert box with message 'Deleted', but the request and response from page is not appended.... in network tab of chrome, i can see message of selected post deleted... but its not appending in page.
$(document).ready(function() {
$("#post").submit(function() {
var post = $('#post').val();
var token = $('#token').val();
var str = 'token='+ token + '&post='+ post;
$.ajax({
type: "POST",
cache: false,
url: "http://localhost/delete.php",
data: str,
beforeSend: function(){
$("#post").html('<img src="http://localhost/loader.gif" align="absmiddle"> Deleting...');
},
success: function(msg) {
alert('Deleted');
$("#post").ajaxComplete(function(event, request, settings) {
$("#post").html(msg);
});
}
});
return false;
});
});
You're attaching a new event listener to #post after the AJAX query succeeds. Basically what you're saying is, "after this query succeeds, wait for another query to succeed and then change the HTML." Since the query has already succeeded, you need to remove ajaxComplete and simply use:
success: function() {
alert('Deleted');
$("#post").html(msg);
}

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