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 ......
Related
Laravel AJAX Request not working of a restful controller of a method.
This AJAX request does not work on create method but it works on index method of a laravel resource controller.
The first link is worked as it is index method. And the second link is create method which does not work. Both code are same
http://thetoppinghouse.com/laravel/public/listing
http://thetoppinghouse.com/laravel/public/listing/create
Here you will get my code summary
http://laravel.io/bin/roYBY
I have already post this question without live example here but could not get solution.
Laravel Ajax request not working of a controller
Here is my AJAX code summary
// AJAX Requesst
<script>
$('#parent_ID').on('change',function(e){
console.log(e);
var cat_id = e.target.value;
// AJAX
$.get('ajax-subcat?cat_id=' + cat_id, function(data){
$('#subcategory').empty();
$.each(data, function(index, subcatObj){
$('#subcategory').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>')
});
console.log(data);
});
});
</script>
And routes is here
// routes.php
Route::resource('listing','ListingController');
Route::get('ajax-subcat', function(){
$cat_id = Input::get('cat_id');
$subcategories = Subcategory::where('parent_ID', '=', $cat_id)->get();
return Response::json($subcategories);
});
The problem is that your javascript code is making the ajax request to ajax-subcat?cat_id=1, a relative URL. This means:
/laravel/public/listing => /laravel/public/ajax-subcat
/laravel/public/listing/create => /laravel/public/listing/ajax-subcat
Since you already have your javascript inside the blade template you can easily let Laravel generate the URL:
// AJAX
$.get('{{ URL::to('ajax-subcat') }}?cat_id=' + cat_id, function(data){
$('#subcategory').empty();
I am developing an application with angular js
Question: When I have an ajax call to server and I need to change the views based on the result of ajax call, the views don't get affected by this call, I think it the page renders before ajax call is finished but I don't know how to resolve it
For example the following piece of code
$scope.addItem = function() {
$http({
method :'GET',
url : 'addItem',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success( function(data) {
$scope.allItems = data;
});
}
the allItems changed after the ajax call but the view is not changed
how should I solve this?
I hope you can help,
I am relatively new to mootools
I have been using http://zendold.lojcomm.com.br/fvalidator/ to validate some webforms and I wanted to try and use it with an Ajax form. It is an oldish website using Mootools 1.2.5.
http://jsfiddle.net/jessicajet/gTqV8/ is the form I am trying to use it with. (The fValidator script is not added here)
This is what I am using to submit the form
formtostop.addEvent("submit", function(e) {
e.stop();
new Request({
url: this.get("action"),
method: "post",
data: this,
onRequest: function() {
document.id("result").set("html", "sending...");
},
onComplete: function() {
document.id("result").set({html: '<div class="response"><p>Thank you for completing our contact form, we will get back to you as soon as possible</p></div>', style: 'background:red'});
}
}).send();
});
When I hit submit the validation and the ajax form fires, which is to be expected.
Can I get the submit button to look for the validation script before the e.stop(); new Request({ or am I trying to do something not possible?
I will appreciate any advice that can be offered.
http://zendold.lojcomm.com.br/fvalidator/js/fValidator-full.js, take a look at the _onSubmit function. You should extend this class (http://mootools.net/docs/core/Class/Class) and modify the _onSubmit function to do a request if the isValid statement is true.
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")'
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.