Search code examples
jqueryajaxangularjsasp.net-mvc-4angularjs-factory

ajax success function return view on second click


I am using ajax's post request in the angular's factory.... everything works fine except the ajax success function... you can see in success function i have to go on another page..(logout.html).. but the ajax's success function login me to second page after clicking login button two times,, i dont know what is problem any help please

my ajax call in angular factory

demoapp.factory("authser", function ($location) {
    return {
        login: function (credantials) {
            if (credantials.username != "jot") {
                alert("its ");
            }
            else {
                $.ajax({
                    url: "/valued/newvalue",
                    type: 'POST',
                    data: { 'name': credantials.username, 'password': credantials.password },
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        $location.path('/logout');

                    }
                });
            }
        },
        logout: function (data) {
console.log(data);

            $location.path('/hello');
        }
    }
})

my controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace angulardata.Controllers
{
    public class valuedController : Controller
    {
       // GET: /valued/
        [HttpPost]
        public ActionResult newvalue(string name, string password)
        {
            var res = new {Success="True",Message="Error MEssage" };
            return Json(res);
        }

    }
}

Solution

  • Instead of using $.ajax try to use $http angular service to call server that will trigger the angular digest cycle .

    demoapp.factory("authser", function ($location,$http) {
    

    //

    $http({
        method: 'POST',
        url:  "/valued/newvalue",
        responseType: "json",
       data: { 'name': credantials.username, 'password': credantials.password }
    }).success(function (data) {
       console.log(data);
       $location.path('/logout');
    });