I have a .jsp file with JavaScript.
If I click to the OK button, I call a JavaScript method. This method detects an id.
I want to send this id to my servlet. In my servlet I want to get the id with getParameter(id).
I have implemented this on my local machine, and it functions well. If I deploy my source code on the sever, the JavaScript method will be called and the id will be detected, but the method doesn't send a request to my servlet.
<script language="text/javascript">
function removeLink(){
var id='';
var tmpcounter=0;
var check=0;
for (var counter = 0; counter < (document.getElementsByName("inProject[]").length); counter++) {
if (document.getElementsByName("inProject[]")[counter].checked) {
tmpcounter = tmpcounter+1;
}
}
for (var zaehler = 0; zaehler < (document.getElementsByName("inProject[]").length); zaehler++) {
if (document.getElementsByName("inProject[]")[zaehler].checked) {
check++;
if((check == tmpcounter) || (tmpcounter==1)){
id += 'id='+ document.getElementsByName("inProject[]")[zaehler].value;
}else{
id += 'id='+ document.getElementsByName("inProject[]")[zaehler].value +' OR ';
}
}
}
alert(id);
location.href='<%=request.getContextPath()%>/issues?action=uploaddeletelink&wherestatement=' + id;
close();
}
//-->
</script>
And this is my OK button:
<td align='right'><a class='funktion' href='javascript:removeLink();'>OK<IMG src="<%=request.getContextPath()%>/issuedb/system/layout/funktionpfeil.gif" width="14" height="9" border="0"></a></td>
On my server, the function will be called, and the id will be detected. The line of code below, which sends the request to my servlet, doesn't function however.
location.href='<%=request.getContextPath()%>/issues?action=uploaddeletelink&wherestatement=' + id;
Use AJAX as to call servlet. Get the response back from servlet.
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpReq.open('POST', strURL, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.onreadystatechange = function() {
if (xmlHttpReq.readyState == 4) {
alert(xmlHttpReq.responseText)
}
}
xmlHttpReq.send();
Use Jquery ajax for this purpose, this is simple and handy. All you need to do is use jquery plugin.
function removeLink(){
$.ajax({
url: "<%=request.getContextPath()%>/issues?action=uploaddeletelink&wherestatement="+id,
type: "POST",
success: function(data){
//If you want to return anything in jsp.
}
});
}
Hope this helps..
Related
I think I'm going crazy. I can't get it to work.
I simply want to check if a user has liked my page with javascript in an iFrame app.
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
This returns: False
But I'm a fan of my page so shouldn't it return true?!
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
string true string false json
formatted response of error if token
or page_id are not valid
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
You can do it in JavaScript like so (Building off of #dwarfy's response to a similar question):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
div#container_notlike, div#container_like {
display: none;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : 'http(s)://YOUR_APP_DOMAIN/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
var page_id = "YOUR_PAGE_ID";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
// 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/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div id="container_notlike">
YOU DON'T LIKE ME :(
</div>
<div id="container_like">
YOU LIKE ME :)
</div>
</body>
</html>
Where the channel.html file on your server just contains the line:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.
Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.
The basic code is rather simple:
FB.api("me/likes/SOME_ID", function(response) {
if ( response.data.length === 1 ) { //there should only be a single value inside "data"
console.log('You like it');
} else {
console.log("You don't like it");
}
});
ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:
FB.login(function(response) {
//do whatever you need to do after a (un)successfull login
}, { scope: 'user_likes' });
i use jquery to send the data when the user press the like button.
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example:
url:
http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file.
in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.
I am working on a news summarizer and one of its requirements is to display a list of article titles dynamically on a webpage using AJAX called from a database. I have been able to successfully configure the datastore(google app engine) and use the AJAX call to display article title. However, there is one big issue here. I am only able to call and show a single title. I want to run the AJAX call inside a loop so that I can display 10 news articles stored in datastore from 1 to 10 using the variable i of the loop as the unique reference.
The AJAX CODE :
function change(element) {
var xmlhttp;
var i = 1;
var param = "category=" + element + "&no=" + i; // This i is the key to my operation.
alert(param); //testing purpose
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//alert('function()');
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var div = document.getElementById('content');
div.innerHTML = '';
for (i = 1; i <=10; i++) {
var a = document.createElement('a');
a.href = "#";
a.onclick = rem.bind(null, i);
a.innerHTML = '<h2 id="theading'+i+'">'
+ xmlhttp.responseText + '</h2>'; //the title will go here.
div.appendChild(a);
div.appendChild(document.createElement('br'));
}
}
}
xmlhttp.open("POST", "/display?" + param, true);
xmlhttp.send();
}
I also request to suggest JavaScript code and not jquery, as I am unfamiliar with it. These are my humble beginnings.
UPDATE
MY SERVLET CODE:
public class ArticleHandler extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
String category=req.getParameter("category");
String number=req.getParameter("no");
int i = Integer.parseInt(number);
List<EntityArticles> articles = RegisterClass.ofy().load().type(EntityArticles.class).filter("category ",category).list();
out.write(articles); // Is this the correct way to send this list articles ?
}
}
Is this the correct way to send the list ?
10 articles in responseText, you can render html in server code to responseText(loop in server code). And then in ajax sucess you call
var div = document.getElementById('content');
div.innerHTML = xmlhttp.responseText;
I have created a fiddel for you to understand check it. Ajax Example in fiddle
Are you doing post request or get request? I'm asking this because I saw method as "POST" and parameter passed as "GET" by putting it in url. Please correct that part too in your code.
loadXMLDoc=function()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/ahmadfaizalbh/LaH8F/show/",true);
xmlhttp.send();
}
The best choice is to call the ajax one time and get 10 items.
But, if you have no alternative, you can modify the function a little:
function change(element, i){
var xmlhttp;
//var i=1;
var param = "category=" + element + "&no=" + i;
...
}
Call the function this way (10 times as you need):
for(i=1;int <= 10; i++){
change(element, i);
}
UPDATE
To make one time the ajax call, you can do:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
//append html node
//the object is xmlhttp.responseText. The loop will depend if this is json, html objects, string, etc
}
xmlhttp.open("POST", "/display?" + param, true);
xmlhttp.send();
To obtain 10 results you need (necessarily) to modify the server side script or servlet. If you cannot have access to modify the servlet, is impossible to get 10 items in a single ajax call.
if(xmlhttp) {
xmlhttp.open("GET","DokterWeek_KlantoverzichtServletAjax?" + $(this).prop("href").split("?")[1],true);//gettime will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
});
});
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera,chrome Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function handleServerResponse() {
document.getElementById("pop1").innerHTML = xmlhttp.responseText; //Update the HTML Form element
}
Hello,
I have the following problem (the code works), the xmlhttpRequest(ajax-call) refreches when I use firefox or Chrome (so it works nice). But IE 9.0+ caches the XMLHttprequest, so it never refreches. I read alot about this problem on the internet,but i really cannot find any solution to this problem.
Can anybody tell me the possibilities to fix this?
I think it is fixable with using the jquery ajax, but I don't have the brains to tune this whole script into jquery. Some say you can set the live-time to 0 but I don't find this. (I communicate my Ajax with a servlet)
Somebody knows an clear,easier solution?
Thank you very much
Once of the accepted practice is to add a random parameter to the url like the timestamp.
Add a parameter like _d to the url with the value new Date().getTime()
Ex:
xmlhttp.open("GET","DokterWeek_KlantoverzichtServletAjax?_d=" + (new Date().getTime()) + '&' + $(this).prop("href").split("?")[1], true);//gettime will be the servlet name
I'm making a website containing a book and the user should have the option to go to the next or previous chapter. Each chapter has 1 html file. I'm already using this script, but when I press the next or previous button, enter link description here tries to load this page rather than 2.html
<script type="text/javascript">
function goto(url) { window.location=url; }
var curPage = parseInt(location.href.replace(/([1-93]+)\.html/, ''))
if (curPage <= 1) {
// First page, no 'back' link
document.write('Back');
} else {
var backPage = curPage-1;
document.write("Back");
}
if (curPage >= 93) { // Replace with highest page number
// Last page, no 'next' link
document.write('Next');
} else {
var nextPage = curPage+1;
document.write("Next");
}
</script>
can you use jQuery to do something of this nature?
$('#next').click(function(e)
{
e.preventDefault()
$('#currentPage).remove();
$(#'yourDiv').load('2.html, function()
{
//more logic here
});
});
So firstly you make a directory lets say:
localhost/book/
Secondly add a few html documents in that directory (such as 1.html, 2.html, 3.html) paste in the following html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script src="code.js"></script>
<a class="prev" href="#">Load Prev page</a>
<a class="next" href="#">Load Next page</a>
Create a javascript file called code.js in the root directory and paste the following code:
$(function(){
var _href = location.pathname.split('/')[1];
var _url = location.pathname.split('/');
var _length = _url.length;
var _page = _url[_length - 1] + "";
var _current = _page.split('.')[0];
_current = parseInt(_current);
$('a.next').click(function(){
var request = location.protocol + '//' + location.hostname + '/' + _href + "/" + (_current + 1) + '.html';
$.ajax({
url: request,
type:'HEAD',
error: function()
{
// last page
},
success: function()
{
window.location = request;
}
});
});
});
Your problem is probably with your curPage variable. Try this:
curPage = location.href.substring(location.href.lastIndexOf('/') + 1);
curPage = parseInt(curPage.replace(/([1-99]+)\.html/, '$1'));
I believe your replace function is replacing everything with an empty string. This should replace the page with the number.
Updated
See code above. You need to get the page name from the URL before you use the replace function.
Forgot to put location.href in the first line.
I'm running JEE6 with glassfish v3 on NetBean6.9 and working on RESTful web service.
I have jsp file which contains javascript function below.
It basically read info from HTML input fields and convert to JSON format.
Then with onclick Ajax call, attempt to send JSON string using HTTP PUT method.
(i.e. I'm trying to UPDATE the db record using REST)
For js framework I'm using is Prototype1.7
When I test the function below, it always return 404 thus "something went wrong" alert is displayed.
According to my search Prototype above 1.5 version supports HTTP PUT/DELETE methods and to do so add _method to the request URL like what I'm doing:
var url = "/resources/inventory/" + invId + "?_method=PUT";
This will create for instance:
http://localhost:8080/NoJSF/resources/inventory/123?_method=PUT
I looked at Firebug and console showing that the request is actually POST. Not sure but I believe this is because of Prototype using POST tunneling to achieve PUT method?
Also even though Ajax is being called, my Java file with JAX-RS annotated witn #POST is not even being called (#GET version is working with separate data so this is the right file) since the first line of its method that spit message is not showing up so I suspect my Ajax statement has some bug or there is something beyond my thinking.. could anyone give me hint?
function protoAjaxPut() {
//get all fields value and store into json
var invId = document.getElementById("invIdField").value;
var invName = document.getElementById("invNameField").value;
//put info into JSON format
var jsonInput = JSON.stringify(new Array(invName));
var url = "/resources/inventory/" + invId + "?_method=PUT";
new Ajax.Request(url, {
method:'put',
postBody: jsonInput,
ContentType: 'application/json',
onSuccess: function(transport) {
var responseData = transport.responseText;
document.getElementById('putResponseText').innerHTML = responseData;
},
onFailure: function() { alert('something went wrong!')}
})
}//end protoAjaxPut
They are tunneled:
http://dobrzanski.net/2007/04/22/using-put-and-delete-methods-in-ajax-requesta-with-prototypejs/
As you already mentioned in your question, prototype averts PUT, DELETE,... requests by default. Some people (including me) think that this is stupid behavour, but since the developer doenst seem to care about that, we have to do it by editing the request-function itself (without touching our dist of prototype.js!):
Ajax.Request.prototype.request = function(url) {
this.url = url;
this.method = this.options.method;
var params = Object.isString(this.options.parameters) ?
this.options.parameters :
Object.toQueryString(this.options.parameters);
// NOTE: THE MISSING PART WAS HERE
if (params && this.method === 'get') {
// when GET, append parameters to URL
this.url += (this.url.include('?') ? '&' : '?') + params;
}
this.parameters = params.toQueryParams();
try {
var response = new Ajax.Response(this);
if (this.options.onCreate) this.options.onCreate(response);
Ajax.Responders.dispatch('onCreate', this, response);
this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);
if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();
this.body = this.method == 'post' ? (this.options.postBody || params) : null;
this.transport.send(this.body);
/* Force Firefox to handle ready state 4 for synchronous requests */
if (!this.options.asynchronous && this.transport.overrideMimeType)
this.onStateChange();
}
catch (e) {
this.dispatchException(e);
}
};
Run this code after Prototype got inited.
Now this:
new Ajax.Request('42', {method:'PUT'});
Will cause an actual HTTP PUT Request (see a jsFiddle).
Below which using raw xml rather than using prototype works.
When I use prototype ajax call, 405 method not allowed would return, not sure why.
<script type="text/javascript">
function simplePut() {
var xmlHttp = new XMLHttpRequest();
var invId = document.getElementById("invIdField").value;
var invName = document.getElementById("invNameField").value;
//put info into JSON format
var jsonInput = JSON.stringify(new Array(invId, invName));
var url = "resources/inventory/" + invId;
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//out = xmlHttp.responseText;
document.getElementById('simple').innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("put", url, true);
//xmlHttp.open("put", "resources/inventory/1", true);
//xmlHttp.setRequestHeader("Content-Type", "text/plain");
xmlHttp.setRequestHeader("Content-Type", "application/json");
xmlHttp.send(jsonInput);
}//end protoAjaxPut
</script>
...html body
<body>
<h1>Inventory page</h1>
<table border="1" cellspacing="1" cellpadding="5">
<th>id</th>
<th>amount</th>
<c:forEach items="${inventoryList}" var="inv" >
<tr>
<td>${inv.id}</td>
<td>${inv.amount}</td>
</tr>
</c:forEach>
</table>
<hr />
<h3>REST</h3>
<form method="post" action="">
Inventory ID: <input type="test" id="invIdField" readonly /><br />
Inventory Name: <input type="text" id="invNameField" /><br />
<input type="button" value="insert POST form" onclick="protoAjaxPost()" /><br />
<!-- <input type="button" value="update PUT" onclick="protoAjaxPut()" /><br /> -->
<div id="putResponseText"></div>
</form>
<button onclick="protoAjaxPut()">update PUT</button><br />
<button onclick="simplePut()">call SIMPLE PUT</button><br />
<button onclick="ajaxDelete()">HTTP DELETE</button><br />
<div id="simple"></div>
</body>
I want to thank RienNeVaPlus for his answer. I added additional override in order to post correctly with parameters and contenttype:
Ajax.Request.prototype.setRequestHeaders = function() {
var headers = {
'X-Requested-With': 'XMLHttpRequest',
'X-Prototype-Version': Prototype.Version,
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
};
if (this.method == 'post' || this.method=='put') {
headers['Content-type'] = this.options.contentType +
(this.options.encoding ? '; charset=' + this.options.encoding : '');
/* Force "Connection: close" for older Mozilla browsers to work
* around a bug where XMLHttpRequest sends an incorrect
* Content-length header. See Mozilla Bugzilla #246651.
*/
if (this.transport.overrideMimeType &&
(navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
headers['Connection'] = 'close';
}
if (typeof this.options.requestHeaders == 'object') {
var extras = this.options.requestHeaders;
if (Object.isFunction(extras.push))
for (var i = 0, length = extras.length; i < length; i += 2)
headers[extras[i]] = extras[i+1];
else
$H(extras).each(function(pair) { headers[pair.key] = pair.value });
}
for (var name in headers) {
this.transport.setRequestHeader(name, headers[name]);
}
};
Only tested for PUT method.