I am trying to learn asp.net. I am making a demo website in which there would be an admin panel. The admin would update the Daily Messages which will get reflected in the main homepage. I am using MVC.
I have created the table in database as
create table DailyMsg(Sno int primary key, msg varchar(max));
This is my controller
public class DailyMsgsController : Controller
{
private amenEntities db = new amenEntities();
// GET: DailyMsgs
public ActionResult Index()
{
return Json(db.DailyMsgs.ToList(),JsonRequestBehavior.AllowGet);
}
}
On running the following URL, I am successfully able to see the data in JSON format.
https://localhost:44329/DailyMsgs
[{"Sno":1,"msg":"Hi!"}]
Now, I am stuck. I know that I would have to add another class for Data Access Layer, but I am confused as how should I parse this data and print it to the main HTML page.
From my research on the internet, I have found out that I might have to use JQuery. So, I wrote the following(with what I could understand from the internet as I am not familiar with JQuery) -
$.ajax({
url: "/DailyMsgs/Index",
type: "GET",
success: function (data) {
$("#div1").html(data);
}
});
This, of course, is not working and I can't see anything on my webpage.
My Homepage.html
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
</body>
</html>
<script src="../Scripts/jquery-1.8.0.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<link href="../Content/bootstrap.css" rel="stylesheet" />
<script src="../JQuery/DailyMsgsJQ.js"></script>
All I want is to read and parse msg from JSON and display it on webpage.
Could you guide me as how should I proceed or is there any other way to achieve the purpose? Thanks a lot!
Try this
$.ajax({
url: "/DailyMsgs/Index",
type: "GET",
success: function (data) {
$.each(data, function (index, element) {
$("#div1").append(element.msg);
});
}
});
If you still have error please get console.log(data); and send for me.
Your <script> tags are outside your <html> tag. That means the scripts are probably not even executed, or not loaded in the correct order. You want jQuery and Bootstrap to be loaded first, so put them in the <head>. Put your custom script just before the closing </body>, so it is loaded last.
Related
So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.
First of all thanks to you all for your valuable suggestion.I got stuck one problem that is in jQuery ajax call in grails remote function call on controller.
The plug-ins installed in my project are: jQueryUi - 1.10.3, jQuery - 1.11.0.
My controller this method:
def loadamount(){...}
And for ajax call method:
def ajaxCallBalance(long id){
def userBalances=loadamount(id)
def userBalance=userBalances[0] //it returns in array
return [usreBalance:userBalance]
}
These are nothing but my database call to load user amount in his a/c that should load on page load inside user profile html page. So for that i use this:
Point 677:
<g:if test="${session.LogedUser}">
<script>
${remoteFunction(
controller:'user',
action:'ajaxCallBalance',
update:[success:'uresult',failure:'uresult'],
id:session.LogedUser.id
)}
</script>
In HTML:
<li id="uresult"><!-- Want to see hare what result either value or error it returns --></li>
In firebug console I see get this error:
SyntaxError: syntax error
<script>
jQuery.ajax({
type:'POST',
url:'/...../..../ajaxCallBalance/10000000',
success:function(data,textStatus) {jQuery('#uresult').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown)
jQuery('#uresult').html(XMLHttpRequest.responseText);
}
});
</script>
[Note:This is generated by grails ajax plugin what i have wrote is see point 677.]
Here is my Question:
Why is this $#39; appearing even though I have no space, nor any symbol. Is it a bug or my mistake?
Is there any way to handle this kind of scenario as user onLoad/(document).ready() call for such conditions. If Yes, then what I will do?
You can't just use the grails construct of ${remoteFunction...} in js directly. use ajax:
$.ajax({
type: 'POST',
url: "${createLink(action:'ajaxCallBalance', controller:'user')}",
data: { id: id },
success: function (dataCheck) {
//Do stuff
}
........
});
or use g:remoteFunction like this way
$('mydiv').onclick = <g:remoteFunction action="ajaxCallBalance" controller="user" id="${id}" />
My app is using the play framework mvc setup. In the controller I am passing a parameter while rendering the template, like this:
public static void scenario(){
...
render(active_brands);
}
Now in my HTML page "scenario.html", I can access the parameter using the play framework tags like this:
#{list items:active_brands, as:'c'}
...
#{\list}
Or using JQuery inside an HTML table like this:
<td>${active_brands.get(1)}</td>
Just for reference, the passed in parameter is a List.
However, I am trying to access the parameter "active_brands" from a javascript function and I am not sure how to do that.
I thought using Jquery to access the variable would work and I tried to access the variable like this:
function update_brands(active_scenario_ids){
...
alert('Reached: '+ ${active_brands});
}
but that does not work. It seems to me that the HTML attribute is out of scope for the javascript function. Is that true?
It would be great if someone can help me with this. Thanks.
This works for me using Play 2.2.0:
Application.scala (controller):
def index = Action { implicit request =>
val message = "This is a test."
Ok(views.html.test(message))
}
test.scala.html (view template):
#(message: String)
<script type="text/javascript">
$(document).ready(function(){
console.log("#message");
});
</script>
Console output:
This is a test.
The root of the problem was that my template variable, which is accessible in client side HTML, was of type java.util.List, which is not accessible by client side code ie. javascript. However, it is recognized in the play tags because play tags are server side code written in client side. So the only solution I could find for reading Objects inside java collections is returning a JSON object.
Therefore I had to change my code such that instead of returning a Java List as a template variable, I retrieve the data as a JSON object through an ajax call.
$.ajax({
url: '/getBrands/',
type: 'POST',
data: {active_scenario_ids: active_scenario_ids},
dataType: "json",
success: function(data){
console.log(data);
},
error: function(req, status, error){
alert("R:"+req+"S:"+status+"E:"+error);
}
});
}
I'd like to create my own JS widget, which it must be dinamic.
I mean, for example, the html generated from the downloaded script :
<script src="www.mywebsite.it/widget/?ID=2&Category=4" type="text/javascript"></script>
must be different from :
<script src="www.mywebsite.it/widget/?ID=1&Category=5" type="text/javascript"></script>
and the Data into HTML should be taken from Database, on my server. So, I need to call an aspx page that create javascript that will create html? Or which could be the solution?
The better way is to use generic handler with .ashx, if you want retrieve data from server and send data in JSON or XML.
Next, the data will be inserted in page with javascript.
So, if I understand well, you do generate an .aspx that contains your template and a javascript that hold the code to navigate in Category as this if you use JQuery :
$.ajax({
url: 'data.ashx?ID=2&Category=5',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Server behind (ashx) :
private readonly JavaScriptSerializer _js = new JavaScriptSerializer();
public void ProcessRequest(HttpContext context)
{
//Do logic and retrieve data here
Categorys c = GetFooById(context.Request["id"]);
context.Response.Write(_js.Serialize(c));
context.Response.ContentType = "application/json";
}
It seems that you'd want to use AJAX.
The script source shouldn't be dynamic (it can't be cached if it is), but the script itself could call whatever page you like to pull back data (say in JSON format) or raw markup to place in a pre-defined element.
Don't use the ASPX page to create javascript if you can help it.
Consider using a JavaScript library such as jQuery to help you.
Can anyone point me in the right direction with implementing the History.js gist with MVC project over at https://github.com/browserstate/history.js
Im just getting to grips with MVC and im considering full Ajax app with Ajax nav or standard nav (urls) with content loaded via Ajax, not sure which way to go but help appreciated.
Im MVC newbie so please forgive me if this is a basic or obvious question
If you are an MVC newbie, you might as well use a library to help you do it.
Backbone does that for you in a very clean way and also supports history through its router.
copy from this link:
Make an MVC Application into a SPA with AJAX and History.js (from Edson_Ferreira)
1.. Let's start with the Layout file. We need to add the following references to our Layout page (_Layout.cshtml):
<script src="~/Scripts/jquery-2.1.0.js "></script>
<script src="~/Scripts/jquery.history.js"></script>
<script src="~/Scripts/jquery.showLoading.js"></script>
2.. Create the Controller(s) and associated Views that we are going to navigate to:
This is how an MVC Controller method that returns a View will look like:
public ActionResult Rating()
{
ViewBag.IsAjaxRequest = Request.IsAjaxRequest();
return View();
}
The reason why we need to specify the dynamic property "ViewBag.IsAjaxRequest = Request.IsAjaxRequest();" is because this information will be used to disable or enable the associated layout with the view being returned.
The '_ViewStart.cshtml' will be responsible for managing this. The file should look like this:
#{
if (ViewContext.ViewBag.IsAjaxRequest == true)
{
Layout = null;
}
else
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
This is required to enable the user to type the URL on the address bar and not get a PartialView, but instead, get the expected full page with the layout applied on top of it.
3.. Prepare your links to be managed via AJAX:
On the Anchor Element, we need to add a class that will be used later to bind the 'Click' event using jQuery. Also, we need to add a 'data-ref' attribute so we can store the URL associated with this link.
Because this is an MVC application, we can use the '#Url.Action' helper to assist us in creating the URL; the 1st parameter is the 'View' and the 2nd parameter the 'Controller'.
This is how it should look:
Rating
4.. Prepare a container on which the views will be inserted.
The _Layout.cshtml file should have the following lines of code in it:
<div id="bodyContent">
#RenderBody()
</div>
5.. Create the JavaScript responsible for the AJAX based navigation and history state management:
$(function () {
var contentShell = $('#bodyContent');
var History = window.History, State = History.getState();
$(".ajaxLink").on('click', function (e) {
e.preventDefault();
var url = $(this).data('href');
var title = $(this).data('title');
History.pushState(null, title, url);
});
History.Adapter.bind(window, 'statechange', function () {
State = History.getState();
if (State.url === '') {
return;
}
navigateToURL(State.url);
});
function navigateToURL(url) {
$('#bodyContent').showLoading();
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function (data, status, xhr) {
contentShell.hideLoading();
$('#bodyContent').hide();
contentShell.html(data);
$('#bodyContent').fadeIn(1000);
},
error: function (xhr, status, error) {
contentShell.hideLoading();
alert("Error loading Page.");
}
});
}
}
6.. Add the reference to this JavaScript file in the _Layout.cshtml file after the views container:
<div id="bodyContent">
#RenderBody()
</div>
#RenderSection("scripts", required: false)
<script src="~/Scripts/App_Scripts/Layout.js"></script>
That's it!