POST http://127.0.0.1:8000/unlock 405 (Method Not Allowed) - laravel

I want to pass the unlock key to route using ajax but I am not allowed to do so. The code gives me method not allowed error.
I cant see the error in my code, whether it the route error or some other error
<script>
$(document).ready(function(){
$('.result-container').hide();
$('.unlock-btn').on('click', function(){
$.ajax({
url: "{{route('unlock')}}",
method: 'post',
data: {
theme_id : {{$theme_id}},
key : $('.key').val(),
},
success: function(data){
console.log('success');
if(data === '0')
$('.result-container').show();
else
{
window.location = "{{route('view', ['theme_id' => $theme_id])}}";
}
}
})
});
});
</script>

So your route is a get but in ajax you are sending post request. Change it to post.
Route::post('/unlock', 'ThemeController#unlock')->name('unlock');
And also add a token in data otherwise you will get 419 error for missing CSRF.
$.ajax({
url: "{{route('unlock')}}",
method: 'post',
data: {
theme_id : {{$theme_id}},
key : $('.key').val(),
"_token": "{{ csrf_token() }}",
},
success: function(data){
console.log('success');
if(data === '0')
$('.result-container').show();
else
{
window.location = "{{route('view', ['theme_id' => $theme_id])}}";
}
}
})

Related

Laravel 8 Method Not Allowed 405 Ajax CRUD

I fixed my csrf
I fixed my route , route clear too
but still error show up .
I'm doing ajax form in modal :
My Route
Route::post('increp/store',[\App\Http\Controllers\IncrepController::class,'store'])->name('increp.store');
My ajax
// Create article Ajax request.
$('#submit_increp').click(function(e) {
e.preventDefault();
var data = $("#main-form").serialize();
$.ajax({
url: "{{ route('increp.store') }}",
type: 'POST',
data: data,
dataType: 'json',
beforeSend:function(){
$(document).find('span.error-text').text('');
},
success: function(result) {
if(result.errors) {
console.log(result.errors);
$('.alert-danger').html('');
$.each(result.errors, function(key, val) {
$('span.'+key+'_error').text(val[0]);
});
} else {
$('.alert-danger').hide();
$('.alert-success').show();
}
}
});
});
I doing this for days, i dont have idea how to fix this errors .
Network tab
Console tab

Detect successful response from ajax function

I have a function which is triggered via AJAX and will run the following when successful:
wp_send_json_success();
I am then doing a console log of the response and trying to detect if success = true:
.done(function (response) {
if( response['success'] == true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Currently I am getting "add to cart failed" despite the output of response looking like it should be successful:
console.log(response);
// Response in the browser console:
{"success":true}
Am I detecting the true response incorrectly?
Update - PHP function the AJAX is triggering. Removed most code just as a test.
function fbpixel_add_to_cart_event_conversion_api() {
echo 'hello world';
wp_send_json_success();
die();
}
add_action('wp_ajax_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
add_action('wp_ajax_nopriv_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'fbpixel_add_to_cart_event_conversion_api',
product_id: productId,
variation_id: variationId,
},
})
.done(function (response) {
console.log(response);
console.log(productId);
console.log(variationId);
console.log(response.success);
if( response.success === true ) {
I always use dot notations to check the response returned from wp_send_json_success, and it always works. So use it like this:
if( response.success === true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Give it a shot and let me know if you were able to get it to work!
I should have pasted the entire code sorry. I had the wrong dataType set within $.ajax:
Before
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'html',
})
After
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
})

Why do I always get undefined value from other data?

I always get undefined values from other data for example: ID:123 the response for this would be the NetAmount: 1000.00 after sending it using AJAX GET REQUEST, so for other data it would just return an undefined value.
MY AJAX
function viewBill(AccountNum){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "GET",
url: "{{ route('view.billing') }}",
data: {AccountNum:AccountNum},
dataType: 'json',
async: true,
beforeSend: function() {$('#userBill').html('Getting Information...')},
success: function(res) {
console.log(res.NetAmount);
$('#checkBill').css('display','block');
$('#userBill').html('₱ '+res.NetAmount);
},
error: function(res) {console.log('Error');},
complete: function() {
}
});
}
My Controller
public function viewBilling(Request $request){
if($request->ajax()){
$viewBilling = Table1::addSelect(['PaymentStatus' => Table2::selectRaw('COUNT(*)')
->whereColumn('AccountNumber','Table1.AccountNumber')
->whereColumn('ServicePeriodEnd','Table1.ServicePeriodEnd')
->where('AccountNumber', $request->AccountNum)
])->where('AccountNumber', $request->AccountNum)
->orderBy('ServicePeriod','desc')
->first();
return Response()->json($viewBilling);
}
}
I tried using dd() and it turns out there are values for the account I tried from the one that returns the NetAmount and from the one that returns an undefined value.
Found the problem, because of the parameter of my viewBill() function, I don't know why would it give me undefined values from other data I did check using the network tools, it just that it wasn't able to send the AccountNumber to the Controller. So I tried removing the parameter. I have an input tag that already has the value of the Account Number so instead of using the above code, I did this
function viewBill(){
var AccountNum = $('#inputAccountNum1').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post({
url: "{{ route('view.billing') }}",
data: {AccountNum:AccountNum},
dataType: 'json',
beforeSend: function() {$('#userBill').html('Getting Information...')},
success: function(res) {
$('#checkBill').css('display','block');
$('#userBill').html('₱ '+res.NetAmount);
},
error: function(res) {console.log('Error');},
complete: function() {
}
});
}

Laravel - DELETE Ajax request

I am using Laravel 5.0. I have created a RESTful Controller. Now i wanna use the destroy function via an ajax call.
This is my JS:
$.ajax({
type: 'POST',
url: '/pv/' + data.id,
data: {_method: 'delete' },
success: function(data){
console.log(data);
}
});
And this is my destroy function:
public function destroy($id)
{
$pv = PV::find($id);
$pv->delete();
return true;
}
All i got is a 500 error.
first check your route in laravel
Route::delete('/deleteprocess', 'Controller#destroy');
in javascript
$.ajax({
url: '/deleteprocess',
type: 'POST',
data:{
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
},
success: function(result) {
// Do something with the result
}});
set type : POST,
set token : _token,
set method : _method as DELETE,
That's probabily a "CSRF" Exception. If you are using Ajax Request with jQuery, add this (before your $.ajax):
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
And, in your "html" ..create a new "meta tag" with csrf-token..value:
{{ csrf_token() }}
Read more: http://laravel.com/docs/5.0/routing#csrf-protection

Redirecting after Ajax post

I want the success on ajax post to go to the home page. For some reason I keep doing it wrong. Any idea what I should do to fix this?
window.APP_ROOT_URL = "<%= root_url %>";
Ajax
$.ajax({ url: '#{addbank_bankaccts_path}',
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
dataType: "json",
data: 'some_uri=' + response.data.uri ,
success: function(APP_ROOT_URL) {
window.location.assign(APP_ROOT_URL);
}
});
success: function(response){
window.location.href = response.redirect;
}
Hope the above will help because I had the same problem
You can return the JSON from server with redirect status and redirect URL.
{"redirect":true,"redirect_url":"https://example.com/go/to/somewhere.html"}
And in your jQuery ajax handler
success: function (res) {
// check redirect
if (res.redirect) {
window.location.href = res.redirect_url;
}
}
Note you must set dataType: 'json' in ajax config. Hope this is helpful.
Not sure why, but window.location.href did not work for me. I ended up using window.location.replace instead, which actually worked.
$('#checkout').click(function (e) {
e.preventDefault();
$.ajax('/post/url', {
type: 'post',
dataType: 'json'
})
.done(function (data) {
if (data.cartCount === 0) {
alert('There are no items in cart to checkout');
}
else {
window.location.replace('/Checkout/AddressAndPayment');
}
});
});

Resources