405 error while calling webapi get method using ajax - ajax

I developed a WebApi and Client page for testing.
Here is my controller
public class CarDetailsController : ApiController
{
// GET api/cardetails
[HttpGet]
public IEnumerable<CarsStock > GetAllcarDetails()
{
CarsStock ST = new CarsStock();
CarsStock ST1 = new CarsStock();
List<CarsStock> li = new List<CarsStock>();
ST.CarName = "Maruti Waganor";
ST.CarPrice = "4 Lakh";
ST.CarModel = "VXI";
ST.CarColor = "Brown";
li.Add(ST);
ST1.CarName = "Maruti Swift";
ST1.CarPrice = "5 Lakh";
ST1.CarModel = "VXI";
ST1.CarColor = "RED";
li.Add(ST1);
return li;
}
}
and here is my ajax call
<button onclick="AllcarDetails()"></button>
<script type="text/javascript">
function AllcarDetails()
{
$.ajax({
type: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
contentType: 'application/json',
url: "http://localhost:1822/api/cardetails", //URI
success: function (data) {
debugger;
var datadatavalue = data;
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
</script>
It gives 405 Method Not Allowed error all the time.I tried by googling but cannot find the exact situation.Can somebody help me to solve this?
Got result correctly while calling from browser 'http://localhost:1822/api/cardetails'

Did you check so that HTTP Activation is activated where you run this code?

Related

Why Is This AJAX Request Failing

this is my first time trying to implement AJAX and I haven't been able to figure out why its failing. Apologies, as it's probably easy enough spot for a seasoned AJAX user. I'd appreciate if you took a look.
JQuery File:
//declare variables
var friendSearch;
var csrfHeader = "[[${_csrf.headerName}]]";
var csrfToken = "[[${_csrf.token}]]";
$(document).ready(function(){
//give variables values
friendSearch = $("#friendSearchBox");
//call functions when
$(friendSearch).on('input', function(){
updateFriendsDisplay();
})
});
//functions
function updateFriendsDisplay(){
var jsonData = {searchString: friendSearch.val()}
$.ajax({
type: 'POST',
url: 'http://localhost:8080/friends/search',
beforeSend: function(xhr){
xhr.setRequestHeader(csrfHeader, csrfToken);
},
data: JSON.stringify(jsonData),
contentType: 'application/json'
}).done(function(data){
alert(data);
}).fail(function(){
alert("failed");
});
}
Controller:
#ResponseBody
#PostMapping("/search")
public List<UserAccount> getFriendsBySearch(#RequestParam("searchString") String text){
List<UserAccount> accountsList = uRepo.findByUserNamePortion(text);
return accountsList;
}

Laravel Forbidden Access when using Ajax

I installed a fresh Laravel App with authentication. I am using laragon. The login, registration, reset password pages are working fine. I created a profile controller for the user to edit profile. However, when submitting the form through Ajax, it gives me a Forbidden - You don't have permission to access / / /profile/edit_profile on this server..
class ProfileController extends Controller
{
//
function index()
{
return view('profile.index');
}
function edit_profile(Request $request)
{
$txt_midname = $request->input('txt_midname');
$txt_firstname = $request->input('txt_firstname');
$txt_lastname = $request->input('txt_lastname');
$extname = $request->input('extname');
$user = Auth::user();
$user->firstname = $txt_firstname;
$user->midname = $txt_midname;
$user->lastname = $txt_lastname;
if ($user->save()) {
return 'ok';
}
}
}
Here is also the route:
Route::post('/profile/edit_profile', 'ProfileController#edit_profile')->name('edit_profile');
and the view:
$('#btn_update').on('click', function() {
var btn_text = $('#btn_update').text();
var txt_firstname = $.trim($('#txt_firstname').val());
var txt_midname = $.trim($('#txt_midname').val());
var txt_lastname = $.trim($('#txt_lastname').val());
var extname = $.trim($('#extname').val());
$.post(baseUrl + '/profile/edit_profile', {
'_token': token,
'txt_midname': txt_midname,
'txt_firstname': txt_firstname,
'txt_lastname': txt_lastname,
'extname': extname
}, function(data) {
if (data == 'ok') {
window.location.reload();
}
})
})
You need to inject the csrf token to your request.
$.post({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/gallery/create/ajax',
data: {},
method: 'POST',
success: function(response) {
},
error: function(error) {
}
})
or if you want every ajax request inject the csrf token you can do this as well.
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
It was my mistake. The problem is with my baseUrl in javascript. It should be var baseUrl = "{{url('')}}";instead of var baseUrl = '{{url('')}}';

OnDelete Handler always trigger a bad request

Trying to be more consistent with HTTP verbs, I'm trying to call a delete Handler on a Razor Page via AJAX;
Here's my AJAX code, followed by the C# code on my page :
return new Promise(function (resolve: any, reject: any) {
let ajaxConfig: JQuery.UrlAjaxSettings =
{
type: "DELETE",
url: url,
data: JSON.stringify(myData),
dataType: "json",
contentType: "application/json",
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
});
my handler on my cshtml page :
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
which never reaches ... getting a bad request instead !
When I switch to a 'GET' - both the type of the ajax request and the name of my handler function ( OnGetSupprimerEntite ) - it does work like a charm.
Any ideas ? Thanks !
Short answer: The 400 bad request indicates the request doesn't fulfill the server side's needs.
Firstly, your server is expecting a form by;
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
However, you're sending the payload in application/json format.
Secondly, when you sending a form data, don't forget to add a csrf token:
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
<script>
function deleteSupprimerEntite(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: myData ,
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
__RequestVerificationToken: "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
};
deleteSupprimerEntite(myData);
});
</script>
A Working Demo:
Finally, in case you want to send in json format, you could change the server side Handler to:
public class MyModel {
public int idEntite {get;set;}
public string infoCmpl{get;set;}
}
public IActionResult OnDeleteSupprimerEntite([FromBody]MyModel xmodel)
{
return new JsonResult(xmodel);
}
And the js code should be :
function deleteSupprimerEntiteInJson(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: JSON.stringify(myData) ,
contentType:"application/json",
headers:{
"RequestVerificationToken": "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
},
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
};
deleteSupprimerEntiteInJson(myData);
});

ajax call returning promis and resolve it by the calling function to its value

By now i read somewhere around 6 pages containing documentations and stackoverflow answers but I don't get the method.
My function is by now after reading all the stuff built like this:
async function getFToken(postId){
const response = await $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data:{
action:'get_f_token',
postId: postId,
},
success:function(response) {
}
});
return response;
}
and in my other function is like this:
function getFeedback(postId){
$(".show_company").hide();
$(".show_feedback").show();
$.ajax({
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data:{
action:'get_feedback',
postId: postId,
},
success:function(response) {
var postTitle = '';
for (i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
var test = getFToken(387);
alert(Promise.resolve(test));
};
$("#result").html(postTitle);
}
});
}
is there any chance, that this is a bigger issue because i call a async in another Ajax call trying to retrieve the value? I'm trying to get the string from the first ajax call and hand it to the second function in the ajax call to attach it to the posts i retrieve from WordPress
The alert is giving me [object Promise] but how do i get the value passed from the php script?
php-scrtipt:
//get fToken from specific feedbacks
add_action( 'wp_ajax_get_f_token', 'get_f_token' );
function get_f_token() {
if(isset($_POST['postId'])){
$postId = $_POST['postId'];
}
$fToken = get_post_meta($postId, 'fToken', true);
echo $fToken;
wp_die();
}
Don't use success callbacks when you can use async/await:
async function getFToken(postId) {
return $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data: {
action: 'get_f_token',
postId: postId,
}
});
}
async function getFeedback(postId) {
$(".show_company").hide();
$(".show_feedback").show();
const response = await $.ajax({
// ^^^^^
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data: {
action: 'get_feedback',
postId: postId,
}
});
let postTitle = '';
for (const i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
const test = await getFToken(387);
// ^^^^^
alert(test); // no Promise.resolve, you don't want to alert a promise
}
$("#result").html(postTitle);
}

Jquery ajax goes to error even though result came

I am using spring MVC and JQuery ajax. In one of my ajax call it returns large amount of data it nearly takes 5 minutes.
In Ajax method shows error even though the response came i checked it through firebug.
my ajax coding is
jQuery(document).ready(function () {
jQuery("sampleSearch").click(function () {
jQuery("body").addClass("loading");
var formValues = jQuery('#sample-search-form').find(':input[value][value!=""]').serialize();
jQuery.ajax({
type: "GET",
url: "/sample/user-byName",
data: formValues,
dataType: 'json',
success: function (data) {
jQuery('#json').val(JSON.stringify(data)).trigger('change');
jQuery('body').removeClass("loading");
},
error: function (e) {
alert('Error while request..' + e.toLocaleString());
jQuery('body').removeClass("loading");
}
});
});
});
and in my controller
#RequestMapping(value = "/user-byName", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public
#ResponseBody
String getUserByName(HttpServletRequest request) {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
Integer page = Integer.parseInt(request.getParameter("page"));
String resultJson = getUserByName(firstName, lastName, page);
return resultJson;
}
You need to increase the timeout for the request.
jQuery.ajax({
type: "GET",
url: "/sample/user-byName",
data: formValues,
dataType: 'json',
timeout: 600000,
success: function (data) {
jQuery('#json').val(JSON.stringify(data)).trigger('change');
jQuery('body').removeClass("loading");
},
error: function (e) {
alert('Error while request..' + e.toLocaleString());
jQuery('body').removeClass("loading");
}
});
read more in the .ajax() documentation

Resources