Jake Lam
Jake Lam

Reputation: 3452

How to use javascript to append the header of request before loading that page

I have 2 html files belong to two different controllers

This is belong to Index action of SignupController

Index.html

<div class="signup-small-font pull-right"><a href="/Account/ResetPassword">Forgot password?</a></div>

When click at this link , it will go to that url and make a request to get the view of the ResetPassword Action of AccountController and get the resetPAssword.html

Now what i want is before making that request , i need to append a custom header in the request for the server side . I was using ajax javascript :

function appendHeader(urlCulture){

$.ajax({
    type: 'GET',
    url: urlCulture,
    headers: {
        "Culture": 'zh'
    },

})
}

What should i do in the index.html anchor link to call this function before requesting for the resetPassword.html

Like what I want is when I click at it , it will navigate to Account/Resetpassword and use the response getting from javascript file to render instead of a normal response

Upvotes: 0

Views: 1329

Answers (2)

Bonestack
Bonestack

Reputation: 81

you are using routes, you need to get the url from the javascript function

there is an example of that here: Get local href value from anchor (a) tag

you could make something similar:

<div class="signup-small-font pull-right"><a onclick="return appendCustomHeader(this);" href="/Account/ResetPassword">Forgot password?</a></div>

in your js function like the previous reply you could make something like this:

function appendCustomHeader(element){

    var url = element.href; // to get full url 

    $.ajax({
        type: 'GET',
        url: url, 
        headers: {
            "CustomHeader": 'YourCustomHeader'
        },
        success: function(res) {
            // here you make anything else with your response
        }
    })

   return false;
}

I've not tested it, I hope it works for you.

it seems you can disable href redirecttion returning false,

see this:

How can I disable HREF if onclick is executed?

Upvotes: 1

Joven28
Joven28

Reputation: 769

In your html file

<div class="signup-small-font pull-right"><a onclick="appendHeader(urlCulture)" href="#">Forgot password?</a></div>

In your js

function appendHeader(urlCulture){
    $.ajax({
        type: 'GET',
        url: urlCulture,
        headers: {
            "Culture": 'zh'
        },
        success: function(res) {
            window.location = 'Account/ResetPassword';
        }

    })
}

Give it a try. Im not quite sure if this is what you want to do.

Upvotes: 1

Related Questions