Getting data out of the company wiki using jQuery and ajax - javascript

The following javascript code gives me ">success-<", i.e. empty data. Pasting the url in my browser gives me the expected content.
$.get("http://company.tld/wiki/api.php?action=query&titles=Page%20Title&format=xml&prop=revisions&rvprop=content", function (data, status) {
alert(">" + status + "-" + data + "<");
});
It's a MediaWiki wiki. Here's the MediaWiki API specification: http://www.mediawiki.org/wiki/API:Query
Why am I not getting any data?

You might breach the ajax cross domain policy there.
Is that domain you try to access yours? better said, the one from your script?
From my experience, if you try to access data from a foreign domain, the success handler will fire regardless. But as you describe, with no data at all.

If data is an object you will receive the close results. Try use typeof data in the alert.
UPDATED:
To jAndy: In the documentation of jQuery.ajax we can read following (see http://docs.jquery.com/Ajax_Events):
success (Local Event).
This event is only called if the request was successful (no errors from the server, no errors with the data).
I just tried execute the following code
try {
$.ajax({url:"http://en.wikipedia.org/w/api.php?action=query&titles=jQuery&format=xml&prop=revisions&rvprop=content",
success: function (data, status, x) {
alert ("ok");
},
error: function (data, status, x) {
alert ("not ok");
},
dataType:"xml"});
} catch (e) {
alert ("exception");
};
where I try to use a crossdomain call. In IE I can see "exception" alert. In Chrome and Firefox: "not ok". The function success will NOT be called in case of error.
So the data from server are really an empty string ("") for the url of Tobbe.
To Tobbe: you should add the last parameter "xml" probably.

Related

Cross domain ajax call to get JSON response fails in error, JSON correctly formatted

I want to execute the following AJAX call (cross domain):
$.ajax({
type: 'GET',
url: url + "?callback=?",
contentType: 'application/json',
async: false,
jsonp: "callback",
dataType: 'jsonp',
success: function (json) {
alert("ok" + JSON.stringify(json));
},
error: function (json) {
alert("err" + JSON.stringify(json));
}
});
And I am getting this alert message:
err{"readyState":4,"status":200,"statusText":"success"}
Which means the code ends in the error method.
If I check the request in Firefox or Chrome, the JSON part of the response is available and clearly formatted. Is it possible to get the JSON response in the error method? Or do you have any idea why the success method isn't hit?
It's not my server unfortunately, so I can't implement any changes on the server side. I used http://jsonlint.com/ to validate the JSON output and it is Valid. Entering the same URL in the browser returns the JSON content correctly.
Thanks much in advance,
I tried a few different approaches, but still failing on the error method,
[EDIT]
SO, I am playing with different approaches, always getting the same error. If I change the error part of my call to this:
error: function (jqXHR, textStatus, ex) {
console.log(arguments);
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
Then I am getting the following error:
http://i.stack.imgur.com/ck6Sd.png
Copy paste of error for search engines:
0: Object
1: "parsererror"
2: Error
message: "jQuery11020553141210693866_1392367304225 was not called"
stack: (...)
get stack: function () { [native code] }
set stack: function () { [native code] }
proto: d
callee: function (jqXHR, textStatus, ex) {
length: 3
proto: Object
The same things apply as above, the response is readable in the browser without issues.
EDIT2
I ended up doing the JSON call the old way, embedding it into the page:
script = document.createElement("script");
script.type = "text/javascript";
script.id = "resultJSON";
script.src = url;
$(".resultsOutput").append(script);
But I have troubles retrieving the data, the script tag seems to be empty. I am getting an error on the JSON:
Uncaught SyntaxError: Unexpected token :
Anyone able to help? I am starting to get desperate on this one. It seems that the issue is that the JASON is returned without a method wrapper.
[LAST EDIT]
So, turns out the server doesn't support CORS and the returned JSON isn't wrapped in a JS function, so this approach won't work. I'll have to use some other approach to retrieve the data.. thanks everyone for reading
Andy
Is there any particular reason to:
Override random callback name jquery gives?
Set datatype to application/json?
This second one may be causing the error. If I'm correct, the server would return application/javascript mime-type, since it should return the JSON you are looking for wrapped into a callback function that shall be called once the request hast completed. Something like this:
function callback() {
return {"a","b"} //the JSON you are looking for
}
This all is handled internally by creating a tag "script" to avoid cross-domain browser restrictions, so you cannot handle JSON directly, it needs to be wrapped into Javascript code. Thus, contentType may be wrong.
Try removing the contenType property on the ajax options and see how jquery behaves (it should interpret content-type from response headers from the server).

Ajax Axis2 communication issue

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)

JQuery AJAX JSONP Invalid Label

I know this question has been asked, but I cannot get it working.
I execute the following AJAX request:
function dislikeMeme(memeId) {
$.ajax({
dataType: "jsonp",
url: "http://<url>.com/dislike/" + memeId,
data: {
u: "username",
p: "password"
},
jsonpCallback: 'successCallback'
});
}
function successCallback(data) {
alert("Test"); // Not firing because of previous 'Invalid label' error
};
Looking at firebug I see that the request was successful, but there is an Invalid Label error which fires the Error callback of the request. The response of the request is as follows:
{
"id":6220673,
"myScore":-1,
"msg":"Not loved"
}
I see that the parentheses are causing JavaScript to interpret the response as an object, but I know this is the format I am retrieving, isn't there anyway to parse this before it causes an error?
I also see that the URL of the page returning this information is:
http://<url>.com/dislike/123456?callback=successCallback&u=username&p=password&_123456789
Everything is working perfectly except this Invalid label error. Does anyone have any ideas?
Thanks in advance everyone
A server that can handle JSONP takes the callback paramater (can be different parameter depending on WS) and passes it in the response. So the response from the server should be:
successCallback({
"id":6220673,
"myScore":-1,
"msg":"Not loved"
})
If you don't have control over the server your only route is proxy. See my cross domain answer for information on getting around same origin policy.
What prevents me from using $.ajax to load another domain's html?

jQuery AJAX 200 status, yet mysterious syntax error

I have a status 200 being returned when I'm using jQuery AJAX. However, I am also getting a syntax error from somewhere. I am posting to PHP like this:
function submit_order(orderInformation) {
$.ajax({
type: 'post',
url: 'queries/submit_order.php?<?=time();?>',
data: 'orderInformation=' + JSON.stringify(orderInformation),
dataType: 'json',
success: function (returnedData) {
console.log(returnedData);
$('#content_container').fadeOut(340, function () {
var new_content = $('#content_container').clone(false);
$('#content_container').remove();
new_content.css('display', 'none');
new_content.children().remove();
new_content.appendTo('body');
$('#content_container').vkTemplate('templates/confirm_template.tmpl?<?=time()?>', returnedData, function (el, data, context) {
console.log('success');
$('#content_container').fadeIn(340);
});
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
My PHP code is pretty straightforward:
$order_information = json_decode($json_str, true);
//go through the array and make an email out of it
//add a few elements to the array
//send the email
//send back a json string with the added elements
echo json_encode($order_information);
Yet I get this:
And oddly, if I copy paste the JSON string from console.log(JSON.stringify(orderInformation)) into the PHP page:
$json_str = '{"sector_0":{"file":[],"sector_info":{"sector_label":"NIO","purchase_order":"test","proof":false},"lines":{"line_0":{"description":"test","quantity":"2","productId":"1","addressId":"20","shipViaId":"1","notes":false}}}} ';
everything works. What is this error? Where could this < seen in the error be coming from?
Thanks
It is your error handler that gets fired and logs:
xhr.status (200)
thrownError (the syntax error)
Note that $.ajax with dataType: json will fire the error handler even if the server returns 200 OK but the response is invalid JSON. The syntax error is not in your JavaScript code but in the JSON. Identify where the < is coming from and make sure that your PHP script is sending valid JSON.
Tip: open the console and look at the network tab; all XHRs are logged there along with headers and body.
200 - Is an Ok response by a server http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
You have a syntax error in your response server returns invalid json
As your PHP code seams fine, there must be something else. Syntax error or your framework returns json wrapped in html ...
Use proper tools to see what is returned by server. (firebug on firefox/ developer tools on chrome)
In your image you see 0: "<" That means that returned string starts with < - That means it is html that got returned.
Looks like you use chrome. Go to your "network" tab in chrome an you should be able to see raw response for your request.
so it is a php error:
$sector_index is not itarable. Can you var_dump it to see. what it is?
It looks like <?=time()?> isn't getting processed. Alert the URL before you post to it for verification.

Reporting syntax errors in a JSON object with jQuery and/or Javascript

What the best way to report a syntax error when I'm loading a JSON feed with jQuery? I can establish the error reporting settings like this:
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}
however this function doesn't fire when the URL I've called loads a valid page (albeit not one with a JSON object in it). Futhermore, I can't check the data that it does return because (according to Firebug at least) jQuery.getJSON breaks at the syntax error before it passes the object to the function that executes it.
The reason I'd like to report errors is because this is my way of checking whether the user has supplied a URL that will produce a valid JSON feed.
Here's a related answer that requires control over what the server will respond with.
Here's the syntax error that Firebug gives me
The syntax error Firebug gives me http://img.skitch.com/20090623-8c97g47jha4mn6adqqtjd41cwy.jpg
Any ideas? Thanks
You can bind a function to global ajaxerror events$(document).ajaxError(function(event, request, ajaxOptions, thrownError){
if ( 4==request.readyState) { // failed after data has received
alert(ajaxOptions['url'] + " did not return valid json data");
}
else {
alert("something else wnet wrong");
}
});
or use $.ajax() instead of $.getJSON()function foo() {
// $.getJSON("http://localhost/test.txt", function(data){});
$.ajax({
type: "GET",
url: "http://localhost/test.txt",
success: function (data, textStatus) {
alert("succuess");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("request failed: " + textStatus);
},
dataType: "json"
});
}
edit: But you might want to keep in mind that both ajax(dataType:"json") and getJSON() (which simply invokes .ajax(dataType:"json") boil down to data = window["eval"]("(" + data + ")") ...this might not be what you want if you don't know what (arbitrary) data your script requests. And this could explain why firebug is catching a syntax error when you feed it an html document instead of json data.
In that case better request dataType:"string" und run the data through a fully fledged json parser lib.
Thanks to all who answered. Because I was calling a JSON feed from an external domain, I wasn't able to just use jQuery's AJAX functionality and pull the feed as "text" instead of "json". jQuery only allows you to pull "json" and "script" from a remote source.
What I ended up doing instead was writing a PHP script to make the external call that lived on my own server. I use jQuery AJAX to call this, pass the requested source in the URL, and then grab that as "text." I then run my own check to ensure that it's properly formatted JSON, and then parse it with another library. jQuery doesn't have the ability to parse JSON at the moment; $.getJSON only works if you pass a URL to it.
Call the URL or the XHR request directly in your browser's address bar, do a view-source and paste the result into and IDE that understands JavaScript. You'll probably spot a misplaced quote or something.
At least you'll be able to remove chunks of it until you find the offending syntax if nothing else.
Adding to Diodeus' answer, paste your potentially offending JSON into here this tool: http://jsonformatter.curiousconcept.com/
If you have firebug, you might even be able to hack together a way to use the site a service programmatically, though that may be frowned upon.

Categories