Jquery Ajax - Alert firing twice - c#

The code below is triggered on a click of a button and having followed the request through, it is only being triggered once. Also, having stepped through, the code is only triggered once, however, the alerts show twice. Any suggestions for why?
$.ajax({
url: '#ConfigurationManager.AppSettings["AppDirectory"]/OperatorApplication/PafSearch/' + pafPostcode.val(),
type: 'POST',
success: function (response) {
addressList.empty();
addressSelection.hide();
if (response == null) {
alert("No addresses found for the postcode provided.\n\nPlease enter your address manually");
}
//other processes removed...
}
});

How did you bind the click event to the button? Or did you bind the same event multiple times?
Is it like this:
$("#targetButton").on("click", function(){
$.ajax({
url: '#ConfigurationManager.AppSettings["AppDirectory"]/OperatorApplication/PafSearch/' + pafPostcode.val(),
type: 'POST',
success: function (response) {
addressList.empty();
addressSelection.hide();
if (response == null) {
alert("No addresses found for the postcode provided.\n\nPlease enter your address manually");
}
//other processes removed...
}
});
return false;
})

Related

MVC RedirectToAction Doesn't Work After JSON Post Return

I am trying to change the page after post process of the AJAX process which executes by MVC. I have used it different way maybe my usage might be wrong.
C# MVC code part. I am sending int list which is user list and process and do something.
[HttpPost]
public ActionResult SelectUserPost(int[] usersListArray)
{
// lots of code but omitted
return JavaScript("window.location = '" + Url.Action("Index", "Courses") + "'"); // this does not work
return RedirectToAction("Index"); // this also does not
return RedirectToAction("Index","Courses"); // this also does not
}
My problem is redirect part do not work after the MVC process ends. Process works, only redirect doesn't.
JavaScript code here
// Handle form submission event
$('#mySubmit').on('click',
function(e) {
var array = [];
var rows = table.rows('.selected').data();
for (var i = 0; i < rows.length; i++) {
array.push(rows[i].DT_RowId);
}
// if array is empty, error pop box warns user
if (array.length === 0) {
alert("Please select some student first.");
} else {
var courseId = $('#userTable').find('tbody').attr('id');
// push the id of course inside the array and use it
array.push(courseId);
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
}
});
Added this to AJAX and it is not working too
success: function() {
window.location.href = "#Url.Content("~/Courses/Index")";
}
Once you are using AJAX the browser is unaware of the response.
The AJAX success in its current form failed because redirect response code is not in the 2xx status but 3xx
You would need to check the actual response and perform the redirect manually based on the location sent in the redirect response.
//...
success: function(response) {
if (response.redirect) {
window.location.href = response.redirect;
} else {
//...
}
}
//...
Update
Working part for anyone who need asap:
Controller Part:
return RedirectToAction("Index","Courses");
Html part:
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Successful!");
window.location.href = "#Url.Content("~/Courses/Index")";
}
});
Just deleted
dataType: 'json'
Part because I am using my own data type instead of JSON.

Pass Option Select Value to Controller

im trying to get the value each time a client selects a option from my Dropdown list to send it back to controller where i use the value on creating a file and then refreshing the page but im unable to do so
This is my Dropdownlist:
<select id="sel0">
<option value="">Todos</option>
#foreach (var item in Model.Select(l => l.Fecha).Distinct())
{
<option value="#lines">#lines</option>
}
</select>
This is my Ajax Call:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
});
$("form").submit(function () {
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
and this is my Controller its named 'HomePosController':
public ActionResult MethodName(string Selected)
{
var db = new ArponClientPosContext();
String value = Selected;
var json4 = JsonConvert.SerializeObject(Selected);
System.IO.File.WriteAllText(#"C:\inetpub\wwwroot\potzolcalli.brain.arpon.com\valorselected.txt", json4);
return View("~/Views/HomePos/Index.cshtml", db.Pos.ToList());
}
But whenever y select a option of my dropdown nothing happens, the page its not refreshed nor the file is created what am i doing wrong?
If you want it to be on dropdown change then you have to send ajax call in change event :
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePos")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
and you have to not write complete Controller class name, you have to skip the Controller postfix, it is convention which is followed by Url helpers in mvc, that way your url generated will be wrong and ajax call will fail.
whenever y select a option of my dropdown nothing happens
Well, this happens:
dataTable.columns('.fechas').search(this.value).draw();
But that doesn't invoke the AJAX request. It doesn't do much of anything, really.
how can i trigger the ajax ? i want it to trigger after a value is changed in the dropdown list
In that case you want to do that on the select element's change event. Currently you perform the AJAX request here:
$("form").submit(function () {
// AJAX
});
That is, you perform the request in the form's submit event. Just add it to the drop down's change event instead:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
the page its not refreshed
Well, no. That won't happen in an AJAX request. Currently your success callback is empty, so nothing will happen on the page. Whatever you want to happen would need to be put in that callback.

Need to go Javascript Method before hit the MVC controller method

I have MVC project. I need to do client side validation on run time. When click the form submit button I need to hit JavaScript Method first and then it is return true move to Controller method.
Just Assume following code type:
JavaScript OnClick Method:
$(function () {
$('#btnSave').on('click', function (event) {
$.ajax({
url: '/Service/Utility/ThresholdValidation',
type: $("#addNewOrderForm").attr('method'),
data: $("#addNewOrderForm").serialize(),
success: function (data) {
if (data != "") {
event.preventDefault();
alert(data);
return false;
}
else {
return true;
}
}
});
});
});
Controller Method:
[HttpPost]
[BaseAuthenticationFilter(UserTypeEnum.Admin, PermissionEnum.CanSendRemittance)]
public ActionResult Create(Invoice model)
{
// Method Goes here
}
Here I cant popup validation alert message. When I click the button it will hit the Controller method. I need to go first javascript method and then if true go to controller method
Please help this.
Try following code, you have to return false in click handler directly instead of ajax response event. because ajax is asynchronous it will execute the ajax and call out from event handler immediately before getting the response of ajax.
So check if data not exists then submit the form otherwise show validation message
$('#btnSave').on('click', function (event) {
$.ajax({
url: '/Service/Utility/ThresholdValidation',
type: $("#addNewOrderForm").attr('method'),
data: $("#addNewOrderForm").serialize(),
success: function (data) {
if (data != "") {
alert(data);
}
else {
$("form").submit();
}
}
});
event.preventDefault();
return false;
});

how can i prevent code behind method call in asp.net

I am creating registration page and doing null field validation on submit button click using jquery. if there is any error in form validation then i am preventing default method call using jquery, so it will not call code behind button click event.
Problem:
sometimes user double clicked on button and this is calling code behind button click event two times with two database row insertion having a same data.
I tried lots of solution but unfortunately i couldn't make any success.
Please help me to solve out this problem if you have any solution.
Thanks in advance,
Actually, i was preventing default server side method call in jquery when button is clicked using e.PreventDefault() method of jquery if validation is false.
Don't know what was the problem but when i set function on client click of button and return true/false based on validation instead of e.PreventDefault, trick worked great for me.
Thanks to all who comment on this question.
Simply add a variable called 'loading' for example and check if the ajax call is busy:
At the top of your code:
var loading = false;
Then on form submit:
$('#form').submit() {
if(loading)
return false;
loading = true;
//Ajax call
$.ajax({
type: "POST",
url: "somePage.php",
data: $('#form').serialize(),
success: function(response) {
loading = false;
//Your response code
}
});
}
Use one on the client side. This will prevent double clicks.
$("#button").one("click", function() {
// validate the form.
// if form is valid, submit form
});
An alternative solution is to have a boolean flag.
var submitting = false;
$("#button").click(function() {
if (!submitting) {
submitting = true;
if (formIsValid) {
submitting = false;
$("#form").submit();
} else {
submitting = false;
}
}
});
Add disabled attribute to your button as the first thing in your js method.
function func(event) {
$("#button").prop("disabled", true);
.....
}
try this it might help for your asp button
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" UseSubmitBehavior="false" OnClientClick="ValidationCode(event); return false;" />
<script>
function ValidationCode()
{
//Code of validtion
event.preventDefault();
if(true)
{
__dopostback:("btnSubmit","");
}
}
</script>
Sample code
Client Side:
$("#submit").click(function () {
if (!YourvalidationFunction)
{
return false;
}
else {
//ajax_function is a folder contain Default.asmx page and insertNewRecord is function name (server side)
$.ajax({
type: "POST",
url: "ajax_function/Default.asmx/insertNewRecord",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessinsertingwcCall,
error: OnErrorCall
});
}
});
Server Side:
[WebMethod]
public string[] insertNewRecord(string prefix)
{
string status = "";
List<string> d = new List<string>();
try
{
// logic code for insertion if success set msg
status = "New record inserted";
}
catch (Exception ac)
{
status = " Error occurs";
}
d.Add(string.Format("{0}", status));
return d.ToArray();
}

Click event not fireing when page is inactive for some time

Ok, this is my problem :).
I have couple of [WebMethods] in my code behind and using jquery ajax to get data from server.
And then it happens :). After some time while page is inactive when i try to click on button which should have send request to server it simply does nothing for about half of minute and only then event is fired and i get response from server.
my javascript looks something like this:
addToCart.click(function () {
AddOrRemoveItemToCart($(this));
});
function AddOrRemoveItemToCart(control)
{
var itemId = contol.attr("id");
$('document').ready(function () {
$.ajax({
type: "POST",
url: "Home.aspx/AddOrRemoveItemToCart",
data: "{itemId:" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
SucessAddItemToCart(data.d);
}
},
error: function (textStatus) {
alert(textStatus);
}
});
});
}
function SucessAddItemToCart(data)
{
//DO SOMETHING WITH DATA
}
And my server side code look something like:
[WebMethod]
public static List<CartItem> AddOrRemoveItemToCart(string itemId)
{
List<CartItem> items = new List<CartItem>();
List<CartItem>temp = new List<CartItem>();
bool check = false;
if(HttpContext.Current.Session["items"]!=null)
{
items = (List<CartItem>)HttpContext.Current.Session["items"];
foreach(CartItem c in items)
{
if(c.Id != itemId)
temp.Add(c);
else
check = true;
}
if(!check)
temp.Add(new CartItem{Id = itemId});
}
HttpContext.Current.Session["items"]=temp;
return temp;
}
Normally I would have said your Session expired. But since the event fires after half a minute, it has to be something else.
Try to debug with Firebug and check if AddOrRemoveItemToCart gets called immediately. You can also see the traffic between the browser and the server.
Your event should fire immediately but as Remy said your Session has probably expired, and it takes some time to re-establish the session object and process the request.

Categories