Call JSON method in asp.net mvc without page refresh? - json

Here is my JSON method in controller
public JsonResult GetNotificationForAll()
{
Int64 userid = Convert.ToInt64(Session["UserID"]);
string searchcriteria = string.Format("N.notificationfor ={0}", 1);
PODService.Notification[] notification = service.GetNotificationBySearchCriteria(searchcriteria);
return Json(notification, JsonRequestBehavior.AllowGet);
}
Here is my script code for JSON method:
var URL6 = "/Home/GetNotificationForAll";
$.getJSON(URL6, "", function (data) {
var x = { "padding-left": "10px" };
$.each(data, function (index, value) {
$("<td>"
+ value["Notification_Name"]
+ "</td>")
.appendTo("#Allnotification").css(x);
});
});
Here is my view:
<div id="Allnotification" style="color:White;float:left;margin-left:10px"> </div>
I want to show data without page refresh.

i have found the solution.
function NotificationForALL() {
$("#Allnotification").empty();
$.ajax({
type: "GET",
url: "#Url.Action("GetNotificationForAll", "Home")",
dataType: "json",
cache: false,
success: function (data) {
$.each(data, function(index, element) {
var x = { "padding-left": "10px" };
$("<td>"
+ element["Notification_Name"]
+ "</td>") .appendTo("#Allnotification").css(x);
});
setTimeout(function(){NotificationForALL();}, 900000);
}
});
}
NotificationForALL();
Hope it will help to someone

Related

Populate textboxes based on id searched

Okay, so i am new to ajax and mvc. i have a form which requires me to enter an id in the field and after clicking the search button it retrieves and populates data from the database and displays it in the textfields.
Controller Code
public ActionResult LoadVendorInfo(string vendornumber)
{
var query = from c in db.Vendors
where c.VendorNumber == vendornumber
select c;
return Json(query.FirstOrDefault());
}
Ajax
<script type="text/javascript">
$(document).ready(function () {
$("#searchvendor").click(function () {
var vendornumber = $('#vendornumber').val();
$.ajax({
cache: 'false',
type: "POST",
data: { "vendornumber": vendornumber },
url: '#Url.Action("LoadVendorInfo", "Vendors")',
datatype: 'json',
"success": function (data) {
if (data != null) {
var vdata = data;
$("#companyname").val(vdata[0].companyname);
$("#regnum").val(vdata[0].regnum);
$("#email").val(vdata[0].email);
$("#contactnum").val(vdata[0].contactnum);
$("#refnum").val(vdata[0].refnum);
}
}
})
})
})

How to pass a variable in button id and then send that id to ajax data?

I am passing id of the product to button id and then through Ajax data, I'm sending that product id to the controller
for(var i=0;i<productsJSON.length;i++)
{
var td5 = document.createElement('td');
td5.innerHTML = "<br><button type='button' id="+product.id+"onclick='Addtocart() ' >Add To Cart</button><br>";
}
function Addtocart() {
var quantity = document.getElementsByName("quantity").item(0).value;
$.ajax({
type: "POST",
data: 'pid=' + this.id + '&quantity=' + quantity,
url: "ProductController",
success: function(content) {
console.log(content);
alert('done');
}
});
}
You have to use a JSON object.
Here I set data from an HTML form using the GET method.
$.ajax(
{
type: "GET",
data: $("#form").serialize(),
url: "url",
success: function(data)
{
# Code
},
error: function()
{
# Code
}
}
);

Handling a model returned as json data from a controller in ASP.NET

I have a controller which return a model as json object:
[HttpGet("{id}")]
[Route("GetById")]
public async Task <JsonResult> GetById([FromQuery]string id)
{
var myfoo = new {foo="bar", baz="Blech"};
return Json(myfoo);
}
How can handle the returned json object in jQuery?
<script type="text/javascript">
$('#id').change(function () {
var id = $('#id').val();
if (id.length = 17) {
$.ajax(
{
url: '/Home/GetById?id=' + id,
type: 'GET',
jsondata: "",
contentType: 'application/json; charset=utf-8',
success: function (jsondata) {
alert("foo is: " + jsondata ); <---?
},
error: function () {
//alert("error");
}
});
}
});
</script>
I need to get foo value and assigned to an html control
Thanks in advance
all the time I was using capital letter
jsondata.foo // not .Foo

Laravel AJAX GET and show new data

I've been working on a project and thus far I've been able to POST to the database using AJAX, so when the user submits data the page wont refresh but the data is still uploaded to the database.
Now what I want to do, is show those results to the user without needing to refresh the page. I've spent a lot of time trying to figure it out but right now I'm very stuck. Could anyone point me in the right direction? I've read the documentation on the website, watched hours worth of videos but still have no luck.
The code I have so far.
Script
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: '{{$video->id}}/shownew',
success: function (data) {
console.log(data);
$("#data").append(data);
},
error: function() {
console.log(data);
}
});
Controller
public function shownew($video)
{
$getstamps = DB::table('timestamps')
->where('videoid', '=', $video)
->orderByRaw('LENGTH(timestamp_time)', 'ASC')
->orderBy('timestamp_time', 'asc')
->get();
return response()->json(array('success' => true, 'getstamps' => $getstamps));
}
Console
{success: true, getstamps: Array(3)}
getstamps: Array(3)
0: {
timestamp_id: 128,
videoid: "5",
timestamp_name: "Title",
timestamp_time: 1,
created_at: "2017-10-04 23:28:12",
…
}
1: {
timestamp_id: 129,
videoid: "5",
timestamp_name: "1",
timestamp_time: 1,
created_at: "2017-10-04 23:41:01",
…
}
2: {
timestamp_id: 130,
videoid: "5",
timestamp_name: "1",
timestamp_time: 1,
created_at: "2017-10-04 23:41:21",
…
}
length: 3
__proto__: Array(0)
success: true
__proto__: Object
here is the solution for you problem
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: '{{$video->id}}/shownew',
success: function (data) {
var obj = JSON.parse(data);
var your_html = "";
$.each(obj['getstamps'], function (key, val) {
your_html += "<p>My Value :" + val + ") </p>"
});
$("#data").append(you_html); //// For Append
$("#mydiv").html(your_html) //// For replace with previous one
},
error: function() {
console.log(data);
}
});
This fixed the issue.
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: '{{$video->id}}/shownew',
dataType: 'json',
success: function (data) {
console.log(data);
container.html('');
$.each(data, function(index, item) {
container.html(''); //clears container for new data
$.each(data, function(i, item) {
container.append('<div class="row"><div class="ten columns"><div class="editbuttoncont"><button class="btntimestampnameedit" data-seek="' + item.timestamp_time + '">' + new Date(item.timestamp_time * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0] +' - '+ item.timestamp_name +'</button></div></div> <div class="one columns"><form action="'+ item.timestamp_id +'/deletetimestamp" method="POST">' + '{!! csrf_field() !!}' +'<input type="hidden" name="_method" value="DELETE"><button class="btntimestampdelete"><i aria-hidden="true" class="fa fa-trash buttonicon"></i></button></form></div></div>');
});
container.append('<br>');
});
},error:function(){
console.log(data);
}
});

Unable to recieve JSON from Webmethod using $.getJSON or Ajax call

I have some JSON objects that I want to process on Client Side, but My WebMethod that I specified does not want to fire.
Here is the Ajax and GetJson methods i used in my Client Side Script:
GetSJON
$(document).ready(function() {
$(document).ready(function() {
//attach a jQuery live event to the button
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
});
Here is the Ajax
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function (res) {
$('#Results').append(CreateTableView(res)).fadeIn();
}
});
});
Both of these Methods Call StockPlacementOptions which is my WebMethod that look like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,
UseHttpGet = true, XmlSerializeString = false)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
If I can just get the JSON web Method to fire on $(document).ready event, I will be able to process and work with the data from there. I have also tried looking at a diffrent jQuery library like KnockoutJS with it's data processing capability, also no luck.
I am using ASP Webforms on Framework 4 with Html5 Markup.
Any advice will be greatly appreciated.
Why are you using two document.ready() handlers at your client side getJson and ajax
$(document).ready(function() { // <-------you can remove this handler
$(document).ready(function() {
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
}); // <-------you can remove this handler
although i am not sure this could be the issue but try this one if this helps.
I got it fixed by using a combination of KnockoutJS and ajax.
By utilizing the knockoutJS mapping model, I am able to manipulate the returned JSON anyway i want :)
Here is my Jquery that does the Mapping and obtains JSON from server.
<script type="text/javascript">
//Declareing Viewmodel For KnockoutJS
var viewModel;
//Using Mapping Plugin for Knockout JS
function bindModel(data) {
viewModel = ko.mapping.fromJS(data);
console.log(viewModel);
ko.applyBindings(viewModel);
}
//Onload ObtainJSON
$(document).ready(function () {
$.ajax({
url: "WebForm1.aspx/StockPlacementOptions",
// Current Page, Method
data: {},
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (result) {
bindModel(result);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
});
</script>
I also changed the Webmethod slightly to obtain the result i wanted:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
And That's it :D
Thanks for all the help