call to $.ajax from firefox extension not working - javascript

I am trying to make a firefox extension that will list all the videos on a page. I had already got it working as a normal js script (not as an extension) so I know the script works.
My problem is that the $.ajax inside my firefox extension doesn't get called at all. If I look at the error console it shows a message like "unsafe use of Jquery". I've tried searching Google and other sites but I couldn't come up with a solution.
Here's the code where the problem is:
var listMainVid = function ()
{
// Make a JSONP call. We are using JSONP instead of JSON because we have to make a cross-domain AJAX call
$.ajax({
url: vidinfo_q_url + "?jsoncallback=?", // Don't forget to put in the 'jsoncallback=' part
dataType: 'jsonp', // Make a JSONP request, have it received as text, and interpreted by jQuery as JSON: "jsonp text xml."
data: {
video_url: '' + doc.document.location
},
success: function ( data, textStatus, jqXHR ) // Keep in mind that this is just the request sending success.
{
if ( data.status === 'SUCCESS' )
{
var vid_loc = data.url, img_url=data.image_url;
if( Object.prototype.toString.call( vid_loc ) === '[object Array]' ) // Check if it's an array
vid_loc = data.url[0];
if( Object.prototype.toString.call( img_url ) === '[object Array]' ) // Check if it's an array
img_url = data.image_url[0];
addVideoToVidDiv( data.id, vid_loc, img_url );
}
else // Error
{
//alert ( " Error! Data=" + data.status );
}
afterMainVid();
},
error: function( xhRequest, ErrorText, thrownError )
{
Application.console.log( " Can't do because: " + ErrorText + ", " + thrownError );
afterMainVid();
}
});
afterMainVid();
}
Any help/pointers would be greatly appreciated.
OK, I finally figured it out on my own. This is to anyone else who might run into the same problem. Change the dataType: 'jsonp', TO dataType: 'json', And that's it! I don't know why but FF doesn't seem to support 'jsonp' calls from inside extensions. One thing to note here is that inside FF extensions, you don't need 'jsonp' anyway as the extensions are free to make cross-domain ajax calls. Hope this will help.

Have you fully installed the extension? You can't just execute the .xul file, you have to install it properly to let Firefox know you "trust" the extension before letting it do stuff like AJAX requests.

OK, as SomeKittens requested, I am answering my own question (didn't know I could do that).
The solution to the problem is to change the dataType: 'jsonp', To dataType: 'json'.
I don't know why but FF doesn't seem to support 'jsonp' calls from inside extensions. One thing to note here is that inside FF extensions, you don't need 'jsonp' anyway as the extensions are free to make cross-domain ajax calls. Hope this will help.
I've also provided the answer in the question itself.

Related

IE6 Ajax with JQuery

I'm trying to fecth data from a REST webservice into a HTML page. The problem is Internet Explorer 6 (which is my target station on XP SP3) that I'm struggling to make work.
Here's the code used :
$.ajax({
type: "GET",
contentType:"application/json; charset=utf-8",
dataType : 'json',
url: "https://jsonplaceholder.typicode.com/posts/1",
success: function(data) {
alert(data);
},
complete: function(xhr) {
alert(xhr.status+" "+xhr.responseText);
}
});
Tested on Firefox 52 ESR : both success and complete functions works.
On Chrome 49 : success works, complete is called but xhr.status is 0 and xhr.responseText is empty.
On IE6 success is not called at all and complete is called but xhr.status is 0 and xhr.responseText is undefined.
Tried what was already answered here on SOF like removing extra commas, adding dataType ... but still no success with IE6.
How can we do it once for all ?
Thanks
IE6 is ancient, it does not support CORS (not even with XDomainRequest).
There is no way to perform cross-origin RESTful HTTP requests with JavaScript in IE6.
If you want to perform a cross-origin request, then you will need to use some other (non-RESTful) approach such as JSONP.
As Quentin said, sending CORS request is not supported in IE 6/7, you could check this blog.
You could refer to the following code to use JSONP.
// Using JSONP
$.ajax({
url: "<request url>",
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
data: {
q: "select title,abstract,url from search.news where query=\"cat\"",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
Besides, please check this article:
Internet Explorer 9 and earlier ignores Access-Control-Allow headers and by default prohibits cross-origin requests for Internet Zone. To enable cross-origin access go to Tools->Internet Options->Security tab, click on “Custom Level” button. Find the Miscellaneous -> Access data sources across domains setting and select “Enable” option.

jQuery JSONP AJAX requests sometimes fail with "TypeError: Cannot call method 'done' of undefined"

I'm trying to use jQuery JSONP AJAX requests in a bookmarklet and I'm finding that the requests work on some pages, but not on others. Here's example code:
jQuery.ajax({
url: "http://echo.jsontest.com/key/value/one/two",
type: "GET",
dataType: "jsonp",
cache: false
}).done( function(data){
console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown){
console.log("errorThrown: " + errorThrown);
});
If you go to the following Amazon page:
http://www.amazon.com/dp/B00336EUTK?psc=1
And execute the above code in your console, you'll find that it works. However, if you go to this Amazon page:
http://www.amazon.com/dp/B00E5UHSYW?psc=1
And execute the above code in your console, the following error appears:
TypeError: Cannot call method 'done' of undefined
What is causing this problem and how can it be fixed?
EDIT: One interesting thing I've noticed is that on pages where the AJAX requests works, the callback parameter always seems to look like this:
callback=jQuery1640586556919850409_1390439428297
On pages where it fails, it always seems to look like this:
callback=jsonp1390439502398
I've tried this on a bunch of different Amazon pages and it seems like that behavior is consistent.
Maybe it's just a coincidence, but I thought it might be worth pointing out.
Different versions of jQuery
Believe it or not, those two pages are using different versions of jQuery.
You can determine this yourself by typing this into the console: $().jquery
the first page is running v1.6.2
the second page is running v1.2.6
Looking at the jQuery docs for jQuery.ajax()(here), it looks like it was not added to jQuery until v1.5
Hope that helps.
If you run a console.log(jQuery.ajax); in console, you'll see that the second link you referenced does not contain a done function in the jQuery.ajax class (since they are two different versions). You can do a version check and handle two different solutions depending on whether or not jQuery has that class method. This works for both links you posted:
//get the jQuery version
var version = jQuery.fn.jquery,
parts = version.split('.');
//piece together a version integer
version = parseInt(parts[0]+parts[1]+parts[2],10);
if (version >= 150) {
//new method
jQuery.ajax({
url: "http://echo.jsontest.com/keyu/value/one/two",
type: "GET",
dataType: "jsonp",
cache: false
}).done( function(data){
console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown){
console.log("errorThrown: " + errorThrown);
});
} else {
jQuery.ajax({
url: "http://echo.jsontest.com/keyu/value/one/two",
type: "GET",
dataType: "jsonp",
success: function(data){
console.log(data);
},
error: function(e){
console.log(e);
}
});
}

jQuery $.ajax works with GET but fails on POST

I've got a really weird problem on a customer's server.
I'm using code like the one posted below in several scripts.
The $.ajax configurations are almost identical (i.e. only file, data and success function change) and always use type:POST.
This works most of the times, but for the case below POST always fails.
Changing the type to GET works without a problem.
I'm a little bit clueless what happens here.
var parameter = {
password : $("#password").val()
};
$.ajax({
type : "POST",
url : "query/submit_password.php",
dataType : "xml",
async : true,
data : parameter,
success : function(aXHR) { /* ... */ },
error : function(aXHR, aStatus, aError) { alert("Error:\n" + aStatus + "\n"+ aError); }
});
This code always results with an alert "NetworkError: A network error occurred.".
Again - other cases with almost identical code work without a problem.
Chrome and Firefox dev tools report a POST error without any further explanation.
Any idea what happens here?
A few more details.
The client's site is hosted on GoDaddy
The same piece code works well on other servers
Yes, the file does exist as a GET request works
All browsers I tried this on have no blocker plugins (like adblock) installed
HTTPScoop shows the following results
(3 attempts, the red status says "Connection closed by communications partner"):
Chrome shows the following:
Almost solved.
The apache log showed a status 403 on the request.
It also showed a returned size of 0 which probably is the reason why chrome, etc. showed a failed request.
Why this happens is still not clear but it is definitely a server side configuration problem (most likely a mod_rewrite problem or sth. like that).
try add contentType: "application/json; charset=utf-8" to your ajax call
$.ajax({
type : "POST",
url : "query/submit_password.php",
contentType: "application/json; charset=utf-8",
dataType : "xml",
async : true,
data : parameter,
success : function(aXHR) { /* ... */ },
error : function(aXHR, aStatus, aError) { alert("Error:\n" + aStatus + "\n"+ aError); }
});
if it doesn't help try what benhowdle89 says, stringify(parameter).

jQuery ajax on IE8 always return error: "Type Error: Could not complete the operation due to error 80070005"

I has encountered this problem when using jquery ajax on IE8 (not happen in IE9+, Chrome or Firefox). After researching for a while, still cannot figure out what was the problem.
A bit on the background, the website was built on Yii PHP framework, jQuery version is 1.8.3 (from Yii core). Here are my code:
$.ajax ({
url: url, // url = "/webapp/vote/apicreate"
type: 'post',
cache: false,
dataType: "json",
contentType: "application/json",
data: {
video_id : video_id,
vote_num : vote_num
},
success: function(response){
alert('success'); // for demonstration only
},
error: function(xhr, textStatus, err){
if (typeof console !== "undefined") console.log(textStatus);
}
}
Okay, with this I always received "Type Error: Could not complete the operation due to error 80070005". Both 'readyState' and 'status' are 0. A bit of frustration, cos I neither know what it mean nor how to fix it. Have tried to use the pure javascript solution which yields the same result...
Last thing to note is I'm on a Mac, testing IE8 using Wine. Can it be related somehow ?
Use the following steps to troubleshoot:
Change the url value to 127.0.0.1
Use alert(response.responseText) instead of 'success'

Unable to get a simple jQuery.Ajax call to work

I'm pretty new to the web-dev world, and I'm having a bear of a time getting a simple jQuery.ajax call to work. Here is the call:
var url = "http://client.the_url.com/get_account_data.php";
$.ajax({
url: url,
dataType: 'json',
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:function (xhr, ajaxOptions, error){
alert("Error");
}
});
I can copy and paste the url into a browser and it renders what I would expect:
{
"id":"Level 3.xpusdscah",
"type":"Level 3",
"name":"xpusdscah",
"total":0,
"in":0,
"out":0
}
Instead, I get the Error alert every time. :/.
The php script I'm hitting starts with the header:
header('Content-type: application/json');
I was trying to pass params to the php script, but now I'm not even doing that. I would think this should be a 'no brainer', but if it is, then I have no brain. I'm trying to figure out how to use wireshark right now, but should I really need to use wireshark to debug a call that is as simple as it gets to a php file?
Can anyone help me? What I'm really hoping for is a "Well duh, you didn't do (insert obvious solution here)!
Thanks in advance,
Fledgling web developer
First, your callback function isn't helpful. It just shows the text "Error" every time. You want to actually display what the error is, like this:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:error(jqXHR, textStatus, errorThrown){
alert("Error:" + textStatus+ "," + errorThrown);
}
});
Your parameters for the error callback were named strangely. The documentation says the second param is a text error code, and the errorThrown is the HTTP status code provided by the web server. See the documentation here: http://api.jquery.com/jQuery.ajax/
Next, you'll want to grab a packet sniffer. This will allow you to inspect the packets going to and from the web server and see the error message that it is throwing. A good free option is Fiddler.
The data you're sending is not json.
var data = "login="+localLogin+"&pw="+localPassword+"&forAccount="+forAccount+"&forAccountType="+forAccountType+"&topAccount="+topAccount+"&fromDate="+fromDate+"&toDate="+toDate;
Should be something like this:
var data = '{"Key1":"' + Value1 + '","Key2":"' + Value2 .... + '""}';
And perhaps you should add the type as POST and content type like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: ....
try these:
inspect the Network tab on your console.
copy and paste the response and parse it in the console command line to verify the JSON is well formed.
show more verbose error description.

Categories