0

I am trying to make ajax work using getJSON() call. When I navigate to /Home/GetWeather, I get Json data back in the browser. However the jQuery call is not working. Any ideas? When I put a breakpoint on alert("Hello"), it never hit. In firebug I dont see any ajax call. Any ideas?

$(document).ready(function() {
    $("#Button1").click(function() {
        $.getJSON("/Home/GetWeather", null, function(data) {
            alert("Hello");
        });
    });
});​

Controller code

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetWeather()
    {
        List<Weather> weather = new List<Weather>();

        // populate weather with data

        return Json(weather, JsonRequestBehavior.AllowGet);
    }
}

View:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
    <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {

            $("#Button1").click(function () {
                $.getJSON("/Home/GetWeather", null, function (data) { //I hit breakpoint here, but in firebug I dont see any call, nothing
                    alert("Hello"); // Breakpoint here doesnt hit :(
                });
            });

        });

    </script>
</head>
<body>
    <input id="Button1" type="button" name="Button1" value="Get Weather" />
    <div id="Weather"></div>
</body>
</html>

Any reason why the solution I found was removed ???

monstro
  • 6,254
  • 10
  • 65
  • 111
  • Corrent path to your controller? Might be something like `../Home/GetWeather`. Also, you can remove `null` from your call – Johan Jun 24 '12 at 17:15
  • Check that you don't have any problems with Same Origin Policy. See: http://stackoverflow.com/questions/2538215/cross-domain-scripting-issues-jsonp – Katie Kilian Jun 24 '12 at 17:16
  • 3
    @CharlieKilian. He's sending data to the controller, how can he viiolate the same origin policy? – gdoron Jun 24 '12 at 17:19
  • do you get any errors in the firebug or chrome dev tools? have you included the jquery.js? is the `#Button1` anchor tag? – Rafay Jun 24 '12 at 17:20
  • also inspect the full request in console... data sent & returned, status etc – charlietfl Jun 24 '12 at 17:33
  • It is correct, it returns the JSON data as expected. The call to controller DOES NOT fire, that's the problem. – monstro Jun 24 '12 at 17:52
  • public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } public JsonResult GetWeather() { List weather = new List(); // populate weather with data return Json(weather, JsonRequestBehavior.AllowGet); } } – monstro Jun 24 '12 at 17:53
  • breakpoint hits $.getJSON in javascript code, but doesnt actually make the call :( – monstro Jun 24 '12 at 17:58
  • Please show us your view. Most important how the button looks like. – gdoron Jun 24 '12 at 18:06
  • Try this: `alert($)` if the result it `undefined` then you didn't included jQuery right. – gdoron Jun 24 '12 at 18:21
  • 1
    Now you update your question...? the first time you really should write an answer, you edit your question... Please do it. – gdoron Jun 24 '12 at 19:45
  • Why are you using such an old jQuery version (1.7.2 is the recent version). You also shouldn't include the `-vsdoc` version in a way where it's actually used in the browser. It's **only** for visual studio's intellisense. – ThiefMaster Jun 24 '12 at 20:56
  • That's what I did, I updated the first post with the answer. But it was removed by moderator. – monstro Jun 25 '12 at 19:05

3 Answers3

4

As far as I know, you're trying to call it cross domain. Having the code run out of the domain of the site. Before I had the html file call the json running from localhost and it does return nothing. But put that html into the same place, call it from localhost and you will be fine.

CHT
  • 137
  • 1
  • 6
3
  • Don't hard code URL with Asp.Net-MVC use Url.Action
  • Remove the null parameter. Why do you need to send null to the controller? just omit it.

The code to get the route right:

@Url.Action("GetWeather", "Home")

Inside the script:

$("#Button1").click(function () {
    $.getJSON("@Url.Action("GetWeather", "Home")", function (data) {
        alert("Hello");
    });
});
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • It doesn't make any difference if there is null or no null. I dont need Url.Action, I am using jQuery All within the same MVC app. – monstro Jun 24 '12 at 17:48
  • @Sigourney_Weaver. Right, so why keeping it?! Three dots – gdoron Jun 24 '12 at 17:48
  • As I said, it doesn change anything, ok, I remove it if you want, same problem. – monstro Jun 24 '12 at 17:49
  • As I said, when navigating /Home/GetWeather in browser, I get JSON data back. No error in firebug. – monstro Jun 24 '12 at 17:50
  • Actually, as I said I dont see the call being made in firebug. I have no idea why, it should absolutely simple, exactly as in the tutorial. – monstro Jun 24 '12 at 17:51
  • @Sigourney_Weaver. 1. Did you use the `@UrlAction`? 2. Do you have errors in your console? 3. I got the feeling you don't have `"#Button1"` element. Try this: `$("#Button1").click(function() { alert('foo')});` – gdoron Jun 24 '12 at 17:51
  • It doesn't change anything now, but does make it much easier to manage if you start moving stuff around later on. – justinb138 Jun 24 '12 at 17:56
  • What are you talking about @justinb138? Who did you refer to? – gdoron Jun 24 '12 at 17:59
  • Url.Action vs hard-coding a route – justinb138 Jun 24 '12 at 17:59
  • Have you checked your script reference to verify that your jquery.js file is reachable? – justinb138 Jun 24 '12 at 18:00
  • @justinb138. You should use `@Sigourney_Weaver` to make him get your comments. Now I'm the only one see them... and writing them on the question should be a better place. btw, if he didn't include jQuery he would have got an error long time ago. – gdoron Jun 24 '12 at 18:02
  • Not sure I understand how this comments thing works... :) Of course all the references are fine – monstro Jun 24 '12 at 18:22
1

Make sure you cancel the default action of the button if it is a submit button or an anchor by returning false:

$("#Button1").click(function() {
    $.getJSON("/Home/GetWeather", null, function(data) {
        alert("Hello");
    });

    return false; // <!-- cancel the default action of the button
});

Also as @gdoron said in his answer, never hardcode urls like this. Always use url helpers to generate them.


UPDATE:

Now that you have shown your view, I can see that you have hardcoded the url to your scripts:

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script>

You should never do this. You should always use url helpers:

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-1.5.1-vsdoc.js")" type="text/javascript"></script>

Also you should learn to use a javascript debugging tool such as FireBug which makes detecting those errors a peace of cake. If you have used FireBug you would have seen the 404 errors when requesting those scripts.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • But he's mentioning he doesn't see the request in FireBug, if that was the issue, he should have seen it, doesn't it master? – gdoron Jun 24 '12 at 18:04
  • He is not seeing it because he gets redirected and there's no time for the AJAX request to even start. Unfortunately since the OP hasn't shown his view we could only be guessing if this is the case or not. – Darin Dimitrov Jun 24 '12 at 18:04
  • Maybe, I'm waiting to see he's view to be sure. If that's the issue, he should have told us he's redirecting with the anchor... :( – gdoron Jun 24 '12 at 18:06
  • Nothing is redirected, it's not a submit button. – monstro Jun 24 '12 at 18:06
  • Then the code should work and if it doesn't FureBug will tell you why. – Darin Dimitrov Jun 24 '12 at 18:06
  • @Sigourney_Weaver. Is it an anchor? – gdoron Jun 24 '12 at 18:06
  • What anchor? I dont nee any anchor, I am using jQuery, forget about MVC, I could use jQuery from HTML page. – monstro Jun 24 '12 at 18:11
  • Hi Darin, but if he doesn't have jQuery referenced, he should get errors when using `$`, so... I don't know. :( – gdoron Jun 24 '12 at 18:19
  • That's right. Then the only thing left is JSON serialization problems of the `Weather` class that he is using. Are you able to see the generated JSON when you directly navigate to `/Home/GetWeather`? – Darin Dimitrov Jun 24 '12 at 18:20
  • I know how to use firebug :) Hardcoding – monstro Jun 24 '12 at 18:24
  • If you know how to use FireBug, what do you see in the Console or the Net tab when you click on the button? Can you see the request being sent? – Darin Dimitrov Jun 24 '12 at 18:25
  • @Sigourney_Weaver. You little bit confused by jQuery <> Razor, but never mind, Darin, he's saying he doesn't even see the request in FireBug, not just the response. X-Files... – gdoron Jun 24 '12 at 18:26
  • Yes, as I said before, in Firebug, I dont see any request when clicking the button, it hits the break point on getJSON, but no request in Firebug. That's why I am asking the question, because it seems that getJSON function has a bug. – monstro Jun 24 '12 at 18:44
  • @Sigourney_Weaver. Try sending with **.ajax** Code: `$.ajax({ url: "@Url.Action('GetWeather', 'Home')", dataType: 'json', success: function(){alert('YES');}, error: function(){alert('ERROR!');} });` It's equals to `getJSON`. – gdoron Jun 24 '12 at 18:56
  • $.getJSON has no bug at all, I can assure you. Could you show how your `Weather` class looks like? – Darin Dimitrov Jun 24 '12 at 19:02
  • gordon, your code throw runtime exception: Server Error in '/' Application. Compilation Error Compiler Error Message: CS1012: Too many characters in character literal Source Error: Line 16: $("#Button1").click(function () { Line 17: Line 18: $.ajax({ url: "@Url.Action('GetWeather', 'Home')", dataType: 'json', success: function () { alert('YES'); }, error: function () { alert('ERROR!'); } }); Line 19: – monstro Jun 24 '12 at 19:04
  • I dont need to use any of razor helpers, My page could be just HTML – monstro Jun 24 '12 at 19:05
  • @Sigourney_Weaver. Of course my bad. It should be `$.ajax({ url: '@Url.Action("GetWeather", "Home")', dataType: 'json', success: function(){alert('YES');}, error: function(){alert('ERROR!');} });` But you should have got this error long time a ago. Note, make sure to add `@gdoron` to your comments or else I won't see them. – gdoron Jun 24 '12 at 19:18
  • I found the solution, posted it, but someone removed it :( I don't understand why :( – monstro Jun 24 '12 at 21:05
  • Sorry guys, but it seems that you dont have an idea what you're talking about. Why would you want to see the Weather class, Darin? Did you understand the problem I explained? LOL – monstro Jun 24 '12 at 21:08
  • Never mind, I found the problem - and it was not with the code! But problem resolution was removed by moderator for unknown reason :( Well, good luck, when you have the same problem and dont know what to do, call the moderator :) – monstro Jun 24 '12 at 21:10
  • @Sigourney_Weaver, I hope everything goes well now with your code. You might also like to read the FAQ about how to use this site. – Darin Dimitrov Jun 24 '12 at 21:12