Ajax Axis2 communication issue - javascript

I've been trying to get result from this Ajax command but only to end up with a failure
$.ajax({
type: "get",
url: "http://[localhost]:80**/*****/getdata.jws",
data: 'method=s**&Table=empservice&Condition=%22ID_Service%22%3D'+$(this).val()+'',
success: processSuccess,
error: processError
});
function processSuccess(data, status, req) {
if (status == "success")
alert("SUCCESS");
}
function processError(data, status, req) {
alert("ERROR");
}
}
});
This is supposed to call a jws web-service and return the XML result, I've tested the URL in the browser and it returns the wanted result XML ( the URL being url concatenated to "?" and data = http://[localhost]:80/*/getdata.jws?method=s**&Table=empservice&Condition=%22ID_Service%22%3D2) I've tried also to make a variable to get $(this).val() into it before the call but nothing works help please
ps: after the call I get the alert popup containing the "ERROR" message
ps2: you probably know it but I'll say it anyway [localhost] = localhost because the website do not allow localhost in a link

Try changing your error handler to something like this so you get more info than just "ERROR". This will write the actual error to the Firebug console. Also, take a look at the Firebug console to see what is actually being sent. I am assuming you aware I am referring to Firefox with the Firebug add-on.
error : function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
TD

I found it, I need to use a proxy since AJAX calls are not allowed outside of one's domain
if your domain is localhost:80
a call from localhost:80 to localhost:8081 for example is not allowed
a call from localhost:80 to sdlksdlk.com is not allowed
only calls from localhost:80 to localhost:80 are allowed (in this example of course)

Related

AJAX requests fails whitout error

My loadView function is a somehow broken
function loadView(view){
$.get("../content/mainView.html", function(data) {
$("#content-container").html(data);
})
.done(function() {
console.log("done");
})
.fail(function(xhr, status, error) {
console.log("fail");
console.log(error);
});
}
I dont know what is wrong with me since I dont even can debug it since
console.log(error);
just gives me an empty response.
Can someone tell me whats wrong with my code and why
console.log(error);
dont give any response?
It is possible in AJAX/GET request world that you may get empty error parameter in fail scenarios.
error object is the message sent from server, In case request doesnt reached till server you may get empty response.
I would recommend to use textStatus
The three parameters are explained below respectively.
.fail(function(jqXHR , textStatus , error)......
jqXHR is a JS object
textStatus is "error"
error is "Internal Server Error", it's the error message sent by the server.
Try using the $.ajax method instead of $.get method
function loadView(view){
$.ajax({
type: "GET",
url: "../content/mainView.html", //Please put the actual url of the page
data: {NameOfData: $("#content-container").html(data)},
dataType: "text",
success: function(resultData){
//Do something
}
})
}
also is your code in $(document).ready(function(){})? If it isn't then also try putting your code into this function
Hope it helps!

jQuery post and get not returning anything, despite the network request is being sent succesfully

I have the following javascript function:
function test() {
jQuery.post("http://www.example.com/test.php", {})
.done(function(data) {
alert(data);
})
.fail( function(xhr, textStatus, errorThrown) {
console.log(xhr);
console.log(textStatus);
console.log(errorThrown);
});
}
And the test.php file reads like this:
<? echo "TEST"; ?>
When I call this function either by clicking on something on my page, either by typing it to the console, the alert is not firing, instead the fail part of the jQuery.post is being fired, where I get the following values:
xhr -> object
textStatus -> "error"
errorThrown -> ""
I've checked firefox debugers network, where I see that the request is being sent to the desired url, and the little circle at the left side gets green, which means that I get some kind of response from the server, but the transfered column is a single "-" line, and the received column is 0 bytes. If I call the page "http://www.example.com/test.php" from a browser, it works correctly.
What could be the problem, or how could I proceed on debuging this error?
Figured out the problem, see my own answer below, if anyone experiences the same error:|
Figured out the problem. I was accessing my site as example.com from the browser, and not as www.example.com where I send my ajax request. Ajax handled the request as cross-domain and that's why I didn't get an answer... dumb me...

AJAX $.ajax not working

This is my $.ajax function. volunteerDist is an array in a previous function and it calls myAjax(volunteerDis);However, the program always calls the error and complete functions, with an error message of undefined. What should I do? Thanks
admin-view-available-volunteeers.php is the filename where this is located
volunteerDist is an array that contains floats
function myAjax(volunteerDist){
$.ajax({
type:'POST',
url: 'admin-view-available-volunteeers.php',
data : ({
distance:volunteerDist
}),
success: function(){
alert('worked');
},
error :function(err){
alert('nope :( ERROR: ' + err.ErrorMessage);
},
complete : function(){
alert('thanks');
}
});
}
If your error: handler is being called, then the remote script returned an error.
Fix the script, not the JS code!
To get better debugging on error you need to update your code, this
error :function(err){
alert('nope :( ERROR: ' + err.ErrorMessage);
},
will not work - as err is a jqXHR object!
change it to this :
error: function(jqXHR, textStatus, errorThrown) {
alert("Error : " + errorThrown);
}
This will output the message sent by the server.
All the details for the params of .ajax() are documentation here
Update
Check the name of your PHP file ...
admin-view-available-volunteeers.php
has 3 es in the word volunteer ... is this the problem ?
I always get this a lot. In your admin-view-available-volunteers.php you need to make sure that you're outputting the right headers.
To do that you need to put this in your php before anything is output:
header("HTTP/1.01 200 OK");
header("Content-type: text/html");
Otherwise it is returned as a 404 to jQuery's ajax and then goes into the error and complete bits.
You may wish to try loading a different test file first, something simple that way you can test the js separately and ensure that when you hit the php script directly in your browser that there are no errors shown.
Also in the future make sure you have all these ajax calls on the same domain as your php scripts(like you do now), otherwise ajax won't work across domains without adding a "Access-Control-Allow-Origin", "*" header.

firefox ajax call returning NS_ERROR_DOM_BAD_URI or jsonp false error

In relation to can't debug hanging $.post in firefox extension
can anyone tell me why my extension https://builder.addons.mozilla.org/addon/1022928/latest/ is with this ajax call:
var url = 'http://e-ønsker.dk/wishlist/ajax/add/';
$(this).hide();
//show icon loading
$("#icon").show();
$.ajax({
type: "POST",
url: url,
data: {title:$("#txtTitle").val(), url:encodeURIComponent(taburl)},
success: function(data, textStatus) {
if(data.code > 0)
{
$("#icon").removeClass().addClass('accept');
}
else
{
$("#icon").removeClass().addClass('error');
if(data.code == '-1')
alert('kunne ikke finde din ønskeseddel på e-ønsker.dk - besøg e-ønsker.dk, og prøv derefter igen');
}
},
error: function(data, textStatus) {
alert(textStatus);
$("#icon").removeClass().addClass('error');
}
});
is returning the error NS_ERROR_DOM_BAD_URI. HttpFox says it's a 500 error which would indicate an internal error, but this exact call works from both chrome and safari in their extensions, so I'm suspecting the error to be related to firefox specifically.
UPDATE
So I added dataType: "jsonp" and that did some of the magic, now I get a 200 response, but I still get a parsererror.
Weirdest thing is that after I modify my server to accomodate JSONP jquery chooses the error method, and the xhr.statusText that I show here alert(xhr.statusText); gives me an alert with the statustext "success" why won't jquery choose the success method when it actually works??
You cannot get data from a different domain from the one you are currently on using AJAX -> http://en.wikipedia.org/wiki/Same_origin_policy
If you are using the same domain then use relative paths ... I suspect that Firefox is encoding the e-ønsker.dk part of the url - making it look like a different domain.

How do I catch jQuery $.getJSON (or $.ajax with datatype set to 'jsonp') error when using JSONP?

Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails):
jQuery.ajax({
type: "GET",
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
And also:
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
});
I've also tried adding the $.ajaxError but that didn't work either:
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
Here's my extensive answer to a similar question.
Here's the code:
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });
It seems that JSONP requests that don't return a successful result never trigger any event, success or failure, and for better or worse that's apparently by design.
After searching their bug tracker, there's a patch which may be a possible solution using a timeout callback. See bug report #3442. If you can't capture the error, you can at least timeout after waiting a reasonable amount of time for success.
Detecting JSONP problems
If you don't want to download a dependency, you can detect the error state yourself. It's easy.
You will only be able to detect JSONP errors by using some sort of timeout. If there's no valid response in a certain time, then assume an error. The error could be basically anything, though.
Here's a simple way to go about checking for errors. Just use a success flag:
var success = false;
$.getJSON(url, function(json) {
success = true;
// ... whatever else your callback needs to do ...
});
// Set a 5-second (or however long you want) timeout to check for errors
setTimeout(function() {
if (!success)
{
// Handle error accordingly
alert("Houston, we have a problem.");
}
}, 5000);
As thedawnrider mentioned in comments, you could also use clearTimeout instead:
var errorTimeout = setTimeout(function() {
if (!success)
{
// Handle error accordingly
alert("Houston, we have a problem.");
}
}, 5000);
$.getJSON(url, function(json) {
clearTimeout(errorTimeout);
// ... whatever else your callback needs to do ...
});
Why? Read on...
Here's how JSONP works in a nutshell:
JSONP doesn't use XMLHttpRequest like regular AJAX requests. Instead, it injects a <script> tag into the page, where the "src" attribute is the URL of the request. The content of the response is wrapped in a Javascript function which is then executed when downloaded.
For example.
JSONP request: https://api.site.com/endpoint?this=that&callback=myFunc
Javascript will inject this script tag into the DOM:
<script src="https://api.site.com/endpoint?this=that&callback=myFunc"></script>
What happens when a <script> tag is added to the DOM? Obviously, it gets executed.
So suppose the response to this query yielded a JSON result like:
{"answer":42}
To the browser, that's the same thing as a script's source, so it gets executed. But what happens when you execute this:
<script>{"answer":42}</script>
Well, nothing. It's just an object. It doesn't get stored, saved, and nothing happens.
This is why JSONP requests wrap their results in a function. The server, which must support JSONP serialization, sees the callback parameter you specified, and returns this instead:
myFunc({"answer":42})
Then this gets executed instead:
<script>myFunc({"answer":42})</script>
... which is much more useful. Somewhere in your code is, in this case, a global function called myFunc:
myFunc(data)
{
alert("The answer to life, the universe, and everything is: " + data.answer);
}
That's it. That's the "magic" of JSONP. Then to build in a timeout check is very simple, like shown above. Make the request and immediately after, start a timeout. After X seconds, if your flag still hasn't been set, then the request timed out.
I know this question is a little old but I didn't see an answer that gives a simple solution to the problem so I figured I would share my 'simple' solution.
$.getJSON("example.json", function() {
console.log( "success" );
}).fail(function() {
console.log( "error" );
});
We can simply use the .fail() callback to check to see if an error occurred.
Hope this helps :)
If you collaborate with the provider, you could send another query string parameter being the function to callback when there's an error.
?callback=?&error=?
This is called JSONPE but it's not at all a defacto standard.
The provider then passes information to the error function to help you diagnose.
Doesn't help with comm errors though - jQuery would have to be updated to also callback the error function on timeout, as in Adam Bellaire's answer.
Seems like this is working now:
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
I use this to catch an JSON error
try {
$.getJSON(ajaxURL,callback).ajaxError();
} catch(err) {
alert("wow");
alert("Error : "+ err);
}
Edit: Alternatively you can get the error message also. This will let you know what the error is exactly. Try following syntax in catch block
alert("Error : " + err);
Mayby this works?
.complete(function(response, status) {
if (response.status == "404")
alert("404 Error");
else{
//Do something
}
if(status == "error")
alert("Error");
else{
//Do something
}
});
I dont know whenever the status goes in "error" mode. But i tested it with 404 and it responded
you ca explicitly handle any error number by adding this attribute in the ajax request:
statusCode: {
404: function() {
alert("page not found");
}
}
so, your code should be like this:
jQuery.ajax({
type: "GET",
statusCode: {
404: function() {
alert("page not found");
}
},
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
hope this helps you :)
I also posted this answer in stackoverflow - Error handling in getJSON calls
I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question
The getJSON structure is as follows (found on http://api.jqueri.com):
$(selector).getJSON(url,data,success(data,status,xhr))
most people implement that using
$.getJSON(url, datatosend, function(data){
//do something with the data
});
where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?" and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.
You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object
(found on w3schools)
$.getJSON(url, datatosend, function(data, status, xhr){
if (status == "success"){
//do something with the data
}else if (status == "timeout"){
alert("Something is wrong with the connection");
}else if (status == "error" || status == "parsererror" ){
alert("An error occured");
}else{
alert("datatosend did not change");
}
});
This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.
Hope this helps someone still looking for an answer to this question.

Categories