0

I have a jQuery script like below.

$.ajax({
    type: "post",
    url: "/TestPage/Parameter",
    data: JSON.stringify(formData),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',

    success: function (data, textStatus, jqXHR) {
        alert('created!');
    },
    error: function (xhr, status, p3, p4) {
        var err = "Error " + " " + status + " " + p3;
        if (xhr.responseText && xhr.responseText[0] == "{")
            err = JSON.parse(xhr.responseText).message;
        alert(err);
    }
});

My website has a default page www.example.com which is the same as www.example.com/Home/Index.

When I go to www.example.com and trigger the jQuery it works fine. The website sends a request to www.example.com/TestPage/Parameter but when I go to www.example.com/Home/Index and trigger the script, it makes a request to www.example.com/Home/Index/TestPage/Parameter which does not exist.

Is there a way to fix this problem?

3
  • Use the @Url.Action helper in your markup, then parse the form attributes in your jquery. Doing this can make your jquery for posting more generic and reusable too. Commented Oct 17, 2013 at 11:48
  • When working with AJAX calls in ASP.NET MVC I usually have a hidden field with the ID of urlroot with the value of Url.Content("~/"). This way I always have a safe URL root reference. Commented Oct 17, 2013 at 11:49
  • Eh? Your URL is absolute, it should be relative to the root of your website. I don't see how it should be targeting a URL relative to your page. Commented Oct 17, 2013 at 13:10

1 Answer 1

2

Let the ASP.NET MVC helpers do the work for you. In your markup for the form use the @Url.Action helper. See this document

<form action="@Url.Action("Parameter", "TestPage")" method="POST">

In your JQuery you can then parse the form attributes.

var postForm = function (item) {
    var $form = $(item).parents('form:first');
    var options = {
        url: $form.attr("action"),
        type: $form.attr("method"),
        data: $form.serialize()
    };

    $.ajax(options);
}      

call the function on submit, button click whatever and pass in this

$('body').on('click','#create', function () {
    postForm(this);
});
Sign up to request clarification or add additional context in comments.

2 Comments

If the jquery is inside the ASPX page we can use the Url.Action in the javascript directly
I didn't know that, I usually have the JQuery in a seperate file. Might come in handy one day thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.