Ajax parameters always null - ajax

I don't know what happened but one of my Ajax query stops working.
I have 2 Views, in first one user choose colors of buttons
function choose()
{
var a = document.getElementById("button1").style.backgroundColor.toString();
var b = document.getElementById("button2").style.backgroundColor.toString();
var c = document.getElementById("button3").style.backgroundColor.toString();
var d = document.getElementById("button4").style.backgroundColor.toString();
if (a && b && c && d != "") {
$.ajax({
url: '#Url.Action("SetCode", "Home")',
type: 'POST',
data: { a, b, c, d },
}).done(function(res) {
window.location.href = res.newUrl;
}).fail(function(xhr, a, error) {
console.log(error);
});
then in controller the colors are saved in singleton class
Kod o1 = Kod.makeObject();
[HttpPost]
public JsonResult SetCode(string a, string b, string c, string d)
{
o1.FirstColor = a;
o1.SecondColor = b;
o1.ThirdColor = c;
o1.FourthColor = d;
return Json(new { newUrl = Url.Action("Game", "Home") });
};
after that there is a redirection to method in controller "Game" which return View. In this View next user selects the colors and checks if they are correct
public IActionResult Game()
{
return View();
}
function checkcode() {
var a = document.getElementById("button1").style.backgroundColor.toString();
var b = document.getElementById("button2").style.backgroundColor.toString();
var c = document.getElementById("button3").style.backgroundColor.toString();
var d = document.getElementById("button4").style.backgroundColor.toString();
if (a && b && c && d != "") {
$.ajax({
url: '#Url.Action("Check", "Home")',
dataType: "text",
type: 'POST',
data: {a , b, c, d },
success: function (data) {
if (data == true) {
alert("OK")
} else { alert("Error") }
}
});
In controller method I always receive nulls in viarables e,f,g,h.
What's wrong?
[HttpPost]
public bool Check(string e, string f, string g, string h)
{
if (o1.FirstColor == e && o1.SecondColor == f && o1.ThirdColor == g && o1.FourthColor == h)
{
return true;
}
else { return false; }
}

You need to change data: {a , b, c, d },
to data: { e:a, f:b, g:c, h:d },.
If you use data: {a , b, c, d },request will pass parameters which name is a,b,c,d,so you need to change their name to e,f,g,h.
When using data: {a , b, c, d },the request data will be:
When using data: { e:a, f:b, g:c, h:d },,the request data will be:
Update:
You need to change data == true to data == "true",When you pass true to ajax,the data will be "true".

Related

how i make a condition with ajax and asp mvc

I want to put a condition if the user want to add a second appointment he receives an alert
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
this is my code in controller :
public JsonResult SaveEvent(Event e)
{
var status = false;
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.StartDate = e.StartDate;
v.EndDate = e.EndDate;
v.EventDescription = e.EventDescription;
v.EventID = e.EventID;
v.ThemeColor = e.ThemeColor;
}
else
db.Events.Add(e);
db.SaveChanges();
status = true;
}
i want to make the user add one time his event and receive an alert i try but not work
I think i can help:
if(Session["appointment"] != "ok")<>
{
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.StartDate = e.StartDate;
v.EndDate = e.EndDate;
v.EventDescription = e.EventDescription;
v.EventID = e.EventID;
v.ThemeColor = e.ThemeColor;
}
else
db.Events.Add(e);
db.SaveChanges();
Session["appointment"] = "ok";
return JSON(new{appointment="ok"});
}
}else
{
return JSON(new {appointment="no-good");
}
and controller:
function SaveEvent(data)
{
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function(data) {
if (data.appointment == "ok")
{
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
else { your msg error here }
},
error: function() {
alert('Failed');
}
})
}
})
dont not forget Session.Clear();
as the user logs out

Pass multiple values of the same parameter for search method

I would like to update my search function, so that it would accept additional parameters, which will be builed dinamically with checkboxes(let's say for a location NY AND Tokio AND Berlin). For now, my controller accepts page number and a search string, which are called with Ajax for infinate pagination.
So my search link is now like: /TopEventsul?searchString=HouseParty
and would like to add more search functions like: /TopEventsul?searchString=HouseParty&Location=London&Location=Tokio
Can u please point me to the right direction or maybe give me some examples?
Bellow is my controller function
// GET: Ul
public ActionResult Index(int? pageNum, string searchString)
{
pageNum = pageNum ?? 0;
ViewBag.IsEndOfRecords = false;
if (Request.IsAjaxRequest())
{
var customers = GetRecordsForPage(pageNum.Value);
ViewBag.IsEndOfRecords = (customers.Any()) && ((pageNum.Value * RecordsPerPage) >= customers.Last().Key);
return PartialView("_TopEventLi", customers);
}
else
{
LoadAllTopEventsToSession(searchString);
ViewBag.TopEvents = GetRecordsForPage(pageNum.Value);
return View("Index");
}
}
public void LoadAllTopEventsToSession(string searchString)
{
var students = from s in db.TopEvents
select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.Location.Contains(searchString)
|| s.Title.Contains(searchString));
}
var customers = students.ToList();
int custIndex = 1;
Session["TopEventi"] = customers.ToDictionary(x => custIndex++, x => x);
ViewBag.TotalNumberCustomers = customers.Count();
}
public Dictionary<int, TopEvents> GetRecordsForPage(int pageNum)
{
Dictionary<int, TopEvents> customers = (Session["TopEventi"] as Dictionary<int, TopEvents>);
int from = (pageNum * RecordsPerPage);
int to = from + RecordsPerPage;
return customers
.Where(x => x.Key > from && x.Key <= to)
.OrderBy(x => x.Key)
.ToDictionary(x => x.Key, x => x.Value);
}
Regards!
Here you have Location as fixed parameter, so you can simply do like these,
public ActionResult Index(int? pageNum, string searchString, IEnumerable<string> Location)
{
// Your code
}
if you have any other parameters you can also add them, for exa.
your parameter is param and it's type is int then
public ActionResult Index(int? pageNum, string searchString, int param)
{
// Your code
}
//Ajax Call for Index
function testAjax() {
$.ajax({
url: "#Url.Content("~/Your-Controller/Index")",
data: "pageNum=" + your data for pageNum + "&searchString=" + your searchString + "&param=" + param,
dataType: "json",
type: "Post",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
//Code for before send whatever you have to do.
},
success: function (data) {
//Your code when all ok
},
error: function (response) {
//Your code when error ocure
alert(response.responseText);
},
failure: function (response) {
//your code for failure
alert(response.responseText);
}
})
return false;
}

How to Use Take and Skip Function in MVC

I want to Load Data and skip previous data which already append in the view using skip and take count in mvc.Here is my View where i am getting data
var skipCount = 5;
var takeCount = 5;
function loadMore() {
$(window).bind('scroll', bindScroll);
itemCount = takeCount;
skipCount += takeCount;
setTimeout(function () {
getFeed();
},100);
}
function bindScroll() {
if ($(window).scrollLeft() + $(window).width() > $('.tile-area').width() - 130) {
$(window).unbind('scroll');
loadMore();
}
}
function getFeed() {
$.ajax({
type: "Post",
url: "/PlanetFeed/PlanetfeedPartial",
dataType: "html",
data: { id: planetFeedOwnerId, filterType: filterType, taggedItemGraphId: taggedItemGraphId, itemCount: takeCount, SkipCount: skipCount }, //"feedGraphId=10696",
success: function (data) {
if (data === null) {
} else {
$('.tile-area-title').html("");
var div = $('.planetFeed:last');
div.after(data);
skipCount += takeCount + 1;
}
});
}
And Here is My Controller Where I am Passing Parameter
public ActionResult PlanetfeedPartial(Guid id, string filterType, Guid taggedItemGraphId, int itemCount, int SkipCount)
{
var planetfeedsOrder = from p in db.PlanetFeeds
where p.CurrentState != 1
join s in searchTag on p.PlanetFeedGraphId equals s.SecondaryTaggedGraphItemId
join g in db.Graphs on p.PlanetFeedItemGraphId equals g.GraphID
join u in db.UserInfos on p.PlanetFeedPosterId equals u.UserInfoID
orderby p.PostDate descending
select new PlanetFeedViewModel
{
Username = u.FirstName + " " + u.LastName,
isRootFeed = p.isRootFeed,
PostDate = p.PostDate,
CommentCount = g.CountResponses,
CountPositiveReactions = g.CountPositiveReactions,
CountNegativeReactions = g.CountNegativeReactions,
ItemID = g.ItemID,
UserLevel = u.UserLevel,
CurrentState = p.CurrentState,
Address = g.Address
};
return PartialView("_PlanetfeedPartial", planetfeedsOrder.OrderByDescending(p => p.PostDate).Skip(SkipCount).Take(itemCount).ToList());
}
I am not getting proper Data and every time when i am loading data in scroll getting different data not in a proper sequence and all data not loading
var planetfeedsOrder = (from p in db.PlanetFeeds
where p.CurrentState != 1
join s in searchTag on p.PlanetFeedGraphId equals s.SecondaryTaggedGraphItemId
join g in db.Graphs on p.PlanetFeedItemGraphId equals g.GraphID
join u in db.UserInfos on p.PlanetFeedPosterId equals u.UserInfoID
orderby p.PostDate descending
select new PlanetFeedViewModel
{
Username = u.FirstName + " " + u.LastName,
isRootFeed = p.isRootFeed,
PostDate = p.PostDate,
CommentCount = g.CountResponses,
CountPositiveReactions = g.CountPositiveReactions,
CountNegativeReactions = g.CountNegativeReactions,
ItemID = g.ItemID,
UserLevel = u.UserLevel,
CurrentState = p.CurrentState,
Address = g.Address
}).orderby(o=>o.id).skip(100);
skip One hundred then shows your data and create order by any id or string that you want sequence data.

how do i insert localstorage var in data read url?

I see my local storage is on the page. I am trying to pull in the user_id and place it in the data URL to build my query. Can someone please let me know what im doing wrong?
<!--GET REMOTE JSON DATA-->
<script>
var app = new kendo.mobile.Application();
var theuser = localStorage.getItem('user_ID'); //grab user ID from local storage
var IRISalerts = new kendo.data.DataSource({
transport: {
read: {
url: "http://procdev.irisdispatch.com/ws/mobilefunctions.cfc? method=getAlerts&user_id='+theuser'",
dataType: "json", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
}
},
You don't use .encodeURIComponent() to encode your query parameters, don't you; it may have invalid url characters ( special characters, etc. ) giving you a headaces. Try out this function, you may use it for object -> query-string conversion ( if you storing json objs in storage ), it performs well for key=value pairs also. For single query parameter .encodeURIComponent() does the job...
function uriParamNcoder(obj) {
if (
Object.prototype.toString.call(obj) === "[object String]"
) {
return obj.split('=')
.map(
function (part) {
return encodeURIComponent(part);
}
)
.join('=')
.replace(/%20/g, '+');
}
var q_str_arr = [];
objTrace(
obj,
function (k, v, trace) {
var tmp = trace.match(/^\[(.+?)\](.*)$/);
q_str_arr.push(
encodeURIComponent(tmp[1]) +
((tmp[2] !== void 0) ? encodeURIComponent(tmp[2]) : "") + "=" + encodeURIComponent(v)
);
}
);
function objTrace(obj, fn) {
if (
obj === Object(obj) && (typeof fn === "function")
) {
objParamTracer.apply(
obj, [obj, fn].concat(Array.prototype.slice.call(arguments, 2))
);
}
return obj;
}
function objParamTracer(obj, fn, trace) {
trace || (trace = "");
if (
Object.prototype.toString.call(obj) === "[object Array]"
) {
obj.forEach(
function (o, k) {
if (o === Object(o)) {
return objParamTracer.apply(
o, [o, fn].concat(trace + "[]")
);
} else {
return fn.apply(
this, [k, o].concat(trace + "[]")
);
}
},
obj
);
} else {
ownEach(
obj,
function (p, o) {
if (
o === Object(o)
) {
return objParamTracer.apply(
obj, [o, fn].concat(trace + "[" + p + "]")
);
} else {
return fn.apply(
this, [p, o].concat(trace + "[" + p + "]")
);
}
}
);
}
}
function ownEach(obj, fn) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
fn.call(obj, prop, obj[prop]);
}
}
return obj;
}
return q_str_arr.join('&').replace(/%20/g, '+');
}

returning different javascript object from controller

my controller action:
[HttpPost]
public ActionResult AddPointAndCopyOtherSongToPlaylist(int id)
{
if (CheckIfAddPointToSelf(User.Identity.Name, id))
{
var song = repository.GetSong(id);
foreach (var item in song.Points)
{
if (User.Identity.Name == item.UsernameGavePoint)
{
var data1 = 1;
return Json(new {data1}, JsonRequestBehavior.AllowGet);
}
}
var originalSong = repository.GetSong(id);
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = originalSong.Title;
newSong.YoutubeLink = originalSong.YoutubeLink;
newSong.GenreId = 38;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = originalSong.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.OtherSongId = id;
repository.AddPoint(point);
repository.Save();
int data = 2;
//process here
return Json(new { data }, JsonRequestBehavior.AllowGet);
}
else
{
return null;
}
}
based on different scenarios I want to return a javascript and somehow notify the client of what was returned and based in the result do something in the success part of my ajax call:
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyOtherSongToPlaylist/",
type: "POST",
data: { id: songId },
success: function (data,one) {
if (data && !one) {
HideAjaxLoader(), ShowMsg("Song Added Successfully");
}
else if(!data) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data && one) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
I tried many different variations but I think i need something like data.property1 returned and in the client to check if that property exists or soemthing like that.. please help
You need to return your status code within the object.
return Json( new { data1 = "Some Other Data", status = 1} );
Then in your success handler check data.status.
if (data.status === 1) {
alert(data.data1);
}

Resources