I would like to send some data on the page to servlet
so I have written following jquery to do this
I use all data to build a json string, and directly send it to servlet
but I don't know how to get the whole data from the ajax in servlet
$("#save").click
(
function()
{
$.ajax
(
{
url:'/WebApplication1/Controller',
data:'{"name":"abc","address":"cde"}',
type:'post',
cache:false,
success:function(data){alert(data);},
error:function(){alert('error');}
}
);
}
);
if see the the Form Data segment of request headers from chrome
you will see the whole json string is the key.
Request URL:http://192.168.0.13/WebApplication1/Controller
Request Method:POST
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Charset:Big5,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:112
Content-Type:application/x-www-form-urlencoded
Host:192.168.0.13
Origin:http://192.168.0.13
Referer:http://192.168.0.13/system_admin/building.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.910.0 Safari/535.7
X-Requested-With:XMLHttpRequest
Form Dataview URL encoded
{"name":"abc","address":"cde"}:
Response Headersview source
Accept-Ranges:bytes
Connection:Keep-Alive
Content-Language:en
Content-Type:text/html; charset=iso-8859-1
Date:Wed, 15 Feb 2012 12:37:24 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1
Transfer-Encoding:chunked
Vary:accept-language,accept-charset
Look here,
data:'{"name":"abc","address":"cde"}',
Your data attribtue is wrong. It should not be a string, but a real JSON object. Remove those singlequotes.
data:{"name":"abc","address":"cde"},
This way it's available in the servlet the usual way
String name = request.getParameter("name"); // abc
String address = request.getParameter("address"); // cde
If it still doesn't work, head to How should I use servlets and Ajax? for complete kickoff examples, just in order to exclude that your actual problem is caused elsewhere.
See also:
jQuery.ajax() documentation
you can send data by ajax without any form, you can do it via GET or POST, but you have to invoke in some way the function that does the ajax petition (http request).
For example you can call your function from a link, this way:
the html:
<a href="" onClick="javascript: yourAjaxCallFunction(parameters)" >Link Text</a>
the javascript:
function yourAjaxCallFunction(parameters)
{
//this function sends the request via jquery ($().ajax)
sendHttpRequest(parameters);
//this one handles the response (process data)
processResult();
}
this link is maybe what you're looking for
ajax function in jQuery documentation
Related
I'm testing oData functinality with SAPUI5.
So far I've implemented GET & DELETE which is working fine.
No when I want to add a new Entry I get some problems.
Im sending the Create-Request like this:
var oEntry = {};
oEntry.EmailAdresse = sap.ui.getCore().getElementById("txtemail").getValue();
oEntry.Nachname = sap.ui.getCore().getElementById("txtlastname").getValue();
oModel.create("/Z_ETT_ODATASet", oEntry, function(oData, response){
alert("Success");
},
function(oError){
alert(oError);
});
This is my Request:
Accept application/json
Accept-Encoding gzip, deflate
Accept-Language en
Content-Length 54
Content-Type application/json
Cookie ZZZZZZZZ
Host XXXXXXXXXXXXXXXXXXXX
MaxDataServiceVersion 2.0
Referer http://XXXXXXXXXXXXXXXXXXXX:8007/sap/bc/ui5_ui5/sap/zhelloworld/index.html?sap-client=100&sap-ui-language=EN&sap-ui-xx-devmode=true
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
X-CSRF-Token AAAAAAAAAAAAAAAA==
dataserviceversion 2.0
sap-cancel-on-close true
sap-contextid-accept header
Also the data I want to post is mentioned in the request:
{"EmailAdresse":"testemail#test.de","Nachname":"Test"}
When I add an external Breakpoint to my SAP GUI I can see that Z_ETT_ODATASET_CREATE_ENTITY is invoked, but sadly IT_KEY_TAB has no entries.
What is wrong here - where am I losing my data ?
IT_KEY_TAB is going to give you the keys that are entered in the REST service (for example the key for the entity that you were using for GET or DELETE).
For POST and PUT requests, you want the object that is being sent, which can be retrieved using the io_data_provider->read_entry_data( ) method.
Trying to make a call and retrieve a very simple, one line, JSON file.
$(document).ready(function() {
jQuery.ajax({
type: 'GET',
url: 'http://wncrunners.com/admin/colors.json' ,
dataType: 'jsonp',
success: function(data) {
alert('success');
}
});
});//end document.ready
Here's the RAW Request:
GET http://wncrunners.com/admin/colors.json?callback=jQuery16406345664265099913_1319854793396&_=1319854793399 HTTP/1.1
Host: wncrunners.com
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2
Accept: */*
Referer: http://localhost:8888/jquery/Test.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Here's the RAW Response:
HTTP/1.1 200 OK
Date: Sat, 29 Oct 2011 02:21:24 GMT
Server: Apache/1.3.33 (Unix) mod_ssl/2.8.22 OpenSSL/0.9.7d SE/0.5.3
Last-Modified: Fri, 28 Oct 2011 17:48:47 GMT
ETag: "166a2402-10-4eaaeaff"
Accept-Ranges: bytes
Content-Length: 16
Content-Type: text/plain
Connection: close
{"red" : "#f00"}
The JSON is coming back in the response (red : #f00), but Chrome reports Uncaught SyntaxError: Unexpected token : colors.json:1
If I navigate directly to url itself, the JSON is returned and is displayed in the browser.
If I paste the contents of colors.json into JSLINT, the json validates.
Any ideas why I can't get this error and I never make it to the success callback?
EDIT - the jQuery.ajax() call above runs perfect at jsfiddle.net, and returns the alert 'success' as expected.
EDIT 2 - this URL works fine 'http://api.wunderground.com/api/8ac447ee36aa2505/geolookup/conditions/q/IA/Cedar_Rapids.json' I noticed that it returned as TYPE: text/javascript and Chrome did not throw the Unexpected Token. I've tested several other url's and the ONLY one that does not throw the Unexptected Token is the wunderground that is returned as TYPE: text/javascript.
Streams returned as text/plain and application/json are not being parsed correctly.
You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399 part to the URL (you can see this in your dump of the request).
What you're returning is JSON, not JSONP. Your response looks like
{"red" : "#f00"}
and jQuery is expecting something like this:
jQuery16406345664265099913_1319854793396({"red" : "#f00"})
If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json needs to be able to actually return a JSONP response.
If the same origin policy isn't an issue for your application, then you just need to fix the dataType in your jQuery.ajax call to be json instead of jsonp.
I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].
The one that worked for me is as follows:
1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ].
2- add a script link to it just below the normal jQuery link.
3- add the line "crossOrigin: true," to your ajax function.
Good to go! here is my working code for this:
$.ajax({
crossOrigin: true,
url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",
type : "GET",
success:function(data){
console.log(data);
}
})
I had the same problem and the solution was to encapsulate the json inside this function
jsonp(
.... your json ...
)
That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character
my JS checks if a youtube link exists on my textarea. i send the URL to a PHP file that echoes the URL back to JS, and append the result.
the issue im having, the returned data is being printed (or appended) in my case, twice.
if i typed-in a youtube link http://www.youtube.com/watch?v=iol0B-clFFM in my textarea, i send this link to getyoutube.php with status 200 OK
Request URL:<website> /getyoutube.php?url=youtube.com/watch?v=iol0B-clFFM
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
X-Requested-With:XMLHttpRequest
Query String Parametersview
url:youtube.com/watch
PHP file just echoes the URL, and this is the response i get from it.
this result will be fetched by JS and append this result to an html element. but the data being appended is being printed twice
[this is my JS]
$(document).ready(function(){
var youtube = //regex
var getUrl = $('#url');
getUrl.keyup(function() {
if (youtube.test(getUrl.val())) {
var youtube_url = getUrl.val().match(youtube)[0];
$.post("./includes/getyoutube.php?url="+ youtube_url, {
}, function(response){
$('.echotest').append(response);
});
}
});
tldr: send data to a php file via POST, and echo back the data. the data is being printed twice by my JS.
[update]
i added alert(response) and im getting 2 alerts. one after the other. it appears my success function is being looped twice? not sure why.
When you use keyup event, an event if fired on every keyup-motion, even when releasing Ctrl. Use keypress instead.
If you want to fire an event when some text is pasted in your input, use the paste event.
After searching for a while, I cannot find the answer yet.
My problem is when I call a web service function setRequestHeader, I got the error "not allowed by Access-Control-Allow-Origin".
Here is my javaScript code:
var loginController = new sap.ltst.login.loginController({controllerName: "sap.ltst.login.loginController"});
var session = loginController.login("I051486", "123456789");
var config = {};
$.ajax({
beforeSend: function(req) {
req.setRequestHeader('Authentication', 'Authentication-Token ' + session.session_token);
},
url : "http://localhost:8081/com.sap.st.gtpapi/program/"
+ this.program + "/configs",
dataType : 'json',
type : 'GET',
async : false,
success : function(data) {
config = data;
}
});
return config;
In web service side, I have a function that I can enable or disable the authentication. I tried to set the auth as false (not check the auth) then remove setRequestHeader, I got no error and the web service returns me some data.
In another way I tried to put it back, I got the error.
XMLHttpRequest cannot load http://localhost:8081/gtpapi/program/Business%20Intelligence%20platform%204.1%20(BI%20Aurora%204.1)/configs. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.
So I don't think that it's the problem of the auth because in the web service side, I disable the auth verification.
Let's move to the web service side, this is the interface:
public static final String HEADER_AUTH_TOKEN = "Authentication-Token";
#GET
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
#Path("/guid_{planId}/packages/{packId}/{results}")
public Response setPackageResult(#PathParam("planId") final String planGuid, #PathParam("packId") final String packGuid, #PathParam("results") final String results, #HeaderParam(WebServiceBase.HEADER_AUTH_TOKEN) String token);
This is the header response et request on Chrome:
Request URL:http://localhost:8081/com.sap.st.gtpapi/program/SBOP%20EXPLORER%204.1/configs
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:UTF-8,*;q=0.5
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Access-Control-Request-Headers:accept, authentication, origin
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8081
Origin:http://localhost:8080
Pragma:no-cache
Referer:http://localhost:8080/LTST_Frontend/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Response Headersview source
Allow:GET,OPTIONS,HEAD
Content-Length:0
Content-Type:text/xml
Date:Fri, 02 Aug 2013 15:44:10 GMT
Server:Apache-Coyote/1.1
I'm not sure I did some mistake whether the problem comes from javaScript or web service. Any ideas?
Put any header you want to send in the safe list:
header("Access-Control-Allow-Headers: Authentication, X-Custom-Header, .. etc");
This should be part of the CORS headers on the receiving domain.
I am using the Framey API for video recording. When I make a request I get back the json response I expect, but an error is raised:
Uncaught SyntaxError: Unexpected token :
Here's the javascript
var url = "http://framey.com/api/videos/ba9bd910-549d-012e-32f4-549a20bdfc52?
api_key=7VNKGLJZLKSASZ0FXN2TVSZQU&signature=41B08D68E0A4AC2DD91107BBD6AD08B8&time_stamp=1304447242";
$("button").click(function() {
$.ajax({
url: url,
dataType: 'json',
crossDomain: true
}).done(function() {
$(".video").html("here it is babyF!");
});
});
The url is just an example url from Framey's website, I don't know if it works. From reading this question Uncaught SyntaxError: Unexpected token :, I think that I maybe having the same problem. The selected answer to that question is
Just an FYI for people who might have the same problem -- I just had
to make my server send back the JSON as application/json and the
default jQuery handler worked fine.
I don't think I can effect the way Framey is sending me back the data, so I'm not sure how to fix this. Maybe it is something else all together? Thanks in advance and let me know if you need more information.
=========EDIT============
Here is the response from Framey that is giving me the error:
{"success":true,"video":{"name":"6d235a90-7b4b-012f-f97e-12313d297e67","filesize":1335504,"duration":20.48,"state":"uploaded","views":1,"data":{},"flv_url":"http://framey.com/videos/source/6d235a90-7b4b-012f-f97e-12313d297e67.flv","mp4_url":"http://framey.com/videos/source/6d235a90-7b4b-012f-f97e-12313d297e67.mp4","large_thumbnail_url":"http://framey.com/thumbnails/large/6d235a90-7b4b-012f-f97e-12313d297e67.jpg","medium_thumbnail_url":"http://framey.com/thumbnails/medium/6d235a90-7b4b-012f-f97e-12313d297e67.jpg","small_thumbnail_url":"http://framey.com/thumbnails/small/6d235a90-7b4b-012f-f97e-12313d297e67.jpg"}}
I think it is something about Framey putting "application/javascript" in the place where it should be saying "application/json"
============ EDIT 2 =================
Here are the headers for the response, I got these by looking at the "Network" section of the console in Chrome.
Request URL:http://www.framey.com/api/videos/32a7aaf0-7c3a-012f-37bd-12313b093125?api_key=00000000&signature=624643a3481b2a2c2bdb6c7cc29c506e&time_stamp=1536494436&callback=jQuery17202607689620926976_1336594235235&_=1336594483714
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:__utma=229279307.404664337.1336485291.1336573199.1336589854.6; __utmc=229279307; __utmz=229279307.1336485291.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _video-recorder_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFRiIlN2VjODBiYWM1NDk2MDlkYTg2ZTY0NzEzNDA5Zjg3ZGJJIhBfY3NyZl90b2tlbgY7AEZJIjE4aW5KVktxakhyVTRvVGY0RXZlNkVkMU9lV0p1NUEzR01rVzlNK1hRWEJ3PQY7AEY%3D--b9a5f6cf08d7539d2bf9ebebc83ce96b0d070615
Host:www.framey.com
Referer:http://localhost:3000/questions/1
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19
Query String Parametersview URL encoded
api_key:000000000000
signature:624643a3481b2a2c2bdb6c7cc29c506e
time_stamp:1536494436
callback:jQuery17202607689620926976_1336594235235
_:1336594483714
Response Headersview source
Cache-Control:max-age=0, private, must-revalidate
Connection:keep-alive
Content-Length:709
Content-Type:text/javascript; charset=utf-8
ETag:"5e8393861da01fa2effd911365a90e6b"
Server:nginx/1.0.10 + Phusion Passenger 3.0.11 (mod_rails/mod_rack)
Set-Cookie:_video-recorder_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFRiIlN2VjODBiYWM1NDk2MDlkYTg2ZTY0NzEzNDA5Zjg3ZGJJIhBfY3NyZl90b2tlbgY7AEZJIjE4aW5KVktxakhyVTRvVGY0RXZlNkVkMU9lV0p1NUEzR01rVzlNK1hRWEJ3PQY7AEY%3D--b9a5f6cf08d7539d2bf9ebebc83ce96b0d070615; path=/; HttpOnly
Status:200
X-Powered-By:Phusion Passenger (mod_rails/mod_rack) 3.0.11
X-Runtime:0.060476
X-UA-Compatible:IE=Edge,chrome=1
Of particular interest is the content-type header: it is text/javascript.
Where did you find that demo code (I could not find it on the Framey site)? I suspect you will run into cross-domain issues trying to use the Framey REST API from the client. Is your code on a publicly accessible server somewhere that we can take a look?