I am trying to send Arabic data from post request of node to Java (Glassfish server, grizzly framework, formatted to be utf-8 for request content). But the request upon receiving in the Java server shows some garbage value "ÙÙاÙبة اÙعاÙÙ " instead of Arabic text.
The request from node is:
var request = require('request');
request.post("http://localhost:8080/taJavaServer/taResponse", {json: true, body: "مواكبة العالم "}, function(err, res, body) {console.log(body);console.log(err)});
So, I dont know how to send exact same Arabic text from node's request post to Java server.
More Info
On calling the java-api via ajax (jQuery), it works fine and Arabic text is getting detected.
$.ajax({
url: "http://localhost:8080/taJavaServer/taResponse",
type: 'POST',
dataType: "JSON",
data: JSON.stringify({data: "مواكبة العالم "}),
success: function (respon) {..}...
You're not actually sending valid json, try something like this:
request.post("http://localhost:8080/taJavaServer/taResponse", {json: true, body: {data:"مواكبة العالم "}}, function(err, res, body) {console.log(body);console.log(err)});
Related
I am building a web application.
Part of this web application is an ajax request from the client-side to the server:
$.ajax({
url: url,
type: "get",
data: {
id: ID,
},
success: function(response) {
//parameter response contains the data sent back from the server
//some stuff is done to this data in the rest of this function
},
error: function() {
alert("An error occurred.");
}
});
On the server side I am using a servlet to handle the requests.
Once the data from the client is received, and some business logic has been applied to it, I want to send back a simple String.
The data string would then be handled by the following part of the ajax-function above:
success: function(response) {
//parameter response contains the data sent back from the server
//some stuff is done to this data in the rest of this function
},
My problem is this:
I know how to send data to the screen of the client:
PrintWriter out = response.getWriter();
out.println(data);
However, I don't know how to send data (not to the screen but instead) to the ajax-function, so that this ajax-function can then work with the data received from the server.
The java object "response" of class "HttpServletResponse" only provides methods such as "sendError()".
I want to send the data without printing them to the screen.
How can I do that?
*************************UPDATE********************************************
I tried to use PrintWriter to send a string back to the ajax function:
PrintWriter out = response.getWriter();
out.println("test");
... I then wanted to output the text "test" in an alert-message:
$.ajax({
url: url,
type: "get",
data: {
latitude: location.lat(),
longitude: location.lng(),
radius: 10
},
success: function(response) {
alert(response);
},
error: function() {
alert("Ein Fehler beim Abfragen der Daten ist aufgetreten.");
}
});
But instead of outputting an alert-message with content "test", the output consists of the whole html code of the JSP-Page from which the ajax-call had been sent!
Nothing gets sent to the "screen" specifically, it is all about where the request originates.
If you click on a link, the browser initiates the request, and the browser receives response and processes the output to display.
In this case, the request will originate from your ajax call, and therefore the ajax call will process the request and the content will be received in the .requestText property of the response.
You'll probably want to make sure the response content type of the HttpServletResponse object is set to "text/html", But since you're going so far as to use ajax, you might as well consider a step into using JSON as well.
function jsonData() {
$.ajax({
async: false,
url:'http://localhost:8080/libraryapi/BookTransactionController',
type: 'GET',
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
});
}
The Status is 200 Ok and the server is also responding with the json data but it is invoking the error function?
Ths Json data response from browser is:
[{"bookName":"Book","dueDate":"2015-4-8","issueDate":"2015-5-16","studentId":201},
{"bookName":"Book2","dueDate":"2015-4-8","issueDate":"2015-5-16","studentId":211}]
Even if you are working in same machine, this is happening because your API server's port and API consuming application's port is different and browsers don't allow cross domain resource sharing.
The solution is implementing CORS. For more info read Mozilla Documentation on CORS.
For your question, possible solutions are:
If your API is in Java, use:
response.addHeader("Access-Control-Allow-Origin", "*");
* in above line will allow access to all domains, For allowing access to specific domain only:
response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
If your API is using PHP language, use:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
If you are using python's Flask Microframework, use Flask-CORS
I'm trying to hit a web site endpoint from a Java servlet using HttpClient (v4.1). The endpoint expects a post request containing parameters in a JSON string, from what I can tell. I say "from what I can tell" because I have some sample jquery production code that makes successful requests to the endpoint. It looks like this:
$.ajax({
type: "POST",
url: "some/u/r/l",
data: "{'keyA':'valueA','keyB':'valueB','keyC':'valueC'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
...
So I'm trying to replicate this behavior from a Java servlet using HttpClient, but I'm getting ambiguous 500's from the server, so I must be creating the request incorrectly. Can anyone tell me exactly what jQuery is doing in the above code. I understand that using a JS object as value for data parameter will add the respective key-value pairs as URL parameters to the request, but what happens to the JSON string as in the above example? Where does it go?
The JSON string needs to be added to the request body. For HttpClient (4.1) this goes something like:
request.setEntity(new StringEntity(json, "application/json", HTTP.UTF_8));
I am doing a cross-site ajax to java data transaction(Not sure if I named that correctly, so please forgive me about that). Part of code in Java file:
BufferedReader input =
new BufferedReader(new InputStreamReader(connectionsocket.
getInputStream()));
DataOutputStream output =
new DataOutputStream(connectionsocket.getOutputStream());
...
output.writeChars("some random text");
output.close();
Also I have index.php file with some jQuery:
$(document).ready(function()
{
$("#send_data").click(function(){
$.ajax({
type: 'get',
dataType: 'text',
url: 'http://localhost:1024/'+$("#command").val(),
success: function(data) {console.log(data);},
error: function() { console.log("Error"); }
})
});
});
The command is sent correctly and received in Java side correctly. Then the request from java to ajax is 200 OK too. The output is also working. (For example if I remove output.close(), I do see in the firebug, that it is waiting for the output to be closed.)
The only problem is, no matter what I do I get no response text. It's always an empty string :(
cross-site ajax to java data transaction
and
index.php
and
Java
Implies you are violating same origin policy. You must use same host:port combination to retrieve the webpage (or at least the javascript version of the code that does AJAX) and send AJAX requests.
In other words, if your JS comes from localhost:80 and you are trying to send AJAX request to localhost:1024, you are violating security policies.
There are ways to do cross-domain AJAX like jsonp, but do you really need that? I would suggest serving jQuery code from the servlet, or eliminate PHP at all, or, even better, rewrite everything in Scala or Erlang. :)
in your code you create dataType:"xml"
try to use with text.because in your response i don't see the xml format,you're create response with format text.
$.ajax({
type: 'get',
dataType: 'text',
url: 'http://localhost:1024/'+$("#command").val(),
success: function(data) {console.log(data);},
error: function() { console.log("Error"); }
read this for option ajax request http://api.jquery.com/jQuery.ajax/
I have a URL that accepts JSON through a post method. It should return a cookie and status.
When I try the following, (the username and password should be the JSON I'm trying to send) , I get no response, any ideas?
<script>
$.post("https://login-url",{"username":"user","password":"1234567890"},
function(data){
alert("Data Loaded: " + data);
}, "JSON" );
</script>
UPDATE:
After following DavidDorward's comment my code looks like this:
<script>
$.ajax({
url: 'https://loginurl',
type: 'POST',
data: '{"username":"user","password":"1234567890"}',
contentType: 'application/json',
dataType: 'text',
success: function(msg){
alert("Data Loaded win: " + msg);}
});
</script>
To describe my error a little better, a status should be returned, and a cookie. When I load this page firefox, and watch using firebug, there is no response, and no cookie information loaded in the header. Although it does seem to hit the URL, this makes me think its still a problem with the data. Although if the username and password are incorrect it should return an error, which is doesn't. It just consistently returns "null".
And to answer mattb's question, the login URL is only expecting "username" and "password" in JSON format and string datatype
If you want to use jQuery make a POST request with a JSON body, then you have to use the ajax method rather then one of the simpler alternatives. Specify the contentType as "application/json", convert your JavaScript object to a String containing JSON before assigning it to the data property.
Your data wont be sent as JSON this way.
'dataType: The type of data expected from the server.'
http://api.jquery.com/jQuery.post/
Try:
{"json": '{"username":"user","password":"1234567890"}'}
It sounds to me like you have some sort of AJAX cross domain problem. For example, if the page you are running uses http and the url you are trying to access is using https, you will run into this problem.
The result is often what you describe: no response
http://en.wikipedia.org/wiki/Same_origin_policy
Regards,
Thomas Kahn
Change the parameter dataType to 'json'. You don't necessarily need to include contentType
dataType : 'json'