I have an MVC3 project with custom form authentication.
I got the authentication to work fine (I used the "HttpContext.Current.User.Identity.IsAuthenticated" property in order to make sure it worked)
I use on my of my forms an Ajax:
$(document).ready(function () {
$.ajax({
url: '/MyPages/MyControllerFunction',
type: 'POST',
success: function (result) { $('#MyJavaTemplate').tmpl(result).appendTo('#MyHtmlTable'); },
error: function (result) {
$('#errorDisplay').html(result.responseText);
}
})
});
When I get to this page (and the ajax should call this controller's function) I get this error:
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
My controller function:
[HttpPost]
public ActionResult MyControllerFunction()
{
var MyEntity = MyBusinessLogic.GetByID(1);
return Json(MyEntity);
}
(I also tried to add the [Authorized] attribute and it didn't help)
It only happens to me with mhen I call the controller's function through ajax. Before I changed my program to work with form authentication, It all worked. It's as if the user is not authenticated (even though it is)
What should solve this problem?
I'm thinking you have a GET specified on that controller action, where is should be a POST
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult MyControllerFunction()
I FOUND THE SOLUTION !
It was here:
Getting 404s when calling Actions in MVC3 with jQuery
All I had to do is change the:
url: '/MyPages/MyControllerFunction'
to
url: '#Url.Action("MyControllerFunction","MyPages")'
Related
I want to render a cakephp3 template by ajax and inject the html into a loaded page (without reloading the page).
According to
CakePHP 3 and partial View update via Ajax - How it should be done?,
the idea can be
Create dedicated template (*.ctp) file for every ajax action, render
it like any other action but without the main layout and inject the
HTML (kind of variant 1 but with separated VC logic).
It also provides a partial example code:
public function ajaxRenderAuditDetails($id = null)
{
if ($id == null) {
return null;
}
if ($this->request->is("ajax")) {
$this->set("result", $this->viewBuilder()->build()->cell("audits", [$id]));
}
}
May anyone suggest a full example?
For this you have to use a Ajax call for get data from server. In term of CakePhp you will call a controller function using Ajax. This function call a ctp file which render your partial view. Success function of Ajax should updated or append the partial view. A complete example code for this process is here -
Ajax code for call controller function -
$.ajax({
dataType: 'json',
url: basepath/controllername/controllerfunction,
type: "POST",
dataType : 'html',
success: function (data) {
$(selector).html(data);
}
});
public function ajaxRenderAuditDetails($id = null){
$this->viewBuilder()->layout(false);
if ($id == null) {
return null;
}
if ($this->request->is("ajax")) {
$this->set("result", $this->viewBuilder()->build()->cell("audits", [$id]));
}
}
Put your required html or logics in ctp file.
This is not a running code. It is sample example for updating partial view in CakePhp.
I am using Laravel 5.3. I want to insert the data using blade template.But my when i press submit button it gets refreshed every time. what to do? and please anyone tell me how to use ajax url,type,data
If you try to submit via Javascript make sure prevent form default action with e.preventDefault(). This code prevent the form submitted in a regular way. Just add this code to wrap your AJAX call:
$('#form-id').submit(function(e){
e.preventDefault();
$.ajax({...});
});
I just assume you are using jquery if you are talking about ajax. It's really simple. Your laravel routes listen to "post", "get", "patch", "delete" methods.
Everything of these can be created with a ajax request - example:
$.ajax({
method: "POST",
url: "/posts",
data: { title: "Hello World", text: "..." }
})
.done(function( post ) {
// assuming you return the post
alert(post.title + " created");
});
Now that you use ajax you will not want to return a view to the ajax call. You have different options here (create a new route, helper functions etc.) I will give the most easy example
Controller function:
public function store(Request $request) {
$post = App\Post::create($request->all());
if($request->ajax()) {
return $post;
} else {
return redirect('/posts');
}
}
now you controller will return data on ajax calls and will redirect you on default calls without ajax.
Finally you have a last thing to keep in mind. If you have web middleware applied ( done by default ) you need to handle the csrf token. The most easy way to handle this is by adding a meta tag to your html head
and then (before doing all your calls etc.) add this to configure your ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
this will add the valid csrf token which is in your head to every ajax call and will ensure you not run into token missmatch exceptions.
Things to keep in mind:
- if you stay very long on one page tokens might expire ( laravel-caffeine will help here )
- you need to handle validation for ajax calls
I am developing a single page application, with help of AngularJS and I'm new to it
maybe my question is so primitive but at the moment I don't know how to handle it
what I need to do id to open up a pop-up menu after user enters his/her username and password then make a ajax call to Server and if the user is authenticated another view(profile) is displayed.
This is my ajax call
formApp.controller('mainController',function FormCtrl($scope,$http){
$scope.processForm = function() {
$http({
method : 'POST',
url : 'login',
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
console.log(data);
});
};
And this is the routers and views config :
var formApp = angular.module('formApp', ['ngRoute']);
formApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'main',
controller : 'mainController'
})
.when('/profile', {
templateUrl : 'profile',
controller : 'profileController'
})
});
Thanks in advance,
So now in success method call route-change: return $location.path('/profile');
Also, I guess, you need some service where you will keep user's data.
Also, consider to use ngResource (or similar things) to work with REST backend (and don't keep this logic in controller).
Use modal window and inject controller into it and in resolve make the service call which contains your $http request.
see the link for modal window.
Angular-UI
In an ASP.NET MVC3 Application I have a button in the view.
When the button is clicked a function is called and it jquery ajax call is made to save items to the database
function SaveMenuItems() {
var encodeditems = $.toJSON(ids);;
$.ajax({
type: 'POST',
url: '#Url.Action("SaveItems", "Store")',
data: 'items=' + encodeditems + '&storeKey=#Model.StoreID',
complete: function () {
}
}
});
}
What i want is after the items are saved to the database I want to redirect to another view. (Redirect to action)
How can I do that?
I tried to use return RedirectToAction("Stores","Store") in the controller at the end of the SaveItems function. But it is not working
I also tried to add window.location.replace("/Store/Stores"); in the complete function of the ajax call but didn't work either
Any help is greatly appreciated
Thanks a lot
You can use javascript to redirect to the new page. Set the value of window.location.href to the new url in your ajax call's success/complete event.
var saveUrl = '#Url.Action("SaveItems","Store")';
var newUrl= '#Url.Action("Stores","Store")';
$.ajax({
type: 'POST',
url: saveUrl,
// Some params omitted
success: function(res) {
window.location.href = newUrl;
},
error: function() {
alert('The worst error happened!');
}
});
Or in the done event
$.ajax({
url: someVariableWhichStoresTheValidUrl
}).done(function (r) {
window.location.href = '#Url.Action("Stores","Store")';
});
The above code is using the Url.Action helper method to build the correct relative url to the action method. If your javascript code is inside an external javascript file, you should build the url to the app root and pass that to your script/code inside external js files and use that to build the url to the action methods as explained in this post.
Passing parameters ?
If you want to pass some querystring parameters to the new url, you can use this overload of the Url.Action method which accepts routevalues as well to build the url with the querystring.
var newUrl = '#Url.Action("Stores","Store", new { productId=2, categoryId=5 })';
where 2 and 5 can be replaced with some other real values.
Since this is an html helper method, It will work in your razor view only,not in external js files. If your code is inside external js file, you need to manually build the url querystring parameters.
Generating the new url at server side
It is always a good idea to make use of the mvc helper methods to generate the correct urls to the action method. From your action method, you can return a json strucutre which has a property for the new url to be redirected.
You can use the UrlHelper class inside a controller to do this.
[HttpPost]
public ActionResult Step8(CreateUser model)
{
//to do : Save
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Stores", "Store");
return Json(new { status = "success", redirectUrl = url });
}
Now in your ajax call's success/done callback, simply check the return value and redirect as needed.
.done(function(result){
if(result.status==="success")
{
window.location.href=result.redirectUrl;
}
else
{
// show the error message to user
}
});
In action you can write this:
if(Request.IsAjaxRequest()) {
return JavaScript("document.location.replace('"+Url.Action("Action", new { ... })+"');"); // (url should be encoded...)
} else {
return RedirectToAction("Action", new { ... });
}
Try
window.location = "/Store/Stores";
Instead.
I wrote ajax code that works by hitting a button.
<button onclick="clearMessage()" value='myButton'/>
These two are the functions to perform by the button.
function clearMessage(){
var insertedMessage = document.getElementById("insertedMessage").value;
sendMessage(insertedMessage);
document.getElementById("insertedMessage").value="";
}
function sendMessage(insertedMessage){
$.ajax({
type:'POST',
url:("<c:url value='/sendMessage.do' />"),
data:'message='+insertedMessage,
success:function(res){
alert("Success!!!");
},
error: function(){
alert('Fail!!');
}
});
The URL for ajax is '/sendMessage.do', and a method of a Controller has the RequestMapping below.
#RequestMapping(value="/sendMessage.do", method = RequestMethod.POST)
FYI, this project is in Spring MVC, and I made sure that "sendMessage.do" is only assigned to one method.
Hope that I can find a clue to solve ......