Can I create xml using jQuery or use server side? - javascript

Is it possible to create an xml file using jQuery or will I have to use server side functions?

JQuery is a javascript library which runs on the client side/browser. To write to the server you need to use a server side tool. ex. ASP, Python, Php.

You can create xml content for your xml file and then set it in href as base64.
Check this thread:
How to create a dynamic file + link for download in Javascript?

Use jquery ajax to send some data to a server page (ASP.NET/ PHP) and create the XML there.
The below sample makes a call to an ASP.NET MVC action method where i am creating an XML document using the data passed and saving it the disk.I am using the LINQtoXML API for this example
$.post("Home/CreateXML", { name : "Angel", age : "22" } function(data){
alert("Response from server is : "+data);
});
And in your Server side,
public ActionResult CreateXML(string name,string age)
{
XElement elm=new XElement("SomeXML",
new XElement("Name",name),
new XElement("Age",age));
elm.Save("C:\\somexml.xml")
return Content("XML Created and saved in disk!");
}
Executing this will create an XML in this form
<SomeXML>
<Name>Angel</Name>
<Age>Angel</Age>
</SomeXML>

Related

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.

Call Sitecore controller method from JavaScript (MVC)

I have a controller with a function ShowEvents(EventCategory eventCategory). Is it possible to call this function from client-side JavaScript? I know that I can retrieve items from the database using the Sitecore.Services.Client (SCC), but is it possible to actually access methods? Maybe through the controller rendering, if that's possible?
Here is an example of a method I want to call:
public class EventListController : Controller
{
public ActionResult ShowEvents(EventCategory eventCategory)
{
var repository = new EventListRepository();
var eventPages = repository.GetEvents(eventCategory);
var eventListViewModel = repository.GetEventListViewModel(eventPages);
return View("/Some/Path/, eventListViewModel);
}
}
This is on Sitecore 7.5 MVC
You can Post to controllers from the client side using the format
/api/sitecore/{yourcontroller}/{action} in your case this would be /api/sitecore/eventlist/showevents passing the eventCategory as the data.
yes you can reach every function with
A separate view page named with same name of it and the view pages
will be written with RAZOR language which is composed of c# and html
and surely you can write javascript within the html code.
with the Asp.net and MVC5
here an example :::
http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started
You can use the below format for call the Action method in sitecore project.
Sitecore have own route to manage the action method which is used as API. You can use it for Ajax call from the fronted.
/api/Sitecore/{controller Name}/{action method name}
Just post your data as request in data object and cosume the url in above format. It's act like API.

How to Call Variable from Java to HTML?

I would like to call some variable (code and name -- String) from java class on html class (<label>). And I wonder whether it can be directly applied (without using jsp)? Or it necessary to use javascript?
And if it requires javascript I have added the code below, but it's not working.
<script type="text/javascript">
document.getElementById("lists").innerHTML = name;
</script>
And also this is my java file that store variable code and name.
List<Names> nameList = Common.getNameList(data.getName());
for (int i = 0; i < nameList.size(); i++) {
System.out.println(nameList.get(i).code + "=" + whsList.get(i).name);
}
And in HTML I had,
<div id="lists">
<label>Code<label>
<label>Name<label>
</div>
Please help. Thank you.
No, you can't directly. JavaScript is executed on the client side (browser)
JavaScript is client side scripting lang. and 'Java' run on server side. so you need to send request to server . if you want to use java lang on server side then we need to use servlet or framework like a spring, struts etc.
if you want to use java variable in client side JavaScript then send request to server. you can send request using ajax and send nameList in JSON type from servlet as response then all list available to use in JavaScript ... so you need to refer some example like ...
new link i hope this help
http://www.technicalkeeda.com/jquery/spring-framework-jquery-ajax-request-and-json-response-example

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"));
}
}

Build a Javascript Widget : can I call an aspx?

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.

Categories