Alert on Save Click in MVC3 - asp.net-mvc-3

when i click on the save button. I want javascript Alert come that "data saved Sucessfully". How i do this in MVC3..
thanks

You can send a json result back from the server with a success or fail message. Then simply on the complete method of an ajax request, read your json result and display the message accordingly.
Your client side script will look like something like this (if using jQuery):
$("#SubmitBtnId").click(function() {
$.ajax({
type: "POST",
url: "controller/action",
data: "name=FormName&location=Florida",
complete: function(data){
if(data.Success) { alert(data.Message); }
}
});
});
Make sure you return from your controller a Json result that includes a Success property. You can do this like
return Json(new
{
Success = true,
Message = "Data saved Successfully"
});

You can pass a flag in the ViewBag to the View to say the data is successfully saved. In the view then you can trigger a javascript variable which will in turn trigger the alert. Hope this helps.

Related

How to perform ajax call to doaction in ofbiz

I would like to use Ajax to perform an action in OFBiz without the page refreshing. The task will be like filters. When I choose any Checkbox it should perform some action and display the result in the very same page.
What are all the steps i need to do?
I would appreciate some sample code for controller.xml,javascript calling Ajax ..etc
Thanks.
You can use form submission through ajax on an event in your ftl's. Here's a sample code for ajax call from say an ExampleCreateParty.ftl:
$.ajax({
url: '<#ofbizUrl>addSecurityPermissionToSecurityGroup</#ofbizUrl>',
type: 'POST',
accepts: 'xml',
data: $("form#Permissions").serialize(),
success: function(e) { console.log(e);
var xmlDoc;
try {
xmlDoc = $.parseXML(e);
var error = $(xmlDoc).find("Message").find("Error").find("ErrorCode").text();
var errorMsg = $(xmlDoc).find("Message").find("Error").find("ErrorMessage").text();
if (error=='0'){alert(errorMsg);}
console.log(xmlDoc);
} catch (err) {
alert('Saved Successfully!');
}
},
error: function(e) { console.log(e); }
})
Here in response to the service called i.e. addSecurityPermissionToSecurityGroup you can specify the response in the controller.xml which you can get within the success key in the ajax call itself.
To see a full end-to-end example have a look at this OFBiz page
As you can see whenever you change the product configuration, the product price is updated with Ajax call. Then you can find out for yourself the freemarker file containing javascript and the controller doing calculations and returning it back.

Why does an ajax form inside of an if statement submit twice if it is submitted after first failing the condition?

Consider the code below. If myField1 does NOT equal myField2, then the alert appears. When I click okay on the alert pop up my form is still there, with all of the fields still populated with the data I had previously entered. However, when I modify the fields so that myField1 DOES equal myField2, and then submit the form it is actually submitted TWICE! Why is this?
$(document).ready(function(){
$("#myForm").submit(function() {
var myField1 = $('#myID1).val();
var myField2 = $('#myID2).val();
if(myField1 == myField2)
{
$.ajax({
type: "POST",
url: 'myFile.php',
dataType: 'html',
data: {myData:myField1,
myData2:myField2},
success: function(data){
alert(data);
}
});
return false;
}
else
{
alert('These two fields are not equal!)
}
});
});
Okay, so I found this on another question and it solves the problem:
$('#myForm').unbind('submit').bind('submit',function() {
// do stuff here...
});
By unbinding the event, then re-binding it, the form no longer submits twice.
Your submit event is going to fire the submit action of the form unless you prevent it from doing so. Running an AJAX call in does not prevent this from happening. You need to stop this yourself.
You need:
$("#myForm").submit(function(event) {
event.preventDefault()
...

prevent redirection on submit to form

I have the following code I am using to submit my form to a processing script. the form gets submitted but I am getting redirected to the response html from the server. I want to stay on the same page and run the callback function inside success:
the response header is sending
location:http://url-I-am-Redirected-to-and-don't-want-to-be.html
I am working with third party and have no control over the server side code I am submitting to.
$('#go').click (function () {
$.ajax ( {
type: 'POST',
data: $('#newsletter form').serialize(),
url: $('#newsletter').attr('action'),
success: function(){
$('#image_container').hide (1000,
);
}
});
}
At the end of the click block add
return false

Alert is coming before response

I have this ajax function which validates the user provided key. but the alert comes before the ajax response and due to which if the user provide a wrong key even can get access
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
var key = $('#downloadkey').val();
var dataString = {KEY:key};
$.ajax({
url: "/mediabox/home/validate_key",
type: 'POST',
data: dataString,
success: function(msg) {
if(msg=="true")
{
alert("do something");
}
else
{
alert("Your download key is either wrong or you didn't provide it.");
return false;
}
}
});
});
});
What makes you believe the alert is coming before the response? The success handler is only invoked after the response has been successfully received client-side.
To confirm, you can edit your success handler to log the response:
success: function(msg) {
console.log(msg);
if(msg=="true")
{
alert("do something");
}
else
{
alert("Your download key is either wrong or you didn't provide it.");
return false;
}
}
Also, if you're using the return false to deny access to the user by blocking the HTML action that, won't work due to the asynchronous nature of AJAX.
The success function is called when the request completes.
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.
The code within the success handler will only execute once the AJAX request is completed. If you are getting an alert before hand then that indicates that the request completed properly.

JQuery not return any status like Success, Failed, Completed

Experts,
The following function are successfully send data to the Controller.cs (server)
var ajaxResponse = $.ajax({
type: "post",
url: href,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (msg) {
alert("Success");
}
})
but i am not able to get updated status from the following method
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveData(TabMasterViewModel postData)
{
string message = "";
try
{
TabMasterViewModel update = new TabMasterViewModel();
update = _tabmasterService.GetSingle(r => r.colID == postData.colID);
UpdateModel(update);
_tabmasterService.Update(update);
message = "Success";
}
catch (Exception e)
{
message = e.Message;
}
return Content(message);
}
I would like to display message when failed or success. this following line never execute
success: function (msg) {
alert("Success");
}
but my server side code is executed without any error.
Please provide your valuable suggestions,
Thanks,
Imdadhusen
Instead of returning ActionResult you should be returning JsonResult
For example
public JsonResult SaveData() {
return Json(new {success=true, msg="Saved ok"});
}
then your JS
success: function (msg) {
if(msg.success)
alert("Success");
}
You are returning Content result where as in JQuery you have mentioned dataType: 'json'. I would suggest you to either return JSON result from your controller or remove the dataType from jquery call.
I am not sure about this, please give it a try.
Hit a breakpoint in Firebug on the send line of ajax script.
Hit a breakpoint in Firebug on the success method callback.
Hit a breakpoint in Visual Studio on the first line of action method.
Follow the steps to reproduce the scenario, and inspect the objects in Firebug before sending the request, continue and hit F8 to send the request, check the Net tab page in firebug and see if any request was sent or not.
If it was sent, inspect the posted request.
if until now everything is ok continue the process in the server side on VS and check if everything is right.
then check the response on the Firebug and see if nothing goes wrong.
The obvious thing first: are you sure your url is valid? (I guess it is, since you state that the data is sent successfully).
Have you tried monitoring the ajax request to see what http status you recieve?
Anyways, .ajax also has a error callback you can use in case of the request failing all together.
An apropos: where does the return from you function go?
You have to send the reply to the output buffer for it to reach the client. Simply returning will send a null response to the client (but it shouldn't matter in this case since the .ajax success callback should trigger on request readyState 4 + status 200).

Resources