Jquery validation is working but the ajax is not submitted - ajax

I'm trying to validate fields inside the form and then fire a function to submit the form using Ajax, the validation is working very well, but the ajax is not working at all
can you please help me figure the solution out
$(function() {
$.validator.addMethod("urlRegex", function(value, element) {
return this.optional(element) ||regex here .test(value);
}, "this should be url.");
$("#songvalid").validate({
rules:
{
song:
{
required: true,
urlRegex: true
}
},
messages:
{
song:
{
urlRegex:"من فضلك أدخل حروف وأرقام فقط"
}
},
submitHandler: function(form){
$("#error").fadeOut();
$("#song-btn").html('<img src="btn-ajax-loader.gif" /> انتظر لحظات ...', );
$.ajax({
url: 'song_process.php',
type: this.method,
data: $(this).serialize(),
success: function(responsd) {
if(responsd=="song"){
$("#song-btn").html(' تم الإرسال');
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+responsd+' !%</div>');
});
}
}
});
return false;
}
});
});

I found the answer!
I changed this:
type: this.method,
data: $(this).serialize(),
to this:
type: 'POST',
data: $("#formName").serialize(),

Related

The GET method is not supported for this route. Supported methods: POST. Laravel Ajax

I'm using ajax to send comments. This is the route
Route::post('/users/add/comment/', 'UsersController#AddComment')->name('AddComment');
The ajax call
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
type: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
and the controller
public function AddComment(Request $request){
dd($request);
}
It always throws that error. I changed the route and the func name a lot of times. but it does the same thing and the dd(); request is always empty.
Thanks in advance!
You have to set the ajax method to post with the attribute 'method', not 'type'.
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
I was trying to send the same data using <form> I tried AJAX to have more control over the request.
my form tag goes like <form method="POST" action="/users/add/comment/">
I removed the last / in the URL and it does work. I don't know how or why.
But It works !!!
Form
<form id="YourForm">
...
your inputs
...
</form>
Button
<button type="button" class="btn btn-success SendButton">Save This</button>
JS
<script type="text/javascript">
$(document).on('click', '.SendButton', function (e) {
e.preventDefault();
var data = $("#YourForm").serialize();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method : "POST",
url : "{{ url('users/add/comment/') }}",
data : data,
dataType : "JSON",
})
.done(function(response) {
alert('Success!');
location.reload();
.fail(function(response) {
console.log("Error: ", response);
});
return false;
});
</script>
You need to change type to method, you use the wrong keyword. Now it is a default GET
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post', // it should be method: 'post'
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});

I want to delete data without refreshing whole page using ajax

I am new at Laravel, I am trying to delete data with ajax, when I click to delete button, the page is refreshing but data is deleting perfectly but that should not be reloaded.
Controller
public function destroy($id)
{
$delete = Digitizing::where('id', $id)->delete();
return back();
}
HTML view
<a href="{{route('digitizing.delete',$digitizing->id)}}"
class="btn btn-danger" onclick="deleteConfirmation({{$digitizing->id}})">Delete</a>
<script type="text/javascript">
function deleteConfirmation(id) {
Swal.fire({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('digitizing/delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
**Delete wants a get method because you have to give only ID to delete.**
**WEB.PHP**
Route::get('digitizing/delete/{id}','YourController#destroy');
**SCRIPT**
let id = $('#my_id').val();
$.ajax({
type: 'GET',
url: "{{url('digitizing/delete')}}/" + id,
data: {
_token: '{{csrf_token()}}',
},
success: function () {
alert('Successfully Deleted');
}
}).fail(function(){
console.log('problem with route = digitizing/delete');
});

Running Ajax request not working

I just migrated to a different bootstrap template now my ajax functions is not working and my php file which handles the functions is not appearing in the XHR inspect tool of chrome.
I only have this jquery script ? is this enough for running an ajax function? I
<!-- Jquery Core Js -->
<script src="../dashboard-assets/plugins/jquery/jquery.min.js"></script>
HTML CODE
<form id="upload_book_form" method="POST">
<p>Upload Books</p>
<input type="file" id="uploadbookinfo" name="uploadbookinfo" value="Import" />
</form>
SCRIPT FUNCTION
<script type="text/javascript">
$(document).ready(function() {
//upload book
$('#uploadbookinfo').change(function() {
$('#upload_book_form').submit();
});
$('#upload_book_form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Book Added , Try refreshing the page',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else if (getdata == "ERRORFILETYPE") {
swal({
title: 'Oops...',
text: 'File type is not supported',
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-info",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
});
});
</script>

Getting textbox value from X-editable

How do you get the value of the textbox field and send as data inside of ajaxOptions? I tested my view and it prints out the test variable successfully from my Django views. I am using X-editable for Jquery. Heres what textbox input looks like:
http://jsfiddle.net/xBB5x/197/
views.py
def create_post(request):
print request.POST.get("test", "");
return HttpResponse(json,content_type="application/json")
HTML
<a id="other1" data-pk="First Name" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
pk: 1,
url: '/create_post/',
ajaxOptions: {
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
test: "hi",
},
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});
Instead of ajaxOptions, use params. If I remember correctly, test and its value will be included in your POST request by x-editable. Try something like this:
Html
<a id="other1" data-pk="1" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
url: '/create_post/',
params : function(params) {
params.csrfmiddlewaretoken = '{{ csrf_token }}';
return params;
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});

jQuery validation followed by Ajax post

I'm trying to combine jQuery validation plugin with Ajax post. This is my code:
PHP form:
<form id="newsletter_form" method="post">
<input name="newsletteremail" type="text" id="newsletteremail" class="required email">
<input name="Signup" type="submit" class="formsm" id="Signup" value="Signup">
<div id="emailerrormessage"></div>
</form>
JQuery:
$('#newsletter_form').validate({
rules: {
email: {required:true, email:true}
},
submitHandler: function(form) {
$.ajax({
data: $(this).serialize(),
type: "POST",
url: "includes/ajax.php?action=newsletter",
contentType: "application/x-www-form-urlencoded; iso-8859-7",
dataType: 'json',
success: function(response, textStatus, jqXHR) {
if(response.status == 'error'){
$("#newsletteremail").removeClass().addClass('ajaxerror');
} else {
$("#newsletteremail").removeClass();
}
},
error: function (xhr, textStatus, errorThrown) {
$("#emailerrormessage").addClass('ajaxsuccess').html(xhr.responseText).show();
}
});
return false;
}
});
Before using validate() the form would submit fine. After adding the validate() code, the validation works, the form is being submitted (I receive a 200 OK response) but the values being submitted are null. What am I doing wring here?
this refers to the validator object that you're applying to the form, so change:
data: $(this).serialize(),
to
data: $(form).serialize(),
Use jQuery.form plugin and try it as below,
submitHandler: function(form)
{
jQuery(form).ajaxSubmit(
{
dataType : 'json',
beforeSend : function(arr, $form, options)
{
},
success : function(msg)
{
return false;
}
});
}

Resources