Rachit Shah
Rachit Shah

Reputation: 53

Trying to redirect from AJAX post

I am trying to call a webmethod from AJAX which is redirecting to a url like this:

HttpContext.Current.Response.Redirect(StoreCode.ToLower() + "/App/home.html?EventClick=True", false);

AJAX call:

function TokenPost() {
    var token = $('#hdnToken').val();
    $.ajax({
        url: 'http://localhost/QDC/WebServices.asmx/ChkToken',
        type: 'POST',
        data: "{data:'" + token + "'}",
        contentType: 'application/json; charset=UTF-8',
        datatype: 'JSON',
        success: function(response) {

        },
        error: function(response) {
            alert(response.d);
        }
    });
}

But my AJAX call is not redirecting to that url.Thanks in advance.

Upvotes: 4

Views: 3585

Answers (1)

Murat Acarsoy
Murat Acarsoy

Reputation: 304

I think it' s not possible in HttpPost Methods. But you can return link in your HttpPost method from server. And redirect with Javascript Code if ajax returns success.

        $.ajax({
            url: 'http://localhost/QDC/WebServices.asmx/ChkToken',
            type: 'POST',
            data: "{data:'" + token + "'}",
            contentType: 'application/json; charset=UTF-8',
            datatype: 'JSON',
            success: function (link) {
                window.location.href = link;
            },
            error: function (link) {
                alert(response.d);
            }
        });

In Server Method (I am using this in ASP.NET MVC):

string link = "https://...Your Link";

return Json(link, JsonRequestBehavior.AllowGet);

If you are using WebMethod, I think you can return just string, too.

[System.Web.Services.WebMethod]
public static string ChkToken(string data)
{
    string link = "...";
    // Do things
    return link;
}

This time ajax return can be like this,

            success: function (link) {
                window.location.href = link.d;
            },

Upvotes: 3

Related Questions