Build a Javascript Widget : can I call an aspx? - javascript

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.

Related

How to parse JsonResult object from controller in MVC?

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.

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

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.

Save HTML DOM to file on server

I have an html5 web page that allows users to drag-n-drop objects between divs. After a user has moved objects around, I would like to save the current DOM to a file on my web server.
I know I can get the current HTML DOM using javascript but of course, I cannot save to a file on my server using javascript. So I thought about passing the html to a PHP page to do the "save" function, but I cannot figure out how to get the html passed to a PHP page. I've tried sending it as an argument in the URL with URI encoding, but the PHP page is not properly getting the entire string from the URL.
Should this approach work? If so, what am I missing to get the html string passed correctly to a PHP page? Or should I be using some other method?
ajax is the way to go here. If you are not familiar with ajax, please google it and learn it well. Any modern web app needs to have ajax integration in some way.
Here is how you can use javascript to communicate with the server.
Please Note I'm using JQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".draggableDivs").mouseup(function(event){
var documentStructure = ''; // whatever js you use to get document structure
var d = {"document_structure": documentStructure};
$.ajax({
url: "test.php", //Your url both relative and fixed path will work
type: "POST", // you need post not get because you are sending a lot of data
data: d,
success: function(response) {
alert('saved');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
on the server you would then do your php and save the data.
After you are done you can just respond with a json object if needed, if not just exit
you can use the approach like
after the drag and drop with javascript, show a button to save the dom.
on click event on the button, take the current dom in a variable.
use ajax to transfer your current dom to a php file(ajax file).
in the ajax file , save it into database.

Read in javascript a spring controller model

I have a controller where a JSONObject is passed as parameter. I would like to work with the object "all" in javascript (client side) not in the server side (JSP) so I don't want to get the object with JSP tags.
#RequestMapping(value = { "/dfi/rca" }, method = RequestMethod.GET)
public String getRcaResult(Model model, String flight_id) {
...
JSONObject all = new JSONObject ();
...
model.addAttribute("all",all);
return "dfi/rca";
}
I have a JSP file that import a Javasript file where I use the attribute all but I don't know how to access to it. If I use this code in the JSP file it works properly:
<script type="text/javascript">
var all= "${all}";
</script>
But if I try the same importing a Javascript file in the JSP, it doesn't get anything:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/all.js"></script>
In all.js:
var rcaresults = JSON.parse('${all}');
Are there any way to read the Spring model attributes in a Javascript file?
Thanks in advance.
JavaScript is run on the client side. Your model model.addAttribute("all",all); does not exist on the client side, it only exists on the server side while you are rendering your .jsp.
If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.
e.g <script>var paramOne =<c:out value="${all}"/></script>
when you use src, your browser (and not your backend) will try to fetch the javascript file from
"${pageContext.request.contextPath}/resources/js/all.js"
so the file is not processed by the server as a ModelView.

Is there any way to use the JQuery GetJSON method to get HTML from an external page?

So let's say you're trying to do a jquery ajax request, something like:
$.ajax({
...
url: http://other-website.com
...
})
I understand that because of the same-origin principle, this request will fail because the URL is an external domain.
However I've heard that GetJSON() does not obey this principle and can send asynchronous get requests to external servers using JSONP and an appended URL.
My question is: is it possible to use GetJSON() to retrieve all the HTML from an external name as a single string within a JSON object? If it doesn't do so by default, is there any way I can force / trick it into doing so?
Yes, you can request html from a remote location, however you must use a proxy to do so. One publicly available proxy is YQL.
http://jsfiddle.net/BKJWu/
var query = 'SELECT * FROM html WHERE url="http://mattgemmell.com/2008/12/08/what-have-you-tried/" and xpath="//h1" and class="entry-title"';
var url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json&callback=??";
$.getJSON(url,function(data){
alert(data.query.results.h1.content);
})
You could of course build your own on your server that returns plain html rather than json.
The answer is no, you cannot trick it or force it to load html from an external source. GetJSON only works on servers that serve JSONP, and only valid JSON objects are able to be read.
You can retrieve any JSON object that you have access to with GetJSON. Here is an example with Razor an MVC Controller.
jQuery Code
$(function () {
$.getJSON('#Url.Action("GetColorsJson", "Json")', function (jsonData) {
var css = new customContentJs.css.apply(jsonData);
});
});
Controller Code
using System.Web.Mvc;
using DAL;
using Newtonsoft.Json;
public class JsonController : Controller
{
private readonly CustomContentContext _db = new CustomContentContext();
/// <summary>
/// Return a json serialized object of user saved colors
/// </summary>
/// <returns></returns>
public string GetColorsJson()
{
return JsonConvert.SerializeObject(_db.Site.Include("Colors"));
}
}

Categories