5

I'm attempting to use jQuery in order to fire off an Ajax call after clicking a certain button. I've read several examples of the syntax and issues that may be encountered, but have failed to find a working solution for my cause. Here's the code.

Controller Method: (HomeController.cs)

    [HttpPost]
    public JsonResult ChangeCompany(string companyCode)
    {
        return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
    }

jQuery Code:

    function changeCompany(company) {
    $.ajax({
        url: '@Url.Action("ChangeCompany", "Home")',
        type: 'POST',
        data: JSON.stringify({ companyCode: company }),

        success: function (data) {
            alert("Company: " + data);
        },
        error: function (req, status, error) {
            alert("R: " + req + " S: " + status + " E: " + error);
        }
    });
}

And finally, I'm calling this function with:

$('.companyButton').click(function () {
    compCode = $(this).text();
    debug("Click event --> " + $(this).text());
    changeCompany(compCode);
});

My debug message displays properly, and the Ajax call constantly fails with the following alert: R: [object Object] S: error E: Not Found

I'm not entirely sure what to make of that.

I know there are several questions on this topic, but none of them seem to resolve my issue and I'm honestly not sure what's wrong with these code blocks. Any insight would be appreciated.

EDIT: In case it's worth noting, this is for a mobile device. Testing on Windows 8 Phone Emulator (Internet Explorer), alongside jQuery Mobile. Not sure if that affects Ajax at all

EDIT 2: After taking a look at the raw network call, it seems that 'Url.Action("ChangeCompany", "Home")' is not being converted into the proper URL and is instead being called directly as if it were raw URL text. Is this due to an outdated jQuery, or some other factor?

6
  • What does your Controller Action method look like? Also, watch the raw network call in your browser dev tools and see exactly what the call is - that should help troubleshoot. Commented Jun 18, 2013 at 16:02
  • I think it s a server side error. Can you check Chrome's Dev Tool bar Network section when you click the request you can see the response in Preview tab. Commented Jun 18, 2013 at 16:09
  • If you look at the source in your browser, does the url look right? And if you set a debugger; inside the error function, take a closer look at the parameters. Commented Jun 18, 2013 at 16:24
  • I'm running this inside a phone emulator, so the usual browser developer tools aren't available to me. I'll implement a ViewSwitcher so I can test it in desktop browsers and get back to you all on what the dev tools come back with. Commented Jun 18, 2013 at 16:29
  • Okay, please see Edit #2. There's an issue with @Url.Action being parsed into the proper URL Commented Jun 18, 2013 at 16:46

3 Answers 3

6

Ok with your EDIT2 it seems you are using url: '@Url.Action("ChangeCompany", "Home")', in a separate JavaScript file. you can only write the razor code inside the .cshtml file and it is not working inside the .js files

Sign up to request clarification or add additional context in comments.

3 Comments

Ah, that makes sense. Not sure why I thought I could use it outside the view.
Went ahead and hard-coded the URL into the Ajax call and it works fine now, thanks for the catch!
you can create a variable in the .cshtml with the url and access it in the .js file
1

You are missing some important parameters in your AJAX call. Change your AJAX call as below:

function changeCompany(company) {
    $.ajax({
              url: '@Url.Action("ChangeCompany", "Home")',
              type: 'POST',
              data: JSON.stringify({ companyCode: company }), 
              success: function (data) {
                       alert("Company: " + data);
                        },
             error: function (req, status, error) {
                       alert("R: " + req + " S: " + status + " E: " + error);
                        }
          });}

You can then annotate your controller method with [HttpPost] attribute as below;

 [HttpPost]
 public JsonResult ChangeCompany(string companyCode)
 {
   return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
 }

1 Comment

I did the following and received the same error alert. Unsure as to what the issue is.
0

Note that your action is not returning companyCode directly. You're assigning it to Json result property therefore In your success function to display result you need to have:

success: function (data) 
  {
     alert("Company: " + data.result);
  }

Also this: E: Not Found tells me that you may have some routing issues. If you set a break point inside of your ChangeCompany Action, is it being hit ?

Comments

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.