jquery form validation before ajax request? - ajax

this is a simple code to call the form validation function before submit it with ajax request
$(document).ready(function(){
$('#errors').hide();
var serializedData= $("#categoryForm").serialize();
$("#categoryForm").submit(function(){
$.ajax({
type:'POST',
url: 'actions/add-category.php',
data: serializedData,
beforeSubmit: function(){
return $("#categoryForm").validate();
},
success: function(response) {
$('#status').html(response);
}
});
return false;
});
});
it pass the validation and send the ajax request before validating the form
i tried to make the request if the validation true
$(document).ready(function(){
$('#errors').hide();
var serializedData= $("#categoryForm").serialize();
$("#categoryForm").submit(function(){
if($("#categoryForm").validate()){
$.ajax({
type:'POST',
url: 'actions/add-category.php',
data: serializedData,
success: function(response) {
$('#status').html(response);
}
});
}
return false;
});
});
but this not working too

Dont submit the form in any case, do the check when the submit button is clicked - and then if it succedeed - do the submiting.
Try to do it as follows:
$("#submitButton").click(function(){
if($("#categoryForm").validate()){
$.ajax({
type:'POST',
url: 'actions/add-category.php',
data: serializedData,
success: function(response) {
$('#status').html(response);
//if true:
$("#categoryForm").submit();
}
});
}
return false;
});

Related

Laravel/Ajax delete function not refreshing my table after success

when I add my function fetchcategory(); in my delete ajax, my table is not refreshing:
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
alert('Category Deleted!');
// location.reload();
$('#deleteCategoryModal').modal('hide');
fetchcategory();
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
});
});
for a reference, my screenshot shows the alert, showing that the delete function follows through:
another reference is that my add function here reloads the page after a new table is added:
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: category_data,
dataType: "json",
success: function (response){
console.log(response);
if(response.status == 400) {
$('#category_formCheck').html("");
$('#category_formCheck').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheck').append('<li>'+err_values+'</li>');
});
}
else
{
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#createCategory').modal('hide');
fetchcategory();
}
}
});
another problem of mine is that I tried to add the alert and refresh function inside:
$.ajax({
type: "DELETE",
but they do not show up, so I placed them inside on(click
why is my delete ajax not refreshing my table?
UPDATE:
I am aware of location.reload(); but adding this defeats the purpose.
the data does get deleted, I have to manually refresh the whole page to see the changes though.
You can do it in ajax success. I believe fetchcategory() method is populating data to table
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
// location.reload();
$('#deleteCategoryModal').modal('hide');
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
success: function(data) {
alert('Category Deleted!');
fetchcategory();
},
error: function() {
alert('Error occured');
}
});
});
</script>

Unable to receive data using AJAX post in Laravel

I am trying to send some variables(data),one is the checkbox text, and other is the value in the textarea field to the controller in Laravel through ajax, below is the script:
<script>
$('#btn1').on('click', function() {
$('input[type="checkbox"]').on('click', function() {
var aa=$(this).next('label').text();
var bb=$('textarea#txt2').val();
$.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.ajax({
type: "POST",
url: "/masterdata",
//dataType: 'json',
data: {aa,bb},
success:function(){
console.log(data);
}
,error:function(){
console.log("Error!!!!");
}
});
});
});
</script>
On trying to retrieve the request values in the controller, only the request token gets displayed, and the ajax function doesn't display the success or error message either.What am I missing here?
you need to set a variable on ajax success like this:
$.ajax({
type: "POST",
url: "/masterdata",
//dataType: 'json',
data: {aa,bb},
success:function(response){
console.log(response);
}
,error:function(){
console.log("Error!!!!");
}
});
Try your data as in this format:
data:{'posa': aa, 'posb': bb},
and
success:function(data){
console.log(data);
}
Hope this helps.
i found two issue in your ajax request.
you have to change data: {aa,bb}, to object like data: {aa : aa, bb : bb},
Your success response log is wrong. Current code success:function(), it should be success:function(data)
Full output of new code is :
<script>
$('#btn1').on('click', function() {
$('input[type="checkbox"]').on('click', function() {
var aa=$(this).next('label').text();
var bb=$('textarea#txt2').val();
$.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.ajax({
type: "POST",
url: "/masterdata",
dataType: 'json',
data: {aa : aa, bb : bb},
processData: false,
cache: false,
async :false,
success:function(data){
console.log(data);
}
,error:function(){
console.log("Error!!!!");
}
});
});
});
</script>
To get parameter value in controller use
/**
* Store.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$aa = $request->input('aa');
$bb = $request->input('bb');
//Your code here
}
<script>
$('#btn1').on('click', function() {
$('input[type="checkbox"]').on('click', function() {
var aa=$(this).next('label').text();
var bb=$('textarea#txt2').val();
$.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.ajax({
type: "POST",
url: "/masterdata",
//dataType: 'json',
data: 'aa=test'+'&bb=test',
success:function(){
console.log(data);
}
,error:function(){
console.log("Error!!!!");
}
});
});
});
</script>

Check Form Before Submit Use Ajax Django

I use Ajax to send data from form to server. But I want to check data in form before Submit by Ajax:
<form id='#id_form' onsubmit='return checkInputSubmit();' >
...
</form>
In Ajax:
$('#id_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: $('#id_form').serialize(), // serializes the form's elements.
success: function(data) {
if(data.result == true) {
//My code
}
else {
//My code
}
}
});
});
But checkInputSubmit() can't prevent submit from Ajax. You can explain for me and give me solution to check data in form before Submit by Ajax.
Thanks.
in the $('#id_form').submit(function(e) event, you can check/edit/return... any thing you want before call Ajax. Within Ajax, i think it won't work and don't good. (we just check ajax result, not input)
#Blurp, I found the solution by use your help.
$('#id_form').validate({
submitHandler: function(form) {
e.preventDefault();
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: $('#id_form').serialize(), // serializes the form's elements.
success: function(data) {
if(data.result == true) {
//My code
}
else {
//My code
}
}
});
}
});

Laravel - ajax creates double input

I have made this ajax request to show the validation errors and prevent the page to reload
$(document).on('mousedown', ':submit', function() {
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){
},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}
});
});
All is fine with this code! The problem is that after successfull submit i have 2 inputs in DB...how can i prevent this?
Are you sure the form isn't actually submitting and saving the values once by post and once by ajax? Usually if you're capturing a submit event you listen for the forms submit even not the mousedown event of the submit button e.g.
$('form').on('submit', function(e) {
// Stop the forms default submit action
e.preventDefault();
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){
},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}
});
});
Also the e.preventDefault() will prevent the form from submitting itself along with your ajax action. Also you'd best off selecting your form by an ID or class name.

Ajax request type POST returning GET

I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>

Resources