Redirect to another page after Ajax call? - javascript

so this is a hard one for me to try and explain. I have a razor page that when a button is clicked it calls a javascript function which makes an ajax call to a handler in the back end. The handler does some stuff and gets a id that I want to pass to another page. I am trying to use the RedirectToPage function in the back end but the screen never opens. It successfully calls the handler but when the handler does its return, nothing happens. Is there a way to do this?
Here is the javascript/ajax code that gets called from a button being clicked.
#section scripts{
<script>
// Get the account ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
},
});
});
</script>
}
For my code behind code that I am calling from the ajax call, that's below here:
public ActionResult OnPostCopyData (string accountid)
{
// Do my other stuff here
return RedirectToPage("Account_Information", new { id = account.Account_ID });
}
Any help would be appreciated and if doesn't make sense, I can try and clear up any questions.

I think this is what you want, I did something similar in an MVC 5 project and I haven't tested it in Razor Pages yet:
This would be your method, note that you should add your Controller to the Url.Action, and I personally haven't tried passing a parameter along with the url but I image it'll work just fine
[HttpPost]
public ActionResult SubmitSomething()
{
return Json(new { redirectUrl = Url.Action("Account_Information", "YOUR_CONTROLLER_NAME", new { id = account.Account_ID }) });
}
And then this would be your Ajax request, I updated the success portion
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.redirectUrl !== undefined) {
window.location.replace(result.redirectUrl);
} else {
// No redirect found, do something else
}
},
});
});
This isn't tested, so I can only hope that it works for you right now
Edit: Updated the Url.Action to use OP's view names and parameters

Redirect to page returns a 301 response, which will be in the format:
HTTP/1.1 301 Moved Permanently
Location: http://www.example.org/index.asp
To redirect after the ajax call you can redirect to the requested url by:
success: function (result) {
window.location = result.getResponseHeader('Location');
}

Related

ASP.net: AJAX Result Not Kicking Off

I think this will be a weird one for you as I am at my wits end with this. On a screen I have in a table, I have a link being clicked that is setting off a javascript/ajax request. I have similar code in another screen that works perfectly as it heads down into the success part of the ajax call and runs code in the success portion of the call. For some reason though I can't seem to get this to work and when I debug it in chrome, I lose my breakpoints and it never seems to get into the success portion of the Ajax call.
#section scripts{
<script>
// Get the bond ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.updatelink').click(function () {
var bondid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Maintenance/Bond_Maint?handler=UpdateandReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { bondid: bondid },
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
});
});
</script>
}
The ASP.net code behind that is calling does an update to the database and then passes back a variable containing Success as its message.
//-------------------------------------------------------------------------------
// Try to get and insert the data from a selected row and copy it
//-------------------------------------------------------------------------------
public ActionResult OnPostUpdateandReloadData(string bondid)
{
return new JsonResult(new { pass = "Success" });
}
I'm not sure how else to describe my issue other than when I debug my other code via the browser, it appears to take a different path than this code does and I cannot fathom why. For reference my other code looks like this:
#section scripts{
<script>
// Get the offender ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var offenderid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.path != undefined) {
window.location.replace(result.path);
}
},
});
});
</script>
}
Any help would be appreciated.
Okay guys so first off, thank you everyone for responding to my question. Frank Writte and Alfred pointed me into the right direction by looking for the status in the network tab for my calls. I found out that I was getting cancellations for my requests. After looking into that I found this article What does status=canceled for a resource mean in Chrome Developer Tools? that has an answer from FUCO that gave me what I needed to do. Apparently I needed to add event.preventDefault(); in front of my ajax call and all of a sudden my code worked. I'm not sure I completely understand why this works but I can't complain about the results. Again thank you everyone for trying to help. This one has been boggling my mind all morning.

ASP MVC Refresh partial view grid

I am trying to refresh a partial view grid after changing a record.
I have a button where the user can click on, than it will change a row in the grid. This works OK, however. I have to manually refresh the page to see the modification. Now I thought I could make a new JavaScript Ajax function to do this. So after the user push the button it will load the function RefreshGrid
JavaScript Function:
function RefreshGrid() {
var numberPlate = $("#NumberPlate").val();
if (numberPlate) {
$.ajax({
type: 'get',
url: appPath + '/Service/Grid',
data: { numberPlate: numberPlate },
success: function (response) {
$("#Grid").html(response);
},
error: function (response) {
$("#dialog .modal-body").html(msgErrorDuringRequest);
$("#dialog #dialog-title").html(errorTitle);
$("#dialog").modal("show");
}
});
}
}
Now the controller
public ActionResult Grid(string numberPlate)
{
IList<ServiceOrder> services = ServiceRepository.Services(numberPlate);
return PartialView("_Grid", services);
}
For some reason it is returning me the error function
error: function (response) {
$("#dialog .modal-body").html(msgErrorDuringRequest);
$("#dialog #dialog-title").html(errorTitle);
$("#dialog").modal("show");
}
But I have no idea where it goes wrong. Cant really imagine it is in the controller as I have a familiar function elsewhere which works flawless but perhaps I am missing something.
try code:
Remove The All your jquery code ,just used below the code your RefreshGrid Function
var numberPlate = $("#NumberPlate").val();
var url= '/Service/Grid?numberPlate='numberPlate;
$("#Grid").load(url);

How to call a function in another MVC controller using AJAX in Jquery

My folder structure looks like this. Both of these folders are contained within the Area folder.
I am trying to call a function from the EmailController inside ITRequests/Scripts/Edit.js and it fails to find it.
The .js code look likes this
$(document).on('change', '#StatusId', function (event) {
event.preventDefault();
debugger;
if(( $('#OldStatus').val() ) != ( $('#StatusId').val()) ) //Aka if the user switched the status on submit
{
var status_description = [$('#OldStatus').val(), $('#StatusId').val()];
$.ajax({
url: "/Email/Email/statusChangeEmail",
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'request': $('#RequestId').val(), 'status_descriptions': status_description }),
done: function (data) {
debugger;
alert("working");
}
})
}
})
RequestId is a hidden value on the page which is being picked up correctly, likewise the status_description field is taking the correct values and (tries to) pass them to the function.
The function EmailController.cs is defined as such
[HttpPost]
public ActionResult statusChangeEmail(int request, string[] status_descriptions)
{
//stuff happens
return Json(1);
}
However every time this happens I get this error message
Why your URL is /Email/Email/statusChangeEmail? It should be /Email/statusChangeEmail.
The /Email means EmailController and /statusChangeEmail means controller action statusChangeEmail .

jquery and ajax request

I have js function which sends ajax request to the controller and succ. return result and append that result into desired div inside partial page. Now I want to implement pagination and I'm using $("#dataList").on("click", ".pagedList a".getPage); to listen when user click on pagination links to determine which page number is clicked
var getPage = function () {
var $a = $(this);
GetTabData(a);
return false;
}
and finally I'm sending pagenumber to the next function which sends pagenumber together with activeTab variable to the controller
function GetTabData(xdata, pageNumber) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: JSON.stringify({ activeTab: xdata, page: pageNumber }),
success: function (result) {
$("[id^='tab-'] div").remove();
var currentTab = $("#tab-" + xdata).html(result);
},
error: function () { alert("error"); }
});
}
Something is definit. wrong here cause on controller side I'm using
Request.IsAjaxRequest()
to allow only ajax request to paginate data and I'm getting Not ajax request. Once more, If I remove pagination option completly and send just activeTab everything works.
Any thoughts?
Your GetTabData function takes 2 arguments: xdata and pageNumber but when calling it you are passing only one:
var $a = $(this);
GetTabData(a);
So you probably are getting a javascript error and the return false statement is never reached.

How do I reload the page after all ajax calls complete?

The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData function) and uses them to get more information from a thirdparty service (getInformation function). This getInformation function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
In your getInformation() call you can call location.reload() in your success callback, like this:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any further ajax calls complete, you can use the ajaxStop event, like this:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
.ajaxStop() works fine to me, page is reloaded after all ajax calls.
You can use as the following example :
$( document ).ajaxStop(function() {
window.location = window.location;
});
How it's works?
A: Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.
Hope help y'all, furthermore information, I'm sharing the link of the documentation following.
source: https://api.jquery.com/ajaxstop/
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
//document.location.reload(true);
window.location = window.location;
See more at: http://www.dotnetfunda.com/forums/show/17887/issue-in-ie-11-when-i-try-to-refresh-my-parent-page-from-the-popupwind#sthash.gZEB8QV0.dpuf

Categories

Resources