Information Bar appears in IE8 while downloading - internet-explorer-8

I have an application in which there are options to Export the document in Word/PDF format. We do a form submit to post the HTML and send it to the server for conversion. In the back-end the servlet writes it back to client after setting a contentType. The Information Bar appears during the first download only.
I cannot recommend users to reduce their Browser Security levels. Hence i need a solution to by-pass this alert. I saw that Google Docs has handled this. Does anyone have an idea about what needs to be done ?

I'm using the following JQuery code:
$.download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : $.param(data);
//split params into form inputs
var inputs = '';
$.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
//send request
$('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove();
};
};
And each time download should be initiated, I'm firing
$.download(options);
Server response is with proper content-type headers (e.g. Word).
Maybe you have forgotten to remove submitted form from the DOM?

Related

How to avoid multipart/form-data with XMLHTTPRequest and FormData

I'm trying to setup an html form, the form action is an aws lambda function.
When I submit the form via plain html, all is well. However, when I'm sending the form via XMLHTTPRequest + FormData the lambda function breaks.
Looking at the lambda logs it seems that when using the plain html form send, the form is encoded in the request body as straight forward query string ('name=Johnny&email=john%40bon.com' etc) which my lambda function can parse.
However, when using XMLHTTPRequest+FormData to send the form, the form is encoded in using a different format which I believe (not sure) is called multipart/form-data (has these WebKitFormBoundaryXXX additions).
Is there a way to make XMLHTTPRequest+FormData send the form in the same format as is used when sending the form via plain html. Alternatively, how to do parse this multipart/form-data format in aws lambda python.
const form = document.querySelector('#my-form-id')
form.addEventListener('submit', event => {
// disable default action
event.preventDefault()
// configure a request
const xhr = new XMLHttpRequest()
xhr.open('POST', 'www.myurl.com/submit')
// prepare form data
let data = new FormData(form)
// set headers
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// send request
xhr.send(data)
// listen for `load` event
xhr.onload = () => {
console.log(xhr.responseText)
}
})```
Is there a way to make XMLHTTPRequest+FormData send the form in the same format as is used when sending the form via plain html.
Well. It does… for a value of plain HTML with enctype='multipart/form-data'.
If you want to send application/x-www-form-urlencoded data then FormData is the wrong tool for the job.
Use URLSearchParams instead.
You can initialise it with a FormData object.
const data = new URLSearchParams(new FormData(document.querySelector('form')));
console.log(`${data}`);
<form>
<input name=foo value=bar>
<input name=x value=y>
</form>
Note that XMLHttpRequest can infer the Content-Type header when you pass a URLSearchParams or FormData object to send() so don't set it manually. That is just a waste of time and an opportunity to introduce errors.
Quentin's solution works. Here's the corrected code:
form.addEventListener('submit', event => {
// disable default action
event.preventDefault()
// configure a request
const xhr = new XMLHttpRequest()
xhr.open('POST', 'www.myurl.com/submit')
// send request
xhr.send(new URLSearchParams(new FormData(form)))
// listen for `load` event
xhr.onload = () => {
console.log(xhr.responseText)
}
})```

AJAX response returns current page

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

Set Session value from JavaScript and Get Session value in C#

Is it available to set the value from javascript(Session / ViewState) and get the value in C# without using hidden field??
Its work to store the value from javascript , and available to get the value in C# (page.request["Token"]) , but its not working for me because there have a postback action " form.submit();"
function setToken(Token) {
try {
var form = document.createElement("form");
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'Token');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} catch (err) {
}
}
If you want to submit a value from your clientside code to your serverside code, you'll need to submit it in some kind of request. A form post would be one way, but if you don't want the page to reload it could equally well be an AJAX request:
function setToken(accessToken) {
$.post('/SetToken', { Token: accessToken });
}
Using jQuery there as it'll save you a lot of the trouble involved in getting AJAX to work the same way across browsers.
In the example I'm posting a request to a page called /SetToken, which could be any url in your website where you have code that can update the token. Your own example submits a form without an action, which means it'll submit to the current page. You could easily do that as well
$.post(location.href, { Token: accessToken });

Ajax send parameters through url

I'm new with ajax and thought i'd be a fun experiment to put into my project. I've created my own lightbox type feature to send a message on a website I'm creating. When the user clicks "Send Message", that's when the lightbox appears, and at the top I'm trying to get it to say "Send message to User", where User is the name of the user they're sending a message too. My lightbox html elements are actually on a seperate webpage, which is why I'm using ajax. this is what I have so far, and can't seem to figure out what the problem is:
user.php page
<div id = "pageMiddle"> // This div is where all the main content is.
<button onclick = "showMessageBox(UsersName)">Send Message</button>
</div>
Note: The username passes correctly into the javascript function, I have checked that much.
main.js page
function showMessageBox(user){
alert(user); // where i checked if username passes correctly
var ajaxObject = null;
if (window.XMLHttpRequest){
ajaxObject = new XMLHttpRequest();
}else if (window.ActiveXObject){
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (ajaxObject != null){
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.send("u="+user);
}else{
alert("You do not have a compatible browser");
}
ajaxObject.onreadystatechange = function(){
if (ajaxObject.readyState == 4 && ajaxObject.status == 200){
document.getElementById("ajaxResult").innerHTML = ajaxObject.responseText;
// use jquery to fade out the background and fade in the message box
$("#pageMiddle").fadeTo("slow", 0.2);
$("#messageFormFG").fadeIn("slow");
}
};
}
message_form.php page
<div id = "messageFormFG">
<div class = "messageFormTitle">Sending message to <?php echo $_GET['u']; ?></div>
</div>
Note: When accessing this page directly through the URL, giving it a parameter of u and a value, it displays correctly
Use jQuery.ajax();
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
url: "message_form.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
freakish way to do it (old school) :)
anyway i think the problem may be that you are loading an entire html page to a div! meaning tags and stuff, a good way to understand what's wrong would be to use a debugger and see what comes in ajaxObject.responseText.
Hope this helps.
Btw convert to jQuery ajax!! saves you loads of time =)
I believe that you need to add a request header prior to sending your data. So you'd have this:
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxObject.send("u="+encodeURIComponent(user));
Instead of what you have.
However, it may be a good idea to allow a library to do this for you. It looks like you already have jQuery loaded, so why not let it handle your AJAX requests instead?
I figured it out after watching some ajax tutorials from bucky :) aka thenewboston. If I'm using the GET method, i just had to add the parameter to the end of the url in the .open function, instead of passing it through the send function (like you would a post method).
if you want to send number of field values using ajax.you can use serilalize function.
Example:
jQuery.ajax({
url: 'filenamehere.php',
type: 'post',
data: $("#formidhere").serialize(),
success: function(data){
..//
}
});

How do I send arbitrary JSON to node.js without a page reload?

My ultimate goal is to send an arbitrary JSON to node.js when a button is clicked. I currently only know how to send input from a form. Here's some code I put together to send form information:
function postForm() {
$('form').submit(function(e) {
e.preventDefault(); // no page reload
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data) { console.log('Code for handling response here.') },
'json'
);
});
}
Where the HTML looks like:
<form action='/send' method='post'>
<input name= "foo" type="radio" value=1>
<input type="submit" value="Submit">
</form>
And the relevant express/node.js code looks like:
app.post('/send', function(request, response) {
fs.appendFile('test.txt', JSON.stringify(request.body) + '\n', function(e) {
if(e) throw e;
console.log(request.body);
});
});
However, I don't know how to adapt this example to use data that is not from form input. To give context, I'm building a web-based user study, and I want to send various information collected about the user to node.js. I've tried variants of what was working for the form submission, but none of my attempts have been successful. My impression was that I could just swap out $(this).serialize() to any other data that the client can access, but I couldn't get this line of thought to work. I also tried altering some of the many .ajax() examples, but those always redirected the page which is undesirable, since my study will lose user-state information if the page refreshes.
I've done decent amount of client and server side programming, but I have next to no knowledge about how ajax works, which is proving rather problematic for solving this! And also rather silly since, often times, that's what glues the two together :)
Since you're using jQuery, sending data is simple – call $.post(url, data) from the button's click handler:
$('#somebutton').click(function() {
var data = { key: 'value', ... };
$.post('/send', data, function(res) {
// success callback
});
});
The browser will POST to url with a URL-encoded serialization of the data argument.
POST /send HTTP/1.1
Content-Type: application/x-www-form-urlencoded
...
key=value&...
Which Express' bodyParser will have no trouble with. Alternatively, you can tell jQuery to send a JSON serialization of data:
$.post('/send', data, function(res) {}, 'json');
In your case, it really doesn't matter how jQuery transmits the data (URL encoded or JSON), since bodyParser automatically deserializes both formats.

Resources