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/
Related
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)});
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 am submitting data with jquery ajax and receiving wrong characters on the server when using language other then English. For instance Russian or Georgian. What should I do to solve this problem and get correct unicode characters. I want to mention that form submitting works fine and I am receiving correct unicode chars but I need to use Ajax. below is the code.
$.ajax({
url: url,
data: {
nameGeo: $('#sauceNameGeo').val(),
nameEng: $('#sauceNameEng').val(),
nameRus: $('#sauceNameRus').val(),
descriptionGeo: $('#sauceDescGeo').val(),
descriptionEng: $('#sauceDescEng').val(),
descriptionRus: $('#sauceDescRus').val()
}
}).done(function(response) {
$('#sauceNameGeo').val('');
$('#sauceNameEng').val('');
$('#sauceNameRus').val('');
$('#sauceDescGeo').val('');
$('#sauceDescEng').val('');
$('#sauceDescRus').val('');
$('.table-hotdog-sauces > tbody:last').append(response);
alertify.success("Data has been saved");
});
Maybe I should use some Java APIs or something else on the front end. Any help would be appreciated.
try this?
$.ajax({
type: "POST",
url:url,
data:JSON.stringify(data),
contentType:"application/json; charset=utf-8"});
if you are using spring mvc server side:
#RequestMapping(value = "url", method = "POST", consumes = "application/json")
your method here(url is your actual url)
hope it helps
I'm attempting to use jquery to send information to a servlet and receive a response from the servlet. I know my problem is not with the servlet because when I paste the url
http://localhost:8080/WebPaymentSolution?secureToken=abcd1234569780jfhgutinjhuyikfj746534&user=Conner
I get the proper response back in the browser. Here is the complete jquery code I am using.
$.get(
"http://localhost:8080/WebPaymentSolution",
{ secureToken : 'abcd1234569780jfhgutinjhuyikfj746534', user : 'Conner' },
function( data ) {
$( '#hss_iframe' ).html( data );
}
);
I am currently not getting a response back from the servlet.
I've actually solved this problem but it only works if you have control over the servlet(server side solution). I set the header response the servlet gives back to allow access control from any origin. It's working perfectly now. Here's the line of code I added to make it work.
response.setHeader("Access-Control-Allow-Origin", "*");
I know this doesn't answer the question of how you do this from jQuery but this is the best solution for me so I am going with it.
try it with:
$.ajax({
url: url,
data: data,
type: 'get'
success: function(data){alert(data)},
dataType: dataType
});
to enshure that you are usign get instead of post
and look with firebug if what happened with the request. if you get a "Permanently Moved" in firefox you are trying to call an ajax request to another domain from wherer you script has loaded
if it is so, google:
Cross-Site-Scripting => XSS
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'