JOHN CULVINER FILE DOWNLOAD with dynamic form not working - java

I have a dynamic form on submit I call the plugin like below
var method = "post"; // Set method to post by default if not specified.
var path = "downloadExcel.obj";
var formDownload = document.createElement("form");
formDownload.setAttribute("method", method);
formDownload.setAttribute("action", path);
formDownload.setAttribute("id", "fileDownloadForm");
var custhiddenField = document.createElement("input");
custhiddenField.setAttribute("type", "hidden");
custhiddenField.setAttribute("name", "customerId");
custhiddenField.setAttribute("value", customerId); // VALUE IS GETTING UPDATED HERE
formDownload.appendChild(custhiddenField);
...............................................................................
//On printing the form here on console I get the updated formDownload
...........................................................................
formDownload.submit =
$.fileDownload($('#fileDownloadForm').prop('action'), {
httpMethod: "POST",
data: $('#fileDownloadForm').serialize(),
preparingMessageHtml: "We are preparing your report, please wait...",
failMessageHtml: "There was a problem generating your report, please try again."
});
Now I am able to download the file first time successfully but when I try to download second time [without refreshing the page], my variable formDownload is having the updated data but when I debug inside jquery.fileDownload [settings.data] still have the old data. Henceforth downloading the file for previous customer again and again

In the code where you say:
//re-intialize variables
var custInfoArray = ($('#customerId').val()).split("-");
var customerId = custInfoArray[0];
var regionInfoArray = ($('#regionId').val()).split("-");
.....
You don't reinitialize them. if you have them defined somewhere else, you define new variables in the function scope. Try removing var in front of customerid and other variables used in POST.
Try the following instead:
//re-intialize variables
custInfoArray = ($('#customerId').val()).split("-");
customerId = custInfoArray[0];
regionInfoArray = ($('#regionId').val()).split("-");
.....

It was a stupid mistake, correct code should be:
$.fileDownload($('#fileDownloadForm').prop('action'), {
httpMethod: "POST",
data: $(formDownload).serialize(), //this is changed
preparingMessageHtml: "We are preparing your report, please wait...",
failMessageHtml: "There was a problem generating your report, please try again."
});

Related

struts2 ajax call response always shows null

I am trying to call the struts2 action class from my jsp using ajax. I can hit the action class and able to pass the parameters to action class. But the response that comes from action class to my ajax request is always null
All setters and getters are set correctly and they are working fine when I see in debug sysouts
Action Class
#Override
#Action(value = "/search",
results = { #Result(name = "success", type="json")})
public String execute() throws ParseException
{
this.setName(this.term+": "+this.pos);
System.out.println("Name: "+Name);
JSONObject json = (JSONObject)new JSONParser().parse(Name);
return ActionSupport.SUCCESS;
}
jsp
function Search()
{
var term = document.getElementById("term").value;
var pos = document.getElementById("pos").value;
var itr = document.getElementById("itr").value;
var pri = document.getElementById("pri").value;
var atb = document.getElementById("atb").value;
var jsonData = {};
jsonData.term = term;
jsonData.pos = pos;
jsonData.itr = itr;
jsonData.pri = pri;
jsonData.atb = atb;
$.ajax({
type: "POST",
url: "search",
dataType: "json",
data: jsonData,
success: function(response){
console.log(""+response);
alert('Name: '+response.Name);
//alert('Length: '+data[0].length);
/* $.each(data[0],function(index, value){
alert("value " +value);
});*/
},
error: function(response){
alert(response);
alert(response.length);
$.each(response,function(index, value){
alert("value " + value);
});
}
});
}
I can see the response always as null. I am not sure what is going wrong, but seems the coding part is correct. Am I doing some mistake in ajax call?
As clearly explained in this answer, you need to use the JSON plugin, that will serialize the entire action (or a single root object when needed). You don't need then to do the parsing yourself, just evaluate the name variable.
To send JSON from JSP to action instead you need to use the JSON Interceptor in your stack.
Ensure you have getters and setters for everything.
Your Name variable should be name, both in Java and in Javascript. Only the accessors / mutators should use the capitalized N (getName, setName).
If the error persists, check carefully console and logfiles for errors, with devMode set to true.
Since this comment has gone too far, I've turned it into an answer :)

How to use facebook api taggable_friends by Open Graph tag friend

How to use facebook api taggable_friends by Open Graph tag friend.
my app use taggable_friends api i want to tag my friend in friends wall.
to use Mentioning friends or Tagging friends
https://developers.facebook.com/docs/opengraph/using-actions/v2.0#capabilities
And I use Open Graph doc Step by Step to try
but give me "You, or this app's Open Graph Test User, must have published this action at least once" how to setting?
https://developers.facebook.com/docs/apps/review/opengraph
On FB javascript sdk,
-* fb dashboard -> Open Graph
Create a story
List item make sure you enable the 'capabilities' features such as -tags, -user messages, -place, etc. in your action type.
-* in your js
1. call the js sdk
window.fbAsyncInit = function() {
FB.init({
appId : {YOUR_APP_ID} , // App ID
version: 'v2.0',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/sdk.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
}
3. Login into FB asking with these scopes
function Login()
{
FB.login(function(response) {
if (response.authResponse)
{
console.log(response.authResponse); // Get User Information.
} else
{
console.log('Authorization failed.');
}
},{scope: 'user_friends, publish_actions, status_update, read_stream, manage_friendlists'});// ' user_interests, user_likes, etc.. '
}
4. Get the logged user taggable_friends with a function such as:
var var friendsIDarray = [];
var user_friend_list;
function meTaggableFriends(){
FB.api(
"/me/taggable_friends",
function (response) {
if (response && !response.error) {
/* handle the result */
console.log(response)
for(var i=0; i<response.data.length; i++){
var data = response.data;
friendsIDarray.push(data[i].id);
}
user_friend_list = friendsIDarray.join();
}
}
);
5. Now, we have stored the token ids in user_friend_list for those friends we want to tag in our post
and we can use an Open Graph action like this in order to tag friends:
FB.api(
'me/{namespace}:{action}',
'post',
{
{object-type}:'http://example.com/object/', // make sure to have the apropiate og:type meta set
place:'https://example.com/place/', // open graph page with metas for location, id for a location page etc
tags: user_friend_list, // the tokens ids for those friens you wanna tag and you got on previous step
title: 'whatever',
message: 'like this, you tag friends #['+ONE_TOKEN_ID_FROM_TAGGABLE_FRIENDS+'] , #['+ONE_TOKEN_ID_FROM_TAGGABLE_FRIENDS+'] etc'
},
function(response) {
console.log(response)
}
);
you can find more information about it on:
https://developers.facebook.com/docs/opengraph/using-actions/v2.1
Hope you find it useful.
the error message "You, or this app's Open Graph Test User, must have published this action at least once" means: before you require this permission, you must call the api at least once.
I have occur this kind error before. when I require publish_actions permission, the facebook tell me this:
then I used my app call /me/feed api post a feed, then the error disappeared.
if you are the owner, developers or test users of the app, you can use these api before review approval. you can add roles for app in dashboard.

Uncaught TypeError: Cannot read property 'length' of undefined while accessing arraylist through Json Object

I am returning an array list from my struts2 action class.
When I an trying to access that Array list in my JavaScript file through JSON,
I am getting
"Uncaught TypeError: Cannot read property 'length' of undefined".
in below line json.EmpListByOffsetAndLength
See my code below. I want to display data that is in arraylist into the table in my jsp page.
alert(url);
$.ajax({
type : "POST",
cache : false,
url : url,
success : function(json) {
var table = document.getElementById("tablereload");
var rowCount = document.getElementById("tablereload").rows.length;
alert("this is row count" +rowCount);
$("#test").html('');
$.each(json.EmpListByOffsetAndLength, function(index, value) {
var row = table.insertRow(rowCount);
var i = 0;
for ( var key in value) {
var val = value[key];
alert(val);
var cell = row.insertCell(i);
var div = document.createElement('div'), // create
// DIV
// element
txt = document.createTextNode(val); // create
// text
// node
div.appendChild(txt);
cell.appendChild(div);
i++;
}
});
}
})
I think you didn't mention the dataType in ajax ...
$.ajax({
url:"",
type:"post",
dataType:"json",
success:function(outputdata){ //do somethins
console.log(outputdata);
}
});
Can you check if your selector is working properly? I suspect this line does not return a valid object:
var table = document.getElementById("tablereload");
Try this? You'll need to make sure you use the tbody tag in your table.
var rowCount = document.getElementById('tablereload').getElementsByTagName('tbody')[0].getElementsByTagName('tr').length;
Found here: Counting the number of rows in a table NOT using jquery
thanks for your help.
Issue is resolved. I actually , my arraylist in Java is EmpListByOffsetAndLength , but in console it is coming up as json object with e mpListByOffsetAndLength i.e. with small 'e' . thats why, when we are running length function over it, it was displaying cnnot read length function for underfined object.

jericho Html parser error in jsp page

I have write code as
String sourceUrlString="http://some url";
Source source=new Source(new URL(sourceUrlString));
Element INFORM = source.getElementById("main").getAllElementsByClass("game").get(i-1);
String INFORM = INFORM.replaceAll("\\s",""); //shows error here
sendResponse(resp,+INFORM);
Now i want the text fetch from Element INFORM is Neglect white space how can i do so? above mentioned String INFORM Show error Duplicate local variable INFORM);
e.g
text fetch by Element INFORM is "my name is satish"
but it must send response as
"mynameissatish"
You have the name INFORM used twice - and thats not possible!
String sourceUrlString = "http://some url";
Source source = new Source(new URL(sourceUrlString));
Element INFORM = source.getElementById("main").getAllElementsByClass("game").get(i-1);
String response = INFORM.replaceAll("\\s",""); // ! Use another name here !
sendResponse(resp, respone); // or use '+' - not shure if 1 or 2 args

Server cant handle Search Results (grails)

I have a List which shows Users
<g:form action="listUsers">
<g:select id="userListe" name="selectedUser" size="10" onchange="this.form.submit()"
from="${users.idToShow}"
value="${selectedUser.idToShow}"/>//edit: idToShow, not itToShow
</g:form>
I implemented a search function with JQuery, this one works so far
$(function() {
//When user types, start searching
$('#userSearch').keyup(function() {
$.post(search_url, { query: this.value },
//data stores the found values from server (works)
function(data) {
//first, remove all the values from the userList
$('#userListe').find('option').remove();
//split userID and Value, not important
var userArray = data.split(";");
for (var i = 0; i < userArray.length; i++) {
//split userID and Value, not important
var name = userArray[i].split(':')[0]
var id = userArray[i].split(':')[1]
/*
* This Line solves the problem. Now the Server knows it´s a User
*/
$j('#userListe').append('<option value="'+name+'">'+name+'</option>'
});
});
})
The search shows the correct User, but if I click on one (to change values for example), the server doesnt know it's a User, and just shows a null pointer exception.
I know this is kinda interdisciplinary stuff and maybe a bit to large for a support question, but Ill be happy about any small clue.
Thanks a lot, Daniel
method listUsers:
def listUsers = {
def foundUsers
def users
def selectedUser
foundUsers = User.list()
users = User.list(fetch: [User: foundUsers.IdToShow])
users.sort {it.IdToShow}
selectedUser = users.get(0)
if (params.selectedUser) {
selectedUser = User.findByIdToShow(params.selectedUser)
}
[users: users, selectedUser: selectedUser]

Categories

Resources