I need to realize the following scenario: I have a html page, where is a button and some textboxes. When I click the button i want to create an xml from the textboxes data and send this xml to the server, than server returns this xml back as an attachment and I will have a Save As dialog and I can save this xml locally. I have the following jquery function which send the xml to the server:
function GetXml() {
var xmlData = '{"xml": "<test>test</test>"}';
var contentType = "application/json";
var eDoc = "";
$.ajax({
type: 'POST',
url: 'http://localhost/xmlservice.svc/rest/GetXmlToSave',
data: xmlData,
contentType: contentType,
success: function (result) {
alert(result);
},
error: function (result) {
alert(result);
},
async: false,
});
return result;
}
But i don't know hot to force Save As dialog from javascript with the returned xml from the server.
I can realize it with the classic submit button:
<form action='http://localhost/xmlservice.svc/rest/GetXmlToSave' method="POST" runat="server" >
<input type="submit"/>
</form>
But in this scenario I cannot create xml on the client side.
Is it possible to force Save As dialog from the javascript?
thanks.
From the answers and comments I have made a decision to use classic form submit. I will submit all form to the server and the xml will be constructed on the server side.
Some of suggested solutions looks very good, but there are some restrictions in my target production environment. E.g. there is not possible to install any external components (e.g. flash.). the solution must work also in the older IE 8 browser (i cannot use all new HTML 5 features => i cannot use jsfiddle ). And it seems, that classic javascript doesn't support save as dialog especially from the security reasons.
Related
I make a menu link with javascript. By using the parsing in php I display a menu with the help of javascript. The problem is how do I display data in accordance with the "id" which has been on the destination page.
Here's the code in index.html
function loadkategori(idnya){
$('#contentID').load('kategori.php?id='+idnya, function(){
$('#myListview').listview().listview('refresh');
});
}
$(document).ready(function(){
$.ajax({
url: 'http://localhost/fiqi/fiqi2/kuliner/www/parsing2.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
// $("#listview").append("<li><h2>"+item.namatempatnya+"<p>Kalimat</p></h2></li>");
// seharusnya menggunakan class, tidak inline function
$('#listview').append('<li data-filtertext="form checkboxradio widget checkbox input checkboxes controlgroups" onclick="loadkategori('+item.idkat+')">'+item.namakategori+'</li>');
});
// $("#listview");
// $('ul').listview('refresh');
$('#listview').listview().listview('refresh');
// $('#element').collapsibleset('refresh');
},
error: function(){
alert('Error terjadi');
}
});
});
here's the code in kategori.php
The code in kategori.php doesn't work on adobe phonegap.
I couldn't implement you code but as far as i understand, You need to use some http request function to get data from serverside php rather than using load(), go for using $.get(). That might work out as a solution to your problem.
function loadkategori(idnya){
var data = $.get('kategori.php?id='+idnya, function(data,status){
//PROCESS YOUR DATA OR CALL YOUR FUNCTION TO POPULATE YOUR LISTVIEW
});
}
Secondly you should use either xml or json data for client server communication. That would make your program simple and more efficient. You might paste your php code instead of putting screenshot so that some editing or testing can be done.
My requirement is whenever a Image is clicked a PDF should be opened on the browser. I am using Jquery ajax [POST call] to make a call to the ASP.NET MVC side and a file is returned on the response. A POST is required from the jquery side since I need to pass substantial data from client to server.
HTML Part:
<span data-id='printSettings' title='Generate PDF' class="preferenceSettings"></span>
JS Part: This is fired when the Generate PDF icon is clicked.
var textToSend = $('.microChartTable', self.element)[0];
var dataToSend = { htmlContent: textToSend.outerHTML };
$.ajax({
url: "/EADashboard/ConvertToPDF",
data: JSON.stringify(dataToSend),
type: 'POST',
contentType: 'application/json',
success: function (data) {
} // -- success ends here
});
ASP.NET Side : In my controller, I have the following code:
[HttpPost]
public FileResult ConvertToPDF(HtmContent content)
{
string fileName = Server.MapPath("~/SeedData/data.pdf");
string contentType = "application/pdf";
return new FilePathResult(fileName, contentType);
}
Now the PDF generation code is correct just that the PDF file is not been opened on the browser side. I have seen the post Return PDF to browser using JSON and MVC? but since there was no solution provided, I am posting this again. Can anyone let me know how this can be achieved ?
Thanks
Two things.
Why are you doing post via ajax and not a regular post? With a regular post your code would probably work.
If you indeed need to do it with ajax, you are receiving result in the data object on the success of the ajax call, and I do not see that you do anything with it, which is why you do not see anything happening.
Right now, I have a webapp that uses the jquery ajax to make a call (with params that change from call to call via a form) to my backend and retrieve an xml file. I want to put the xml data into a file with a different extension for a private application.
Basically I just want the user to be able to click a button, and it automatically prompts them to "open or save" a file containing the returned ajax xml data.
I've dabbled with sending a raw http header using php, but I can't figure out how to get it to work.
I'm writing all of this in javascript and jquery.
The only thing the below code does is (1)Make the Ajax Call, (2)Write the XML into an HTML page, (3) open the HTML page.
var format = function() {
$("button#format").click(function() {
$("#form").submit();
$.ajax({
url: "find",
beforeSend: function (xml) {
xml.overrideMimeType("application/octet-stream; charset=x-user-defined");
},
data: $("form#form").serialize(),
dataType: "html",
success: function(xml) {
xmlWindow = window.open("download.ivml");
xmlWindow.document.write(xml);
xmlWindow.focus();
},
error: function(request) {
$("#webdiv").html(request.responseText);
}
});
});
};
There is no need to force something like this into the AJAX paradigm, unless you need to play around with the data you retrieve before making it available for the user, then again, that should be able to be done in php. So I would do something like this:
<form id="format" action="download.ivml" target="_blank">
...
</form>
And in jquery modify the action like this
$('#format').submit(function(){
// tweaking the post data, otherwise this whole block is not needed.
return true;
});
Finally on my server use a .htaccess file to handle that weird URL download.ivml
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)download.ivml$ /path/to/where/I/process/the/request
not quite sure about the syntaxis of this last .htaccess file though.
I am developing a web application and am using jQuery to provide a good user interface for users. Therefore, I am using ajax requests and many jQuery functions.
If I disable JavaScript in the browser most of the function will not work because I am sending asynchronous ajax requests for many functions. But how can I handle this? Do I need to rewrite the code without using jQuery and ajax?
Find a below a sample button click event:
$("#renameCategory").live('click', function (event) {
if ($.trim($("#CategoryNewName").val()) == "") {
alert("Please enter a category name");
return;
}
var selectedCategory = $("#SelectedCategoryId").val();
var newCategoryName = $("#CategoryNewName").val();
var postData = { categoryId: selectedCategory, name: newCategoryName };
$.ajax({
type: "POST",
url: '#Url.Action("UpdateCategoryName", "Category")',
data: postData,
dataType: "json",
success: function (data) {
$('#' + selectedCategory).text(newCategoryName);
$("#selectedCategoryText").html(newCategoryName);
},
error: function () { alert('error') }
});
});
How can I handle this?
Ajax requests and jQuery will not work when the client has JavaScript disabled. The best way to make this work is to use the URL from the <a> tag href like so:
Click Me!
$("#renameCategory").on('click', function (evt) {
//To prevent the link from sending the default request
//call preventDefault() on the jQuery event object
evt.preventDefault();
//
if ($.trim($("#CategoryNewName").val()) == "") {
alert("Please enter a category name");
return;
}
//GET THE URL FOR THE AJAX REQUEST
var actionUrl = $(this).attr('href');
//
var selectedCategory = $("#SelectedCategoryId").val();
var newCategoryName = $("#CategoryNewName").val();
var postData = { categoryId: selectedCategory, name: newCategoryName };
$.ajax({
type: "POST",
url: actionUrl,
data: postData,
dataType: "json",
success: function (data) {
$('#' + selectedCategory).text(newCategoryName);
$("#selectedCategoryText").html(newCategoryName);
},
error: function () { alert('error') }
});
});
You will also need to check for ajax requests in your Controller like below:
public ActionResult UpdateCategoryName() {
...
if(Request.IsAjaxRequest()) {
return Json(yourData);
}
return View();
}
This way, if your user has JavaScript disabled, the link will function like a normal HTTP request. If the user has JavaScript enabled, then they will get the Ajax experience. This is called graceful degradation.
Ajax call works when javascript is enabled.
You can handle it by server-side scripting, when javascript is disabled, you must do works by post/get requests, so you have to recode your web application.
If a lot of modification is needed for your website to work without javascript, then just force the users to enable javascript. One way to notify users to enable javascript is to use the noscript tag. http://www.w3schools.com/tags/tag_noscript.asp
View stackoverflow's page source to see how they use noscript
If JavaScript is disabled in the browser, the <script> tags won't be interpreted and executed in your document, including all your jQuery and AJAX JS code. The most common way to implement interactive web application other than Javascript is Flash, so you can still have a backup plan. You can also go with the old-school server side only generated dynamic pages.
Today, however it is very rare for someone not to have JavaScript enabled, so it should not be an issue at all.
Anyway you can make use of the <noscript> html tag to display a message to these users.
<script type="text/javascript">
... Js code ...
</script>
<noscript>You have JavaScript disabled in your browser. Please enable it.</noscript>
Obviously any functionality depending on script will not work if scripting is disabled, not available or incompatible with the environment it is trying to run in.
It is considered by many to be a good strategy to develop web applications so that they work without script support. You can then add scripting to improve the workflow and efficiency, but you will do so knowing that you have a fall back to a working system available if at any point the script should not run.
The discipline of designing and implementing a good workflow based on just HTML and forms may well lead to an easier interface to script and a more efficient workflow.
All too often developers throw together some minimal HTML and CSS, then try and do everything in script. The extreme is to have a DOCTYPE, title element, one block element and one script element that does everything. Not recommended.
there is any sample showing how to use the blobstore api with ajax?
when i use forms works fine, but if i use jquery i don't know how to send the file and i get this error:
blob_info = upload_files[0]
IndexError: list index out of range
I have this code in javascript
function TestAjax()
{
var nombre="Some random name";
ajax={
type: "POST",
async:true,
//dataType:"json",
url:"{{upload_url}}",
data:"nombreEstudio="+nombre,
error: function ()
{
alert("Some error");
$("#buscando").html("");
},
success: function()
{ alert("it's ok") }
};
$.ajax(ajax);
}
When i use forms the file it's sended with a input tag (exactly like the doc's sample)
I wrote a series of posts about exactly this.
Somehow you still need to get the multipart form data request to the server... so when you're using forms, I assume your <form> tag has something like this on it: enctype="multipart/form-data", right?
When you're just sending a "POST" via ajax, you're losing that multipart request, which is where your file is.
There are some jQuery "ajax file upload" plugins out there that may help you out.
Hope this helps!
** EDIT **
I guess one thing I can add to this is usually ajax file uploads (on the client) are implemented by either creating a hidden iframe, and using that iframe to submit a form, or using a form and posting it via JavaScript.