1

I'm trying to do a simple Ajax call to register a user from a HTML page, the function in the MVC 4 is called and working well, but what it returns never fires the 'success' function in the Ajax call.

If I'm using my browser to manually access the Register() function, it works well and returns the message I want, but not through Ajax

function register() {
    var userModel = {
        phoneNumber: "1236663",
        displayname: "yasuuu",
    }
    $.ajax({
        type: "POST",
        url: "http://localhost:13234/home/register",
        data: userModel,
        success: function (response) {
            $('#deleteThisDivButNotItsContent').html(response)
        }
    })
}

    public ActionResult Register(string PhoneNumber, string DisplayName)
    {
        // Some working code here ...

        ViewBag.Message = "Some Message"; // just trying to display simple text

        return View();

        /* tried all of the lines below too */

        //return this.Json("1234");
        //return Json("{ result : true }");
        //return PartialView("ShowResultPartial", JsonRequestBehavior.AllowGet);
        //CommentSection commentSection = new CommentSection();
        //return PartialView("CommentSection");
        //return PartialView("CommentSection", commentSection);
        //return Json(new { success = true, response = "Saved ok" });
    }

I'm using JQuery 2.0.3

tereško
  • 58,060
  • 25
  • 98
  • 150
Miko Diko
  • 944
  • 1
  • 13
  • 33
  • I've searched the internet for hours but couldn't find anything :( – Miko Diko Aug 04 '13 at 04:47
  • 2
    Which version of jQuery you are using? You should use promise/deferred style with `.done(...)` instead of using `success` – cuongle Aug 04 '13 at 04:48
  • I think success is obsolete. Try complete instead. [http://api.jquery.com/jQuery.ajax/](http://api.jquery.com/jQuery.ajax/) – Dmytro Aug 04 '13 at 04:51
  • With .done(...) it's not working. But when I use complete like Dmytro said, it does go to the body of .complete(function(data) and when I parse the return parameter using JSON.stringify(data), it turns to {"readyState":4,"status":404,"statusText":"error"} – Miko Diko Aug 04 '13 at 05:40
  • Do you get an error in your browser console? – Jeandre Pentz Aug 04 '13 at 08:38
  • Jeandre, Nope, this is the message I get in the console: -- [12:03:15.375] POST http://localhost:13234/home/Register [HTTP/1.1 200 OK 150ms] // end. It's weird cause I get 404 in the actual return parameter, what might it be ? – Miko Diko Aug 04 '13 at 09:04
  • What is the page url from where you are calling the ajax? Do both the 'page url' and the 'ajax url' belongs to the same domain? i.e. `http://localhost:13234`? – shakib Aug 04 '13 at 18:34
  • I'm not quite sure what you meant. I'm using "http://localhost:13234/home/Register" in both the browser (which works) and the ajax call (which has this problem). the url is written only once in the ajax code. the ajax call runs Register() , which ends well but the ajax call has this weird problem with the return value.. – Miko Diko Aug 04 '13 at 19:55
  • I would add `error: logAjaxError(jqXHR, textStatus, errorThrown, this.url)` and set a breakpoint in firebug, always found the issue. – afzalulh Aug 16 '13 at 05:53
  • Solution: http://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method – Miko Diko Sep 25 '13 at 10:38

3 Answers3

0

Why don't you try this?

function register() {
$.post("/home/Register",
       {phoneNumber: "1236663", displayname: "yasuuu"},
       function(data,status,xhr){
            $('#deleteThisDivButNotItsContent').html(data.response);
});
}

In the controller

return Json(new { success = true, response = "Saved ok" });
Huy Hoàng Phạm
  • 145
  • 1
  • 2
  • 10
  • Hey, I've used what you posted, using my browser, doing little modifications to the URL and AllowGet, but still no luck: $.post("http://localhost:13234/home/Register", {phoneNumber: "1236663", displayname: "yasuuu"}) .done(function(data) { $('#deleteThisDivButNotItsContent').html(data); }); return Json(new { success = true, response = "Saved ok" }, JsonRequestBehavior.AllowGet); – Miko Diko Aug 04 '13 at 05:15
  • Try to go to "localhost:13234/home/Register" using your browser. Can you see a json string or something? – Huy Hoàng Phạm Aug 04 '13 at 11:05
  • with the browser, it's working. I'm going to http://localhost:13234/home/register?phonenumber=123&displayname=miko and get the JSON back {"success":true,"response":"Saved ok"} – Miko Diko Aug 04 '13 at 15:08
  • Still no luck, the Register() is launched in debug mode, but now nothing is changed in the html. – Miko Diko Aug 04 '13 at 15:57
  • with a simple alert() I see the function(data,status,xhr) doesn't get launched., unlike 'complete' which does get launched but with '404' – Miko Diko Aug 04 '13 at 16:03
0

Let it return JsonResult instead of ActionResult. How in the world can AJAX interpret an ActionResult view?

Also you send an object to the Register() method but you're receiving two string variables.

Here is an example:

function register() {
    var userModel = {
        phoneNumber: "1236663",
        displayName: "yasuuu",
    }

    $.ajax({
        type: "POST",
        url: "http://localhost:13234/Home/Register",
        data: userModel,
        success: function (response) {
            $('#deleteThisDivButNotItsContent').html(response.message)
        }
    });
}

publi class UserModel
{
    public string phoneNumber { get; set; }
    public string displayName { get; set; }
}

public JsonResult Register(UserModel userModel)
{
    // Some working code here ...

    return Json(new { message = "Some message here" }, JsonRequestBehavior.AllowGet);
}
Gaui
  • 8,723
  • 16
  • 64
  • 91
0

When you type http://localhost:1234/register into the browser it is issuing a GET request for that URL. In your javascript, jquery is issuing a POST request. The ajax request is receiving a 404 error because the route is not configured to respond to POST requests.

Jason
  • 15,915
  • 3
  • 48
  • 72
  • I've added [HttpPost] before the Register function in the MVC, but it's still not working, is that what you meant ? – Miko Diko Aug 07 '13 at 02:46
  • That is what I meant. Are you looking at the network requests using the browser debug tools? maybe you can try cUrl (http://curl.haxx.se/) - the problem is your site is returning an HTTP404 (not found) response to the ajax post. You just have to figure out why. – Jason Aug 07 '13 at 03:11
  • But when I use the browser to call http://localhost:1283/home/register?phonenumber=123&displayname=miko , it works fine. And when I use Ajax - comes the problem. Any idea why this could happen ? :\ – Miko Diko Aug 09 '13 at 22:21
  • try using Ajax to issue a GET request (i.e. $.get("/whatever")), or use CURL to issue POST and GET requests to see if that's the problem. comparing the ajax call to typing the URL in the browser is not a fair comparison – Jason Aug 09 '13 at 22:48
  • Changing to $.get(..) hasn't solved the problem. I've also tried to run this on Windows 8 with IIS 8, same problem. CURL looks so complicated :/ – Miko Diko Aug 10 '13 at 01:54